diff -Nrc3pad gcc-3.4.0/gcc/ada/5gmastop.adb gcc-3.4.1/gcc/ada/5gmastop.adb *** gcc-3.4.0/gcc/ada/5gmastop.adb 2004-01-05 15:20:42.000000000 +0000 --- gcc-3.4.1/gcc/ada/5gmastop.adb 2004-05-12 07:28:31.000000000 +0000 *************** package body System.Machine_State_Operat *** 121,127 **** -- load/store instructions used to save/restore machine instructions. Roff : constant Character := Character'Val (o32n * Character'Pos ('4') + ! n32n * Character'Pos (' ')); -- Offset from first byte of a __uint64 register save location where -- the register value is stored. For n32/64 we store the entire 64 -- bit register into the uint64. For o32, only 32 bits are stored --- 121,127 ---- -- load/store instructions used to save/restore machine instructions. Roff : constant Character := Character'Val (o32n * Character'Pos ('4') + ! n32n * Character'Pos ('0')); -- Offset from first byte of a __uint64 register save location where -- the register value is stored. For n32/64 we store the entire 64 -- bit register into the uint64. For o32, only 32 bits are stored diff -Nrc3pad gcc-3.4.0/gcc/ada/ChangeLog gcc-3.4.1/gcc/ada/ChangeLog *** gcc-3.4.0/gcc/ada/ChangeLog 2004-04-19 01:57:55.000000000 +0000 --- gcc-3.4.1/gcc/ada/ChangeLog 2004-07-01 18:48:42.000000000 +0000 *************** *** 1,3 **** --- 1,30 ---- + 2004-07-01 Release Manager + + * GCC 3.4.1 released. + + 2004-06-09 Arnaud Charlet + + PR ada/14150 + * Make-lang.in: Clean up generation of documentation + + * gnat-style.texi, gnat_rm.texi, ug_words: Resync with AdaCore version + + * xgnatug.adb: Removed, replaced by xgnatugn.adb + + * xgnatugn.adb: Replaces xgnatug.adb + + * gnat_ug.texi: Removed, replaced by gnat_ugn.texi + + * gnat_ugn.texi: Replaces gnat_ug.texi. Resync with AdaCore version + + * gnat_ug_unx.texi, gnat_ug_vms.texi, gnat_ug_vxw.texi, + gnat_ug_wnt.texi: Removed. + + 2004-05-12 Richard Sandiford + + PR target/15331 + * 5gmastop.adb (Roff): Choose between '4' and '0', not '4' and ' '. + 2004-04-18 Release Manager * GCC 3.4.0 released. diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_rm.texi gcc-3.4.1/gcc/ada/gnat_rm.texi *** gcc-3.4.0/gcc/ada/gnat_rm.texi 2003-05-22 16:25:58.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_rm.texi 2004-06-09 09:20:43.000000000 +0000 *************** *** 28,50 **** @end direntry @copying ! Copyright @copyright{} 1995-2001, Free Software Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; ! with the Invariant Sections being ``GNU Free Documentation License'', with the ! Front-Cover Texts being ``GNAT Reference Manual'', and with no Back-Cover Texts. ! A copy of the license is included in the section entitled ``GNU ! Free Documentation License''. @end copying @titlepage - @title GNAT Reference Manual @subtitle GNAT, The GNU Ada 95 Compiler ! @subtitle GNAT Version for GCC @value{version-GCC} @author Ada Core Technologies, Inc. @page --- 28,49 ---- @end direntry @copying ! Copyright @copyright{} 1995-2004, Free Software Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; ! with the Invariant Sections being ``GNU Free Documentation License'', ! with the Front-Cover Texts being ``GNAT Reference Manual'', and with ! no Back-Cover Texts. A copy of the license is included in the section ! entitled ``GNU Free Documentation License''. @end copying @titlepage @title GNAT Reference Manual @subtitle GNAT, The GNU Ada 95 Compiler ! @subtitle GCC version @value{version-GCC} @author Ada Core Technologies, Inc. @page *************** Free Documentation License''. *** 53,114 **** @insertcopying @end titlepage @ifnottex @node Top, About This Guide, (dir), (dir) @top GNAT Reference Manual ! GNAT Reference Manual ! GNAT, The GNU Ada 95 Compiler ! ! GNAT Version for GCC @value{version-GCC} Ada Core Technologies, Inc. ! @insertcopying @menu ! * About This Guide:: ! * Implementation Defined Pragmas:: ! * Implementation Defined Attributes:: ! * Implementation Advice:: ! * Implementation Defined Characteristics:: * Intrinsic Subprograms:: * Representation Clauses and Pragmas:: ! * Standard Library Routines:: ! * The Implementation of Standard I/O:: * The GNAT Library:: ! * Interfacing to Other Languages:: ! * Machine Code Insertions:: ! * GNAT Implementation of Tasking:: ! * Code generation for array aggregates:: ! * Specialized Needs Annexes:: ! * Compatibility Guide:: * GNU Free Documentation License:: ! * Index:: --- The Detailed Node Listing --- About This Guide ! * What This Reference Manual Contains:: ! * Related Information:: The Implementation of Standard I/O ! * Standard I/O Packages:: ! * FORM Strings:: ! * Direct_IO:: ! * Sequential_IO:: ! * Text_IO:: ! * Wide_Text_IO:: ! * Stream_IO:: ! * Shared Files:: ! * Open Modes:: ! * Operations on C Streams:: ! * Interfacing to C Streams:: The GNAT Library --- 52,265 ---- @insertcopying @end titlepage + @ifnottex @node Top, About This Guide, (dir), (dir) @top GNAT Reference Manual ! @noindent GNAT Reference Manual ! @noindent ! GNAT, The GNU Ada 95 Compiler@* ! Version @value{gnat_version}@* ! Document revision level $Revision: 1.13.16.1 $@* ! Date: $Date: 2004/06/09 09:20:43 $ + @noindent Ada Core Technologies, Inc. ! @noindent ! Copyright @copyright{} 1995-2003, Free Software Foundation + @noindent + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.1 + or any later version published by the Free Software Foundation; + with the Invariant Sections being ``GNU Free Documentation License'', with the + Front-Cover Texts being ``GNAT Reference Manual'', and with no Back-Cover + Texts. A copy of the license is included in the section entitled ``GNU + Free Documentation License''. @menu ! * About This Guide:: ! * Implementation Defined Pragmas:: ! * Implementation Defined Attributes:: ! * Implementation Advice:: ! * Implementation Defined Characteristics:: * Intrinsic Subprograms:: * Representation Clauses and Pragmas:: ! * Standard Library Routines:: ! * The Implementation of Standard I/O:: * The GNAT Library:: ! * Interfacing to Other Languages:: ! * Specialized Needs Annexes:: ! * Implementation of Specific Ada Features:: ! * Project File Reference:: * GNU Free Documentation License:: ! * Index:: --- The Detailed Node Listing --- About This Guide ! * What This Reference Manual Contains:: ! * Related Information:: ! ! Implementation Defined Pragmas ! ! * Pragma Abort_Defer:: ! * Pragma Ada_83:: ! * Pragma Ada_95:: ! * Pragma Annotate:: ! * Pragma Assert:: ! * Pragma Ast_Entry:: ! * Pragma C_Pass_By_Copy:: ! * Pragma Comment:: ! * Pragma Common_Object:: ! * Pragma Compile_Time_Warning:: ! * Pragma Complex_Representation:: ! * Pragma Component_Alignment:: ! * Pragma Convention_Identifier:: ! * Pragma CPP_Class:: ! * Pragma CPP_Constructor:: ! * Pragma CPP_Virtual:: ! * Pragma CPP_Vtable:: ! * Pragma Debug:: ! * Pragma Elaboration_Checks:: ! * Pragma Eliminate:: ! * Pragma Export_Exception:: ! * Pragma Export_Function:: ! * Pragma Export_Object:: ! * Pragma Export_Procedure:: ! * Pragma Export_Value:: ! * Pragma Export_Valued_Procedure:: ! * Pragma Extend_System:: ! * Pragma External:: ! * Pragma External_Name_Casing:: ! * Pragma Finalize_Storage_Only:: ! * Pragma Float_Representation:: ! * Pragma Ident:: ! * Pragma Import_Exception:: ! * Pragma Import_Function:: ! * Pragma Import_Object:: ! * Pragma Import_Procedure:: ! * Pragma Import_Valued_Procedure:: ! * Pragma Initialize_Scalars:: ! * Pragma Inline_Always:: ! * Pragma Inline_Generic:: ! * Pragma Interface:: ! * Pragma Interface_Name:: ! * Pragma Interrupt_Handler:: ! * Pragma Interrupt_State:: ! * Pragma Keep_Names:: ! * Pragma License:: ! * Pragma Link_With:: ! * Pragma Linker_Alias:: ! * Pragma Linker_Section:: ! * Pragma Long_Float:: ! * Pragma Machine_Attribute:: ! * Pragma Main_Storage:: ! * Pragma No_Return:: ! * Pragma Normalize_Scalars:: ! * Pragma Obsolescent:: ! * Pragma Passive:: ! * Pragma Polling:: ! * Pragma Propagate_Exceptions:: ! * Pragma Psect_Object:: ! * Pragma Pure_Function:: ! * Pragma Ravenscar:: ! * Pragma Restricted_Run_Time:: ! * Pragma Restriction_Warnings:: ! * Pragma Source_File_Name:: ! * Pragma Source_File_Name_Project:: ! * Pragma Source_Reference:: ! * Pragma Stream_Convert:: ! * Pragma Style_Checks:: ! * Pragma Subtitle:: ! * Pragma Suppress_All:: ! * Pragma Suppress_Exception_Locations:: ! * Pragma Suppress_Initialization:: ! * Pragma Task_Info:: ! * Pragma Task_Name:: ! * Pragma Task_Storage:: ! * Pragma Thread_Body:: ! * Pragma Time_Slice:: ! * Pragma Title:: ! * Pragma Unchecked_Union:: ! * Pragma Unimplemented_Unit:: ! * Pragma Universal_Data:: ! * Pragma Unreferenced:: ! * Pragma Unreserve_All_Interrupts:: ! * Pragma Unsuppress:: ! * Pragma Use_VADS_Size:: ! * Pragma Validity_Checks:: ! * Pragma Volatile:: ! * Pragma Warnings:: ! * Pragma Weak_External:: ! ! Implementation Defined Attributes ! ! * Abort_Signal:: ! * Address_Size:: ! * Asm_Input:: ! * Asm_Output:: ! * AST_Entry:: ! * Bit:: ! * Bit_Position:: ! * Code_Address:: ! * Default_Bit_Order:: ! * Elaborated:: ! * Elab_Body:: ! * Elab_Spec:: ! * Emax:: ! * Enum_Rep:: ! * Epsilon:: ! * Fixed_Value:: ! * Has_Discriminants:: ! * Img:: ! * Integer_Value:: ! * Large:: ! * Machine_Size:: ! * Mantissa:: ! * Max_Interrupt_Priority:: ! * Max_Priority:: ! * Maximum_Alignment:: ! * Mechanism_Code:: ! * Null_Parameter:: ! * Object_Size:: ! * Passed_By_Reference:: ! * Range_Length:: ! * Safe_Emax:: ! * Safe_Large:: ! * Small:: ! * Storage_Unit:: ! * Target_Name:: ! * Tick:: ! * To_Address:: ! * Type_Class:: ! * UET_Address:: ! * Unconstrained_Array:: ! * Universal_Literal_String:: ! * Unrestricted_Access:: ! * VADS_Size:: ! * Value_Size:: ! * Wchar_T_Size:: ! * Word_Size:: The Implementation of Standard I/O ! * Standard I/O Packages:: ! * FORM Strings:: ! * Direct_IO:: ! * Sequential_IO:: ! * Text_IO:: ! * Wide_Text_IO:: ! * Stream_IO:: ! * Shared Files:: ! * Open Modes:: ! * Operations on C Streams:: ! * Interfacing to C Streams:: The GNAT Library *************** The GNAT Library *** 116,130 **** --- 267,287 ---- * Ada.Characters.Wide_Latin_1 (a-cwila1.ads):: * Ada.Characters.Wide_Latin_9 (a-cwila9.ads):: * Ada.Command_Line.Remove (a-colire.ads):: + * Ada.Command_Line.Environment (a-colien.ads):: * Ada.Direct_IO.C_Streams (a-diocst.ads):: * Ada.Exceptions.Is_Null_Occurrence (a-einuoc.ads):: + * Ada.Exceptions.Traceback (a-exctra.ads):: * Ada.Sequential_IO.C_Streams (a-siocst.ads):: * Ada.Streams.Stream_IO.C_Streams (a-ssicst.ads):: * Ada.Strings.Unbounded.Text_IO (a-suteio.ads):: * Ada.Strings.Wide_Unbounded.Wide_Text_IO (a-swuwti.ads):: * Ada.Text_IO.C_Streams (a-tiocst.ads):: * Ada.Wide_Text_IO.C_Streams (a-wtcstr.ads):: + * GNAT.Array_Split (g-arrspl.ads):: * GNAT.AWK (g-awk.ads):: + * GNAT.Bounded_Buffers (g-boubuf.ads):: + * GNAT.Bounded_Mailboxes (g-boumai.ads):: + * GNAT.Bubble_Sort (g-bubsor.ads):: * GNAT.Bubble_Sort_A (g-busora.ads):: * GNAT.Bubble_Sort_G (g-busorg.ads):: * GNAT.Calendar (g-calend.ads):: *************** The GNAT Library *** 134,148 **** --- 291,311 ---- * GNAT.CGI.Cookie (g-cgicoo.ads):: * GNAT.CGI.Debug (g-cgideb.ads):: * GNAT.Command_Line (g-comlin.ads):: + * GNAT.Compiler_Version (g-comver.ads):: + * GNAT.Ctrl_C (g-ctrl_c.ads):: * GNAT.CRC32 (g-crc32.ads):: * GNAT.Current_Exception (g-curexc.ads):: * GNAT.Debug_Pools (g-debpoo.ads):: * GNAT.Debug_Utilities (g-debuti.ads):: * GNAT.Directory_Operations (g-dirope.ads):: + * GNAT.Dynamic_HTables (g-dynhta.ads):: * GNAT.Dynamic_Tables (g-dyntab.ads):: + * GNAT.Exception_Actions (g-excact.ads):: * GNAT.Exception_Traces (g-exctra.ads):: + * GNAT.Exceptions (g-except.ads):: * GNAT.Expect (g-expect.ads):: * GNAT.Float_Control (g-flocon.ads):: + * GNAT.Heap_Sort (g-heasor.ads):: * GNAT.Heap_Sort_A (g-hesora.ads):: * GNAT.Heap_Sort_G (g-hesorg.ads):: * GNAT.HTable (g-htable.ads):: *************** The GNAT Library *** 150,160 **** --- 313,328 ---- * GNAT.IO_Aux (g-io_aux.ads):: * GNAT.Lock_Files (g-locfil.ads):: * GNAT.MD5 (g-md5.ads):: + * GNAT.Memory_Dump (g-memdum.ads):: * GNAT.Most_Recent_Exception (g-moreex.ads):: * GNAT.OS_Lib (g-os_lib.ads):: + * GNAT.Perfect_Hash.Generators (g-pehage.ads):: * GNAT.Regexp (g-regexp.ads):: * GNAT.Registry (g-regist.ads):: * GNAT.Regpat (g-regpat.ads):: + * GNAT.Secondary_Stack_Info (g-sestin.ads):: + * GNAT.Semaphores (g-semaph.ads):: + * GNAT.Signals (g-signal.ads):: * GNAT.Sockets (g-socket.ads):: * GNAT.Source_Info (g-souinf.ads):: * GNAT.Spell_Checker (g-speche.ads):: *************** The GNAT Library *** 163,173 **** --- 331,344 ---- * GNAT.Spitbol.Table_Boolean (g-sptabo.ads):: * GNAT.Spitbol.Table_Integer (g-sptain.ads):: * GNAT.Spitbol.Table_VString (g-sptavs.ads):: + * GNAT.Strings (g-string.ads):: + * GNAT.String_Split (g-strspl.ads):: * GNAT.Table (g-table.ads):: * GNAT.Task_Lock (g-tasloc.ads):: * GNAT.Threads (g-thread.ads):: * GNAT.Traceback (g-traceb.ads):: * GNAT.Traceback.Symbolic (g-trasym.ads):: + * GNAT.Wide_String_Split (g-wistsp.ads):: * Interfaces.C.Extensions (i-cexten.ads):: * Interfaces.C.Streams (i-cstrea.ads):: * Interfaces.CPP (i-cpp.ads):: *************** The GNAT Library *** 180,185 **** --- 351,357 ---- * Interfaces.VxWorks.IO (i-vxwoio.ads):: * System.Address_Image (s-addima.ads):: * System.Assertions (s-assert.ads):: + * System.Memory (s-memory.ads):: * System.Partition_Interface (s-parint.ads):: * System.Task_Info (s-tasinf.ads):: * System.Wch_Cnv (s-wchcnv.ads):: *************** The GNAT Library *** 187,216 **** Text_IO ! * Text_IO Stream Pointer Positioning:: ! * Text_IO Reading and Writing Non-Regular Files:: ! * Get_Immediate:: * Treating Text_IO Files as Streams:: * Text_IO Extensions:: * Text_IO Facilities for Unbounded Strings:: Wide_Text_IO ! * Wide_Text_IO Stream Pointer Positioning:: ! * Wide_Text_IO Reading and Writing Non-Regular Files:: Interfacing to Other Languages * Interfacing to C:: ! * Interfacing to C++:: ! * Interfacing to COBOL:: ! * Interfacing to Fortran:: * Interfacing to non-GNAT Ada code:: ! GNAT Implementation of Tasking ! * Mapping Ada Tasks onto the Underlying Kernel Threads:: ! * Ensuring Compliance with the Real-Time Annex:: @end menu @end ifnottex --- 359,397 ---- Text_IO ! * Text_IO Stream Pointer Positioning:: ! * Text_IO Reading and Writing Non-Regular Files:: ! * Get_Immediate:: * Treating Text_IO Files as Streams:: * Text_IO Extensions:: * Text_IO Facilities for Unbounded Strings:: Wide_Text_IO ! * Wide_Text_IO Stream Pointer Positioning:: ! * Wide_Text_IO Reading and Writing Non-Regular Files:: Interfacing to Other Languages * Interfacing to C:: ! * Interfacing to C++:: ! * Interfacing to COBOL:: ! * Interfacing to Fortran:: * Interfacing to non-GNAT Ada code:: ! Specialized Needs Annexes ! Implementation of Specific Ada Features ! * Machine Code Insertions:: ! * GNAT Implementation of Tasking:: ! * GNAT Implementation of Shared Passive Packages:: ! * Code Generation for Array Aggregates:: ! ! Project File Reference ! ! GNU Free Documentation License ! ! Index @end menu @end ifnottex *************** GNAT compiler. It includes information *** 224,316 **** characteristics of GNAT, including all the information required by Annex M of the standard. ! Ada 95 is designed to be highly portable,and guarantees that, for most ! programs, Ada 95 compilers behave in exactly the same manner on ! different machines. However, since Ada 95 is designed to be used in a wide variety of applications, it also contains a number of system ! dependent features to Functbe used in interfacing to the external world. ! ! @c Maybe put the following in platform-specific section ! @ignore ! @cindex ProDev Ada ! This reference manual discusses how these features are implemented for ! use in ProDev Ada running on the IRIX 5.3 or greater operating systems. ! @end ignore ! @cindex Implementation-dependent features @cindex Portability Note: Any program that makes use of implementation-dependent features may be non-portable. You should follow good programming practice and isolate and clearly document any sections of your program that make use of these features in a non-portable manner. @menu ! * What This Reference Manual Contains:: * Conventions:: ! * Related Information:: @end menu @node What This Reference Manual Contains @unnumberedsec What This Reference Manual Contains This reference manual contains the following chapters: @itemize @bullet @item ! @ref{Implementation Defined Pragmas} lists GNAT implementation-dependent pragmas, which can be used to extend and enhance the functionality of the compiler. @item ! @ref{Implementation Defined Attributes} lists GNAT implementation-dependent attributes which can be used to extend and enhance the functionality of the compiler. @item ! @ref{Implementation Advice} provides information on generally desirable behavior which are not requirements that all compilers must follow since it cannot be provided on all systems, or which may be undesirable on some systems. @item ! @ref{Implementation Defined Characteristics} provides a guide to minimizing implementation dependent features. @item ! @ref{Intrinsic Subprograms} describes the intrinsic subprograms implemented by GNAT, and how they can be imported into user application programs. @item ! @ref{Representation Clauses and Pragmas} describes in detail the way that GNAT represents data, and in particular the exact set of representation clauses and pragmas that is accepted. @item ! @ref{Standard Library Routines} provides a listing of packages and a brief description of the functionality that is provided by Ada's extensive set of standard library routines as implemented by GNAT@. @item ! @ref{The Implementation of Standard I/O} details how the GNAT implementation of the input-output facilities. @item ! @ref{Interfacing to Other Languages} describes how programs written in Ada using GNAT can be interfaced to other programming languages. @item ! @ref{Specialized Needs Annexes} describes the GNAT implementation of all ! of the special needs annexes. @item ! @ref{Compatibility Guide} includes sections on compatibility of GNAT with ! other Ada 83 and Ada 95 compilation systems, to assist in porting code ! from other environments. @end itemize @cindex Ada 95 ISO/ANSI Standard This reference manual assumes that you are familiar with Ada 95 language, as described in the International Standard ANSI/ISO/IEC-8652:1995, Jan 1995. --- 405,501 ---- characteristics of GNAT, including all the information required by Annex M of the standard. ! Ada 95 is designed to be highly portable. ! In general, a program will have the same effect even when compiled by ! different compilers on different platforms. ! However, since Ada 95 is designed to be used in a wide variety of applications, it also contains a number of system ! dependent features to be used in interfacing to the external world. @cindex Implementation-dependent features @cindex Portability + Note: Any program that makes use of implementation-dependent features may be non-portable. You should follow good programming practice and isolate and clearly document any sections of your program that make use of these features in a non-portable manner. @menu ! * What This Reference Manual Contains:: * Conventions:: ! * Related Information:: @end menu @node What This Reference Manual Contains @unnumberedsec What This Reference Manual Contains + @noindent This reference manual contains the following chapters: @itemize @bullet @item ! @ref{Implementation Defined Pragmas}, lists GNAT implementation-dependent pragmas, which can be used to extend and enhance the functionality of the compiler. @item ! @ref{Implementation Defined Attributes}, lists GNAT implementation-dependent attributes which can be used to extend and enhance the functionality of the compiler. @item ! @ref{Implementation Advice}, provides information on generally desirable behavior which are not requirements that all compilers must follow since it cannot be provided on all systems, or which may be undesirable on some systems. @item ! @ref{Implementation Defined Characteristics}, provides a guide to minimizing implementation dependent features. @item ! @ref{Intrinsic Subprograms}, describes the intrinsic subprograms implemented by GNAT, and how they can be imported into user application programs. @item ! @ref{Representation Clauses and Pragmas}, describes in detail the way that GNAT represents data, and in particular the exact set of representation clauses and pragmas that is accepted. @item ! @ref{Standard Library Routines}, provides a listing of packages and a brief description of the functionality that is provided by Ada's extensive set of standard library routines as implemented by GNAT@. @item ! @ref{The Implementation of Standard I/O}, details how the GNAT implementation of the input-output facilities. @item ! @ref{The GNAT Library}, is a catalog of packages that complement ! the Ada predefined library. ! ! @item ! @ref{Interfacing to Other Languages}, describes how programs written in Ada using GNAT can be interfaced to other programming languages. + @ref{Specialized Needs Annexes}, describes the GNAT implementation of all + of the specialized needs annexes. + @item ! @ref{Implementation of Specific Ada Features}, discusses issues related ! to GNAT's implementation of machine code insertions, tasking, and several ! other features. @item ! @ref{Project File Reference}, presents the syntax and semantics ! of project files. ! @end itemize @cindex Ada 95 ISO/ANSI Standard + @noindent This reference manual assumes that you are familiar with Ada 95 language, as described in the International Standard ANSI/ISO/IEC-8652:1995, Jan 1995. *************** appear with the @samp{$} replaced by wha *** 360,365 **** --- 545,551 ---- @node Related Information @unnumberedsec Related Information + @noindent See the following documents for further information on GNAT: @itemize @bullet *************** compilers (although GNAT implements this *** 409,422 **** platforms). Therefore if portability to other compilers is an important consideration, the use of these pragmas should be minimized. ! @table @code @findex Abort_Defer @cindex Deferring aborts - @item pragma Abort_Defer @noindent Syntax: - @smallexample pragma Abort_Defer; @end smallexample --- 595,698 ---- platforms). Therefore if portability to other compilers is an important consideration, the use of these pragmas should be minimized. ! @menu ! * Pragma Abort_Defer:: ! * Pragma Ada_83:: ! * Pragma Ada_95:: ! * Pragma Annotate:: ! * Pragma Assert:: ! * Pragma Ast_Entry:: ! * Pragma C_Pass_By_Copy:: ! * Pragma Comment:: ! * Pragma Common_Object:: ! * Pragma Compile_Time_Warning:: ! * Pragma Complex_Representation:: ! * Pragma Component_Alignment:: ! * Pragma Convention_Identifier:: ! * Pragma CPP_Class:: ! * Pragma CPP_Constructor:: ! * Pragma CPP_Virtual:: ! * Pragma CPP_Vtable:: ! * Pragma Debug:: ! * Pragma Elaboration_Checks:: ! * Pragma Eliminate:: ! * Pragma Export_Exception:: ! * Pragma Export_Function:: ! * Pragma Export_Object:: ! * Pragma Export_Procedure:: ! * Pragma Export_Value:: ! * Pragma Export_Valued_Procedure:: ! * Pragma Extend_System:: ! * Pragma External:: ! * Pragma External_Name_Casing:: ! * Pragma Finalize_Storage_Only:: ! * Pragma Float_Representation:: ! * Pragma Ident:: ! * Pragma Import_Exception:: ! * Pragma Import_Function:: ! * Pragma Import_Object:: ! * Pragma Import_Procedure:: ! * Pragma Import_Valued_Procedure:: ! * Pragma Initialize_Scalars:: ! * Pragma Inline_Always:: ! * Pragma Inline_Generic:: ! * Pragma Interface:: ! * Pragma Interface_Name:: ! * Pragma Interrupt_Handler:: ! * Pragma Interrupt_State:: ! * Pragma Keep_Names:: ! * Pragma License:: ! * Pragma Link_With:: ! * Pragma Linker_Alias:: ! * Pragma Linker_Section:: ! * Pragma Long_Float:: ! * Pragma Machine_Attribute:: ! * Pragma Main_Storage:: ! * Pragma No_Return:: ! * Pragma Normalize_Scalars:: ! * Pragma Obsolescent:: ! * Pragma Passive:: ! * Pragma Polling:: ! * Pragma Propagate_Exceptions:: ! * Pragma Psect_Object:: ! * Pragma Pure_Function:: ! * Pragma Ravenscar:: ! * Pragma Restricted_Run_Time:: ! * Pragma Restriction_Warnings:: ! * Pragma Source_File_Name:: ! * Pragma Source_File_Name_Project:: ! * Pragma Source_Reference:: ! * Pragma Stream_Convert:: ! * Pragma Style_Checks:: ! * Pragma Subtitle:: ! * Pragma Suppress_All:: ! * Pragma Suppress_Exception_Locations:: ! * Pragma Suppress_Initialization:: ! * Pragma Task_Info:: ! * Pragma Task_Name:: ! * Pragma Task_Storage:: ! * Pragma Thread_Body:: ! * Pragma Time_Slice:: ! * Pragma Title:: ! * Pragma Unchecked_Union:: ! * Pragma Unimplemented_Unit:: ! * Pragma Universal_Data:: ! * Pragma Unreferenced:: ! * Pragma Unreserve_All_Interrupts:: ! * Pragma Unsuppress:: ! * Pragma Use_VADS_Size:: ! * Pragma Validity_Checks:: ! * Pragma Volatile:: ! * Pragma Warnings:: ! * Pragma Weak_External:: ! @end menu + @node Pragma Abort_Defer + @unnumberedsec Pragma Abort_Defer @findex Abort_Defer @cindex Deferring aborts @noindent Syntax: @smallexample pragma Abort_Defer; @end smallexample *************** the effect of deferring aborts for the s *** 428,439 **** for the declarations or handlers, if any, associated with this statement sequence). ! @item pragma Ada_83 @findex Ada_83 @noindent Syntax: ! ! @smallexample pragma Ada_83; @end smallexample --- 704,715 ---- for the declarations or handlers, if any, associated with this statement sequence). ! @node Pragma Ada_83 ! @unnumberedsec Pragma Ada_83 @findex Ada_83 @noindent Syntax: ! @smallexample @c ada pragma Ada_83; @end smallexample *************** restrictions of Ada 83 are enforced. *** 450,467 **** Ada 83 mode is intended for two purposes. Firstly, it allows existing legacy Ada 83 code to be compiled and adapted to GNAT with less effort. ! Secondly, it aids in keeping code backwards compatible with Ada 83. However, there is no guarantee that code that is processed correctly by GNAT in Ada 83 mode will in fact compile and execute with an Ada 83 compiler, since GNAT does not enforce all the additional checks required by Ada 83. @findex Ada_95 - @item pragma Ada_95 @noindent Syntax: ! ! @smallexample pragma Ada_95; @end smallexample --- 726,743 ---- Ada 83 mode is intended for two purposes. Firstly, it allows existing legacy Ada 83 code to be compiled and adapted to GNAT with less effort. ! Secondly, it aids in keeping code backwards compatible with Ada 83. However, there is no guarantee that code that is processed correctly by GNAT in Ada 83 mode will in fact compile and execute with an Ada 83 compiler, since GNAT does not enforce all the additional checks required by Ada 83. + @node Pragma Ada_95 + @unnumberedsec Pragma Ada_95 @findex Ada_95 @noindent Syntax: ! @smallexample @c ada pragma Ada_95; @end smallexample *************** contexts. This pragma is useful when wr *** 474,485 **** itself uses Ada 95 features, but which is intended to be usable from either Ada 83 or Ada 95 programs. @findex Annotate - @item pragma Annotate @noindent Syntax: ! ! @smallexample pragma Annotate (IDENTIFIER @{, ARG@}); ARG ::= NAME | EXPRESSION --- 750,761 ---- itself uses Ada 95 features, but which is intended to be usable from either Ada 83 or Ada 95 programs. + @node Pragma Annotate + @unnumberedsec Pragma Annotate @findex Annotate @noindent Syntax: ! @smallexample @c ada pragma Annotate (IDENTIFIER @{, ARG@}); ARG ::= NAME | EXPRESSION *************** The analyzed pragma is retained in the t *** 499,513 **** by any part of the GNAT compiler. This pragma is intended for use by external tools, including ASIS@. @findex Assert - @item pragma Assert @noindent Syntax: ! ! @smallexample pragma Assert ( boolean_EXPRESSION ! [, static_string_EXPRESSION]) @end smallexample @noindent --- 775,789 ---- by any part of the GNAT compiler. This pragma is intended for use by external tools, including ASIS@. + @node Pragma Assert + @unnumberedsec Pragma Assert @findex Assert @noindent Syntax: ! @smallexample @c ada pragma Assert ( boolean_EXPRESSION ! [, static_string_EXPRESSION]); @end smallexample @noindent *************** The effect of this pragma depends on whe *** 515,525 **** line switch is set to activate assertions. The pragma expands into code equivalent to the following: ! @smallexample if assertions-enabled then if not boolean_EXPRESSION then System.Assertions.Raise_Assert_Failure ! (string_EXPRESSION); end if; end if; @end smallexample --- 791,801 ---- line switch is set to activate assertions. The pragma expands into code equivalent to the following: ! @smallexample @c ada if assertions-enabled then if not boolean_EXPRESSION then System.Assertions.Raise_Assert_Failure ! (string_EXPRESSION); end if; end if; @end smallexample *************** and @var{nnn} is the line number of the *** 533,539 **** statement, so if a statement sequence contains nothing but a pragma assert, then a null statement is required in addition, as in: ! @smallexample @dots{} if J > 3 then pragma Assert (K > 3, "Bad value for K"); --- 809,815 ---- statement, so if a statement sequence contains nothing but a pragma assert, then a null statement is required in addition, as in: ! @smallexample @c ada @dots{} if J > 3 then pragma Assert (K > 3, "Bad value for K"); *************** which results in the raising of @code{As *** 558,598 **** If the boolean expression has side effects, these side effects will turn on and off with the setting of the assertions mode, resulting in ! assertions that have an effect on the program. You should generally avoid side effects in the expression arguments of this pragma. However, the expressions are analyzed for semantic correctness whether or not assertions are enabled, so turning assertions on and off cannot affect the legality of a program. @cindex OpenVMS @findex Ast_Entry - @item pragma Ast_Entry @noindent Syntax: ! ! @smallexample pragma AST_Entry (entry_IDENTIFIER); @end smallexample @noindent This pragma is implemented only in the OpenVMS implementation of GNAT@. The argument is the simple name of a single entry; at most one @code{AST_Entry} ! pragma is allowed for any given entry. This pragma must be used in conjunction with the @code{AST_Entry} attribute, and is only allowed after the entry declaration and in the same task type specification or single task as the entry to which it applies. This pragma specifies that the given entry may be used to handle an OpenVMS asynchronous system trap (@code{AST}) resulting from an OpenVMS system service call. The pragma does not affect ! normal use of the entry. For further details on this pragma, see the DEC Ada Language Reference Manual, section 9.12a. @cindex Passing by copy @findex C_Pass_By_Copy - @item pragma C_Pass_By_Copy @noindent Syntax: ! ! @smallexample pragma C_Pass_By_Copy ([Max_Size =>] static_integer_EXPRESSION); @end smallexample --- 834,874 ---- If the boolean expression has side effects, these side effects will turn on and off with the setting of the assertions mode, resulting in ! assertions that have an effect on the program. You should generally avoid side effects in the expression arguments of this pragma. However, the expressions are analyzed for semantic correctness whether or not assertions are enabled, so turning assertions on and off cannot affect the legality of a program. + @node Pragma Ast_Entry + @unnumberedsec Pragma Ast_Entry @cindex OpenVMS @findex Ast_Entry @noindent Syntax: ! @smallexample @c ada pragma AST_Entry (entry_IDENTIFIER); @end smallexample @noindent This pragma is implemented only in the OpenVMS implementation of GNAT@. The argument is the simple name of a single entry; at most one @code{AST_Entry} ! pragma is allowed for any given entry. This pragma must be used in conjunction with the @code{AST_Entry} attribute, and is only allowed after the entry declaration and in the same task type specification or single task as the entry to which it applies. This pragma specifies that the given entry may be used to handle an OpenVMS asynchronous system trap (@code{AST}) resulting from an OpenVMS system service call. The pragma does not affect ! normal use of the entry. For further details on this pragma, see the DEC Ada Language Reference Manual, section 9.12a. + @node Pragma C_Pass_By_Copy + @unnumberedsec Pragma C_Pass_By_Copy @cindex Passing by copy @findex C_Pass_By_Copy @noindent Syntax: ! @smallexample @c ada pragma C_Pass_By_Copy ([Max_Size =>] static_integer_EXPRESSION); @end smallexample *************** You can also pass records by copy by spe *** 624,635 **** @code{Import} and @code{Export} pragmas, which allow specification of passing mechanisms on a parameter by parameter basis. @findex Comment - @item pragma Comment @noindent Syntax: ! @smallexample pragma Comment (static_string_EXPRESSION); @end smallexample --- 900,912 ---- @code{Import} and @code{Export} pragmas, which allow specification of passing mechanisms on a parameter by parameter basis. + @node Pragma Comment + @unnumberedsec Pragma Comment @findex Comment @noindent Syntax: ! @smallexample @c ada pragma Comment (static_string_EXPRESSION); @end smallexample *************** pragma Comment (static_string_EXPRESSION *** 637,656 **** This is almost identical in effect to pragma @code{Ident}. It allows the placement of a comment into the object file and hence into the executable file if the operating system permits such usage. The ! difference is that @code{Comment}, unlike @code{Ident}, has no limit on the ! length of the string argument, and no limitations on placement ! of the pragma (it can be placed anywhere in the main source unit). @findex Common_Object - @item pragma Common_Object @noindent Syntax: ! @smallexample pragma Common_Object ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] ! [, [Size =>] EXTERNAL_SYMBOL] ) EXTERNAL_SYMBOL ::= IDENTIFIER --- 914,935 ---- This is almost identical in effect to pragma @code{Ident}. It allows the placement of a comment into the object file and hence into the executable file if the operating system permits such usage. The ! difference is that @code{Comment}, unlike @code{Ident}, has ! no limitations on placement of the pragma (it can be placed ! anywhere in the main source unit), and if more than one pragma ! is used, all comments are retained. + @node Pragma Common_Object + @unnumberedsec Pragma Common_Object @findex Common_Object @noindent Syntax: ! @smallexample @c ada pragma Common_Object ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] ! [, [Size =>] EXTERNAL_SYMBOL] ); EXTERNAL_SYMBOL ::= IDENTIFIER *************** support is available, then the code gene *** 672,683 **** indicating that the necessary attribute for implementation of this pragma is not available. @findex Complex_Representation - @item pragma Complex_Representation @noindent Syntax: ! @smallexample pragma Complex_Representation ([Entity =>] LOCAL_NAME); @end smallexample --- 951,989 ---- indicating that the necessary attribute for implementation of this pragma is not available. + @node Pragma Compile_Time_Warning + @unnumberedsec Pragma Compile_Time_Warning + @findex Compile_Time_Warning + @noindent + Syntax: + + @smallexample @c ada + pragma Compile_Time_Warning + (boolean_EXPRESSION, static_string_EXPRESSION); + @end smallexample + + @noindent + This pragma can be used to generate additional compile time warnings. It + is particularly useful in generics, where warnings can be issued for + specific problematic instantiations. The first parameter is a boolean + expression. The pragma is effective only if the value of this expression + is known at compile time, and has the value True. The set of expressions + whose values are known at compile time includes all static boolean + expressions, and also other values which the compiler can determine + at compile time (e.g. the size of a record type set by an explicit + size representation clause, or the value of a variable which was + initialized to a constant and is known not to have been modified). + If these conditions are met, a warning message is generated using + the value given as the second argument. This string value may contain + embedded ASCII.LF characters to break the message into multiple lines. + + @node Pragma Complex_Representation + @unnumberedsec Pragma Complex_Representation @findex Complex_Representation @noindent Syntax: ! @smallexample @c ada pragma Complex_Representation ([Entity =>] LOCAL_NAME); @end smallexample *************** example, in some environments, there is *** 693,705 **** records by pointer, and the use of this pragma may result in passing this type in floating-point registers. @cindex Alignments of components @findex Component_Alignment - @item pragma Component_Alignment @noindent Syntax: ! @smallexample pragma Component_Alignment ( [Form =>] ALIGNMENT_CHOICE [, [Name =>] type_LOCAL_NAME]); --- 999,1012 ---- records by pointer, and the use of this pragma may result in passing this type in floating-point registers. + @node Pragma Component_Alignment + @unnumberedsec Pragma Component_Alignment @cindex Alignments of components @findex Component_Alignment @noindent Syntax: ! @smallexample @c ada pragma Component_Alignment ( [Form =>] ALIGNMENT_CHOICE [, [Name =>] type_LOCAL_NAME]); *************** the @code{Default} choice is the same as *** 748,753 **** --- 1055,1061 ---- alignment). @end table + @noindent If the @code{Name} parameter is present, @var{type_local_name} must refer to a local record or array type, and the specified alignment choice applies to the specified type. The use of *************** If the alignment for a record or array t *** 769,781 **** pragma @code{Pack}, pragma @code{Component_Alignment}, or a record rep clause), the GNAT uses the default alignment as described previously. @findex Convention_Identifier @cindex Conventions, synonyms - @item pragma Convention_Identifier @noindent Syntax: ! @smallexample pragma Convention_Identifier ( [Name =>] IDENTIFIER, [Convention =>] convention_IDENTIFIER); --- 1077,1090 ---- pragma @code{Pack}, pragma @code{Component_Alignment}, or a record rep clause), the GNAT uses the default alignment as described previously. + @node Pragma Convention_Identifier + @unnumberedsec Pragma Convention_Identifier @findex Convention_Identifier @cindex Conventions, synonyms @noindent Syntax: ! @smallexample @c ada pragma Convention_Identifier ( [Name =>] IDENTIFIER, [Convention =>] convention_IDENTIFIER); *************** for example pragma @code{Import} or anot *** 789,795 **** pragma). As an example of the use of this, suppose you had legacy code which used Fortran77 as the identifier for Fortran. Then the pragma: ! @smallexample pragma Convention_Indentifier (Fortran77, Fortran); @end smallexample --- 1098,1104 ---- pragma). As an example of the use of this, suppose you had legacy code which used Fortran77 as the identifier for Fortran. Then the pragma: ! @smallexample @c ada pragma Convention_Indentifier (Fortran77, Fortran); @end smallexample *************** windows systems, and @code{C} on some ot *** 802,815 **** define a convention identifier @code{Library} and use a single @code{Convention_Identifier} pragma to specify which convention would be used system-wide. ! @findex CPP_Class @cindex Interfacing with C++ - @item pragma CPP_Class @noindent Syntax: ! @smallexample pragma CPP_Class ([Entity =>] LOCAL_NAME); @end smallexample --- 1111,1125 ---- define a convention identifier @code{Library} and use a single @code{Convention_Identifier} pragma to specify which convention would be used system-wide. ! ! @node Pragma CPP_Class ! @unnumberedsec Pragma CPP_Class @findex CPP_Class @cindex Interfacing with C++ @noindent Syntax: ! @smallexample @c ada pragma CPP_Class ([Entity =>] LOCAL_NAME); @end smallexample *************** as subprograms as required). Initializa *** 830,845 **** constructor functions (see pragma @code{CPP_Constructor}). Pragma @code{CPP_Class} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for related information. @cindex Interfacing with C++ @findex CPP_Constructor - @item pragma CPP_Constructor @noindent Syntax: ! @smallexample pragma CPP_Constructor ([Entity =>] LOCAL_NAME); @end smallexample --- 1140,1156 ---- constructor functions (see pragma @code{CPP_Constructor}). Pragma @code{CPP_Class} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for related information. + @node Pragma CPP_Constructor + @unnumberedsec Pragma CPP_Constructor @cindex Interfacing with C++ @findex CPP_Constructor @noindent Syntax: ! @smallexample @c ada pragma CPP_Constructor ([Entity =>] LOCAL_NAME); @end smallexample *************** pragma CPP_Constructor ([Entity =>] LOCA *** 847,853 **** This pragma identifies an imported function (imported in the usual way with pragma @code{Import}) as corresponding to a C++ constructor. The argument is a name that must have been ! previously mentioned in a pragma @code{Import} with @code{Convention} = @code{CPP}, and must be of one of the following forms: --- 1158,1164 ---- This pragma identifies an imported function (imported in the usual way with pragma @code{Import}) as corresponding to a C++ constructor. The argument is a name that must have been ! previously mentioned in a pragma @code{Import} with @code{Convention} = @code{CPP}, and must be of one of the following forms: *************** On the right side of an initialization o *** 875,880 **** --- 1186,1192 ---- In an extension aggregate for an object of a type derived from @var{T}. @end itemize + @noindent Although the constructor is described as a function that returns a value on the Ada side, it is typically a procedure with an extra implicit argument (the object being initialized) at the implementation *************** for declaring and creating an object: *** 886,894 **** @itemize @bullet @item @code{New_Object : Derived_T} ! @item @code{New_Object : Derived_T := (@var{constructor-function-call with} @dots{})} @end itemize In the first case the default constructor is called and extension fields if any are initialized according to the default initialization expressions in the Ada declaration. In the second case, the given --- 1198,1207 ---- @itemize @bullet @item @code{New_Object : Derived_T} ! @item @code{New_Object : Derived_T := (@var{constructor-call with} @dots{})} @end itemize + @noindent In the first case the default constructor is called and extension fields if any are initialized according to the default initialization expressions in the Ada declaration. In the second case, the given *************** initialization forms using an explicit c *** 901,922 **** permitted. Pragma @code{CPP_Constructor} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for more related information. @cindex Interfacing to C++ @findex CPP_Virtual - @item pragma CPP_Virtual @noindent Syntax: ! @smallexample pragma CPP_Virtual [Entity =>] ENTITY, [, [Vtable_Ptr =>] vtable_ENTITY,] ! [, [Position =>] static_integer_EXPRESSION]) @end smallexample This pragma serves the same function as pragma @code{Import} in that case of a virtual function imported from C++. The @var{Entity} argument must be a --- 1214,1237 ---- permitted. Pragma @code{CPP_Constructor} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for more related information. + @node Pragma CPP_Virtual + @unnumberedsec Pragma CPP_Virtual @cindex Interfacing to C++ @findex CPP_Virtual @noindent Syntax: ! @smallexample @c ada pragma CPP_Virtual [Entity =>] ENTITY, [, [Vtable_Ptr =>] vtable_ENTITY,] ! [, [Position =>] static_integer_EXPRESSION]); @end smallexample + @noindent This pragma serves the same function as pragma @code{Import} in that case of a virtual function imported from C++. The @var{Entity} argument must be a *************** virtual function, since it is always acc *** 937,952 **** appropriate Vtable entry. Pragma @code{CPP_Virtual} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for related information. @cindex Interfacing with C++ @findex CPP_Vtable - @item pragma CPP_Vtable @noindent Syntax: ! @smallexample pragma CPP_Vtable ( [Entity =>] ENTITY, [Vtable_Ptr =>] vtable_ENTITY, --- 1252,1268 ---- appropriate Vtable entry. Pragma @code{CPP_Virtual} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for related information. + @node Pragma CPP_Vtable + @unnumberedsec Pragma CPP_Vtable @cindex Interfacing with C++ @findex CPP_Vtable @noindent Syntax: ! @smallexample @c ada pragma CPP_Vtable ( [Entity =>] ENTITY, [Vtable_Ptr =>] vtable_ENTITY, *************** imported on the Ada side (the default va *** 968,982 **** case is simply the total number of virtual functions). Pragma @code{CPP_Vtable} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for related information. @findex Debug - @item pragma Debug @noindent Syntax: ! @smallexample pragma Debug (PROCEDURE_CALL_WITHOUT_SEMICOLON); PROCEDURE_CALL_WITHOUT_SEMICOLON ::= --- 1284,1299 ---- case is simply the total number of virtual functions). Pragma @code{CPP_Vtable} is intended primarily for automatic generation ! using an automatic binding generator tool. See @ref{Interfacing to C++} for related information. + @node Pragma Debug + @unnumberedsec Pragma Debug @findex Debug @noindent Syntax: ! @smallexample @c ada pragma Debug (PROCEDURE_CALL_WITHOUT_SEMICOLON); PROCEDURE_CALL_WITHOUT_SEMICOLON ::= *************** PROCEDURE_CALL_WITHOUT_SEMICOLON ::= *** 986,992 **** @noindent The argument has the syntactic form of an expression, meeting the ! syntactic requirements for pragmas. If assertions are not enabled on the command line, this pragma has no effect. If asserts are enabled, the semantics of the pragma is exactly --- 1303,1309 ---- @noindent The argument has the syntactic form of an expression, meeting the ! syntactic requirements for pragmas. If assertions are not enabled on the command line, this pragma has no effect. If asserts are enabled, the semantics of the pragma is exactly *************** with a terminating semicolon. Pragmas a *** 995,1007 **** declarations, so you can use pragma @code{Debug} to intersperse calls to debug procedures in the middle of declarations. @cindex Elaboration control @findex Elaboration_Checks - @item pragma Elaboration_Checks @noindent Syntax: ! @smallexample pragma Elaboration_Checks (RM | Static); @end smallexample --- 1312,1325 ---- declarations, so you can use pragma @code{Debug} to intersperse calls to debug procedures in the middle of declarations. + @node Pragma Elaboration_Checks + @unnumberedsec Pragma Elaboration_Checks @cindex Elaboration control @findex Elaboration_Checks @noindent Syntax: ! @smallexample @c ada pragma Elaboration_Checks (RM | Static); @end smallexample *************** of the command line. For full details o *** 1017,1029 **** used by the GNAT compiler, see section ``Elaboration Order Handling in GNAT'' in the @cite{GNAT User's Guide}. @cindex Elimination of unused subprograms @findex Eliminate - @item pragma Eliminate @noindent Syntax: ! @smallexample pragma Eliminate ( [Unit_Name =>] IDENTIFIER | SELECTED_COMPONENT); --- 1335,1348 ---- used by the GNAT compiler, see section ``Elaboration Order Handling in GNAT'' in the @cite{GNAT User's Guide}. + @node Pragma Eliminate + @unnumberedsec Pragma Eliminate @cindex Elimination of unused subprograms @findex Eliminate @noindent Syntax: ! @smallexample @c ada pragma Eliminate ( [Unit_Name =>] IDENTIFIER | SELECTED_COMPONENT); *************** SUBTYPE_NAME ::= STRING_LITERAL *** 1044,1050 **** @noindent This pragma indicates that the given entity is not used outside the ! compilation unit it is defined in. The entity may be either a subprogram or a variable. If the entity to be eliminated is a library level subprogram, then --- 1363,1369 ---- @noindent This pragma indicates that the given entity is not used outside the ! compilation unit it is defined in. The entity may be either a subprogram or a variable. If the entity to be eliminated is a library level subprogram, then *************** In this form, the @code{Unit_Name} argum *** 1053,1059 **** library level unit to be eliminated. In all other cases, both @code{Unit_Name} and @code{Entity} arguments ! are required. item is an entity of a library package, then the first argument specifies the unit name, and the second argument specifies the particular entity. If the second argument is in string form, it must correspond to the internal manner in which GNAT stores entity names (see --- 1372,1378 ---- library level unit to be eliminated. In all other cases, both @code{Unit_Name} and @code{Entity} arguments ! are required. If item is an entity of a library package, then the first argument specifies the unit name, and the second argument specifies the particular entity. If the second argument is in string form, it must correspond to the internal manner in which GNAT stores entity names (see *************** which overloaded alternative is to be el *** 1074,1080 **** the first subprogram (in lexical order), 2 indicates the second etc. The effect of the pragma is to allow the compiler to eliminate ! the code or data associated with the named entity. Any reference to an eliminated entity outside the compilation unit it is defined in, causes a compile time or link time error. --- 1393,1399 ---- the first subprogram (in lexical order), 2 indicates the second etc. The effect of the pragma is to allow the compiler to eliminate ! the code or data associated with the named entity. Any reference to an eliminated entity outside the compilation unit it is defined in, causes a compile time or link time error. *************** are used. *** 1085,1105 **** The intention of pragma @code{Eliminate} is to allow a program to be compiled in a system independent manner, with unused entities eliminated, without the requirement of modifying the source text. Normally the required set ! of @code{Eliminate} pragmas is constructed automatically using the gnatelim tool. ! Elimination of unused entities local to a compilation unit is automatic, ! without requiring the use of pragma @code{Eliminate}. Note that the reason this pragma takes string literals where names might be expected is that a pragma @code{Eliminate} can appear in a context where the relevant names are not visible. @cindex OpenVMS @findex Export_Exception - @item pragma Export_Exception @noindent Syntax: ! @smallexample pragma Export_Exception ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL,] --- 1404,1425 ---- The intention of pragma @code{Eliminate} is to allow a program to be compiled in a system independent manner, with unused entities eliminated, without the requirement of modifying the source text. Normally the required set ! of @code{Eliminate} pragmas is constructed automatically using the gnatelim ! tool. Elimination of unused entities local to a compilation unit is ! automatic, without requiring the use of pragma @code{Eliminate}. Note that the reason this pragma takes string literals where names might be expected is that a pragma @code{Eliminate} can appear in a context where the relevant names are not visible. + @node Pragma Export_Exception + @unnumberedsec Pragma Export_Exception @cindex OpenVMS @findex Export_Exception @noindent Syntax: ! @smallexample @c ada pragma Export_Exception ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL,] *************** name available to the OpenVMS Linker as *** 1120,1135 **** on this pragma, see the DEC Ada Language Reference Manual, section 13.9a3.2. @cindex Argument passing mechanisms @findex Export_Function - @item pragma Export_Function @dots{} @noindent Syntax: ! @smallexample pragma Export_Function ( ! [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] [, [Parameter_Types =>] PARAMETER_TYPES] [, [Result_Type =>] result_SUBTYPE_MARK] --- 1440,1456 ---- on this pragma, see the DEC Ada Language Reference Manual, section 13.9a3.2. + @node Pragma Export_Function + @unnumberedsec Pragma Export_Function @cindex Argument passing mechanisms @findex Export_Function @noindent Syntax: ! @smallexample @c ada pragma Export_Function ( ! [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] [, [Parameter_Types =>] PARAMETER_TYPES] [, [Result_Type =>] result_SUBTYPE_MARK] *************** pragma Export_Function ( *** 1139,1148 **** EXTERNAL_SYMBOL ::= IDENTIFIER | static_string_EXPRESSION PARAMETER_TYPES ::= null ! | SUBTYPE_MARK @{, SUBTYPE_MARK@} MECHANISM ::= MECHANISM_NAME --- 1460,1474 ---- EXTERNAL_SYMBOL ::= IDENTIFIER | static_string_EXPRESSION + | "" PARAMETER_TYPES ::= null ! | TYPE_DESIGNATOR @{, TYPE_DESIGNATOR@} ! ! TYPE_DESIGNATOR ::= ! subtype_NAME ! | subtype_Name ' Access MECHANISM ::= MECHANISM_NAME *************** MECHANISM_ASSOCIATION ::= *** 1154,1164 **** MECHANISM_NAME ::= Value | Reference - | Descriptor [([Class =>] CLASS_NAME)] - - CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca @end smallexample Use this pragma to make a function externally callable and optionally provide information on mechanisms to be used for passing parameter and result values. We recommend, for the purposes of improving portability, --- 1480,1488 ---- MECHANISM_NAME ::= Value | Reference @end smallexample + @noindent Use this pragma to make a function externally callable and optionally provide information on mechanisms to be used for passing parameter and result values. We recommend, for the purposes of improving portability, *************** the declarative part you must use the @c *** 1180,1195 **** unique designation. @var{subtype_ mark}s in these parameters must exactly match the subtypes in the corresponding function specification, using positional notation to match parameters with subtype marks. @cindex OpenVMS @cindex Passing by descriptor ! Passing by descriptor is supported only on the OpenVMS ports of GNAT@. @findex Export_Object - @item pragma Export_Object @dots{} @noindent Syntax: ! @smallexample pragma Export_Object [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] --- 1504,1530 ---- unique designation. @var{subtype_ mark}s in these parameters must exactly match the subtypes in the corresponding function specification, using positional notation to match parameters with subtype marks. + The form with an @code{'Access} attribute can be used to match an + anonymous access parameter. + @cindex OpenVMS @cindex Passing by descriptor ! Note that passing by descriptor is not supported, even on the OpenVMS ! ports of GNAT@. + @cindex Suppressing external name + Special treatment is given if the EXTERNAL is an explicit null + string or a static string expressions that evaluates to the null + string. In this case, no external name is generated. This form + still allows the specification of parameter mechanisms. + + @node Pragma Export_Object + @unnumberedsec Pragma Export_Object @findex Export_Object @noindent Syntax: ! @smallexample @c ada pragma Export_Object [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] *************** EXTERNAL_SYMBOL ::= *** 1200,1205 **** --- 1535,1541 ---- | static_string_EXPRESSION @end smallexample + @noindent This pragma designates an object as exported, and apart from the extended rules for external symbols, is identical in effect to the use of the normal @code{Export} pragma applied to an object. You may use a *************** separate Export pragma (and you probably *** 1207,1218 **** of portability), but it is not required. @var{Size} is syntax checked, but otherwise ignored by GNAT@. @findex Export_Procedure - @item pragma Export_Procedure @dots{} @noindent Syntax: ! @smallexample pragma Export_Procedure ( [Internal =>] LOCAL_NAME [, [External =>] EXTERNAL_SYMBOL] --- 1543,1555 ---- of portability), but it is not required. @var{Size} is syntax checked, but otherwise ignored by GNAT@. + @node Pragma Export_Procedure + @unnumberedsec Pragma Export_Procedure @findex Export_Procedure @noindent Syntax: ! @smallexample @c ada pragma Export_Procedure ( [Internal =>] LOCAL_NAME [, [External =>] EXTERNAL_SYMBOL] *************** pragma Export_Procedure ( *** 1222,1231 **** EXTERNAL_SYMBOL ::= IDENTIFIER | static_string_EXPRESSION PARAMETER_TYPES ::= null ! | SUBTYPE_MARK @{, SUBTYPE_MARK@} MECHANISM ::= MECHANISM_NAME --- 1559,1573 ---- EXTERNAL_SYMBOL ::= IDENTIFIER | static_string_EXPRESSION + | "" PARAMETER_TYPES ::= null ! | TYPE_DESIGNATOR @{, TYPE_DESIGNATOR@} ! ! TYPE_DESIGNATOR ::= ! subtype_NAME ! | subtype_Name ' Access MECHANISM ::= MECHANISM_NAME *************** MECHANISM_ASSOCIATION ::= *** 1237,1245 **** MECHANISM_NAME ::= Value | Reference - | Descriptor [([Class =>] CLASS_NAME)] - - CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca @end smallexample @noindent --- 1579,1584 ---- *************** not what is wanted, so it is usually app *** 1252,1263 **** pragma in conjunction with a @code{Export} or @code{Convention} pragma that specifies the desired foreign convention. @findex Export_Valued_Procedure - @item pragma Export_Valued_Procedure @noindent Syntax: ! @smallexample pragma Export_Valued_Procedure ( [Internal =>] LOCAL_NAME [, [External =>] EXTERNAL_SYMBOL] --- 1591,1635 ---- pragma in conjunction with a @code{Export} or @code{Convention} pragma that specifies the desired foreign convention. + @cindex OpenVMS + @cindex Passing by descriptor + Note that passing by descriptor is not supported, even on the OpenVMS + ports of GNAT@. + + @cindex Suppressing external name + Special treatment is given if the EXTERNAL is an explicit null + string or a static string expressions that evaluates to the null + string. In this case, no external name is generated. This form + still allows the specification of parameter mechanisms. + + @node Pragma Export_Value + @unnumberedsec Pragma Export_Value + @findex Export_Value + @noindent + Syntax: + + @smallexample @c ada + pragma Export_Value ( + [Value =>] static_integer_EXPRESSION, + [Link_Name =>] static_string_EXPRESSION); + @end smallexample + + @noindent + This pragma serves to export a static integer value for external use. + The first argument specifies the value to be exported. The Link_Name + argument specifies the symbolic name to be associated with the integer + value. This pragma is useful for defining a named static value in Ada + that can be referenced in assembly language units to be linked with + the application. This pragma is currently supported only for the + AAMP target and is ignored for other targets. + + @node Pragma Export_Valued_Procedure + @unnumberedsec Pragma Export_Valued_Procedure @findex Export_Valued_Procedure @noindent Syntax: ! @smallexample @c ada pragma Export_Valued_Procedure ( [Internal =>] LOCAL_NAME [, [External =>] EXTERNAL_SYMBOL] *************** pragma Export_Valued_Procedure ( *** 1267,1276 **** EXTERNAL_SYMBOL ::= IDENTIFIER | static_string_EXPRESSION PARAMETER_TYPES ::= null ! | SUBTYPE_MARK @{, SUBTYPE_MARK@} MECHANISM ::= MECHANISM_NAME --- 1639,1653 ---- EXTERNAL_SYMBOL ::= IDENTIFIER | static_string_EXPRESSION + | "" PARAMETER_TYPES ::= null ! | TYPE_DESIGNATOR @{, TYPE_DESIGNATOR@} ! ! TYPE_DESIGNATOR ::= ! subtype_NAME ! | subtype_Name ' Access MECHANISM ::= MECHANISM_NAME *************** MECHANISM_ASSOCIATION ::= *** 1282,1292 **** MECHANISM_NAME ::= Value | Reference - | Descriptor [([Class =>] CLASS_NAME)] - - CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca @end smallexample This pragma is identical to @code{Export_Procedure} except that the first parameter of @var{local_name}, which must be present, must be of mode @code{OUT}, and externally the subprogram is treated as a function --- 1659,1667 ---- MECHANISM_NAME ::= Value | Reference @end smallexample + @noindent This pragma is identical to @code{Export_Procedure} except that the first parameter of @var{local_name}, which must be present, must be of mode @code{OUT}, and externally the subprogram is treated as a function *************** with foreign language functions, so it i *** 1301,1314 **** pragma in conjunction with a @code{Export} or @code{Convention} pragma that specifies the desired foreign convention. @cindex @code{system}, extending @cindex Dec Ada 83 @findex Extend_System - @item pragma Extend_System @noindent Syntax: ! @smallexample pragma Extend_System ([Name =>] IDENTIFIER); @end smallexample --- 1676,1701 ---- pragma in conjunction with a @code{Export} or @code{Convention} pragma that specifies the desired foreign convention. + @cindex OpenVMS + @cindex Passing by descriptor + Note that passing by descriptor is not supported, even on the OpenVMS + ports of GNAT@. + + @cindex Suppressing external name + Special treatment is given if the EXTERNAL is an explicit null + string or a static string expressions that evaluates to the null + string. In this case, no external name is generated. This form + still allows the specification of parameter mechanisms. + + @node Pragma Extend_System + @unnumberedsec Pragma Extend_System @cindex @code{system}, extending @cindex Dec Ada 83 @findex Extend_System @noindent Syntax: ! @smallexample @c ada pragma Extend_System ([Name =>] IDENTIFIER); @end smallexample *************** and thus is considered part of the imple *** 1347,1358 **** it you will have to use the appropriate switch for compiling system units. See the GNAT User's Guide for details. @findex External - @item pragma External @noindent Syntax: ! @smallexample pragma External ( [ Convention =>] convention_IDENTIFIER, [ Entity =>] local_NAME --- 1734,1746 ---- it you will have to use the appropriate switch for compiling system units. See the GNAT User's Guide for details. + @node Pragma External + @unnumberedsec Pragma External @findex External @noindent Syntax: ! @smallexample @c ada pragma External ( [ Convention =>] convention_IDENTIFIER, [ Entity =>] local_NAME *************** provided for compatibility with some Ada *** 1367,1381 **** used this pragma for exactly the same purposes as pragma @code{Export} before the latter was standardized. @cindex Dec Ada 83 casing compatibility @cindex External Names, casing @cindex Casing of External names @findex External_Name_Casing - @item pragma External_Name_Casing @noindent Syntax: ! @smallexample pragma External_Name_Casing ( Uppercase | Lowercase [, Uppercase | Lowercase | As_Is]); --- 1755,1770 ---- used this pragma for exactly the same purposes as pragma @code{Export} before the latter was standardized. + @node Pragma External_Name_Casing + @unnumberedsec Pragma External_Name_Casing @cindex Dec Ada 83 casing compatibility @cindex External Names, casing @cindex Casing of External names @findex External_Name_Casing @noindent Syntax: ! @smallexample @c ada pragma External_Name_Casing ( Uppercase | Lowercase [, Uppercase | Lowercase | As_Is]); *************** Implicit external names are derived from *** 1391,1397 **** arises when a standard Ada 95 Import or Export pragma is used with only two arguments, as in: ! @smallexample pragma Import (C, C_Routine); @end smallexample --- 1780,1786 ---- arises when a standard Ada 95 Import or Export pragma is used with only two arguments, as in: ! @smallexample @c ada pragma Import (C, C_Routine); @end smallexample *************** Explicit external names are given as str *** 1415,1428 **** arises when a standard Ada 95 Import or Export pragma is used with three arguments, as in: ! @smallexample pragma Import (C, C_Routine, "C_routine"); @end smallexample @noindent In this case, the string literal normally provides the exact casing required ! for the external name. The second argument of pragma ! @code{External_Name_Casing} may be used to modify this behavior. If @code{Uppercase} is specified, then the name will be forced to all uppercase letters. If @code{Lowercase} is specified, then the name will be forced to all lowercase letters. A specification of --- 1804,1817 ---- arises when a standard Ada 95 Import or Export pragma is used with three arguments, as in: ! @smallexample @c ada pragma Import (C, C_Routine, "C_routine"); @end smallexample @noindent In this case, the string literal normally provides the exact casing required ! for the external name. The second argument of pragma ! @code{External_Name_Casing} may be used to modify this behavior. If @code{Uppercase} is specified, then the name will be forced to all uppercase letters. If @code{Lowercase} is specified, then the name will be forced to all lowercase letters. A specification of *************** compilers convert all symbols to upper c *** 1442,1460 **** such compilers (e.g.@: the DEC C compiler), it may be convenient to use the pragma: ! @smallexample pragma External_Name_Casing (Uppercase, Uppercase); @end smallexample @noindent ! to enforce the upper casing of all external symbols. @findex Finalize_Storage_Only - @item pragma Finalize_Storage_Only @noindent Syntax: ! @smallexample pragma Finalize_Storage_Only (first_subtype_LOCAL_NAME); @end smallexample --- 1831,1850 ---- such compilers (e.g.@: the DEC C compiler), it may be convenient to use the pragma: ! @smallexample @c ada pragma External_Name_Casing (Uppercase, Uppercase); @end smallexample @noindent ! to enforce the upper casing of all external symbols. + @node Pragma Finalize_Storage_Only + @unnumberedsec Pragma Finalize_Storage_Only @findex Finalize_Storage_Only @noindent Syntax: ! @smallexample @c ada pragma Finalize_Storage_Only (first_subtype_LOCAL_NAME); @end smallexample *************** finalization is only used to deal with s *** 1465,1518 **** environments it is not necessary to reclaim memory just before terminating execution, hence the name. @cindex OpenVMS @findex Float_Representation - @item pragma Float_Representation @noindent Syntax: ! @smallexample pragma Float_Representation (FLOAT_REP); FLOAT_REP ::= VAX_Float | IEEE_Float @end smallexample @noindent ! This pragma is implemented only in the OpenVMS implementation of GNAT@. ! It allows control over the internal representation chosen for the predefined floating point types declared in the packages @code{Standard} and ! @code{System}. For further details on this pragma, see the ! DEC Ada Language Reference Manual, section 3.5.7a. Note that to use this ! pragma, the standard runtime libraries must be recompiled. See the description of the @code{GNAT LIBRARY} command in the OpenVMS version of the GNAT Users Guide for details on the use of this command. @findex Ident - @item pragma Ident @noindent Syntax: ! @smallexample pragma Ident (static_string_EXPRESSION); @end smallexample @noindent This pragma provides a string identification in the generated object file, if the system supports the concept of this kind of identification string. - The maximum permitted length of the string literal is 31 characters. This pragma is allowed only in the outermost declarative part or ! declarative items of a compilation unit. @cindex OpenVMS On OpenVMS systems, the effect of the pragma is identical to the effect of ! the DEC Ada 83 pragma of the same name. @cindex OpenVMS @findex Import_Exception - @item pragma Import_Exception @noindent Syntax: ! @smallexample pragma Import_Exception ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL,] --- 1855,1916 ---- environments it is not necessary to reclaim memory just before terminating execution, hence the name. + @node Pragma Float_Representation + @unnumberedsec Pragma Float_Representation @cindex OpenVMS @findex Float_Representation @noindent Syntax: ! @smallexample @c ada pragma Float_Representation (FLOAT_REP); FLOAT_REP ::= VAX_Float | IEEE_Float @end smallexample @noindent ! This pragma ! allows control over the internal representation chosen for the predefined floating point types declared in the packages @code{Standard} and ! @code{System}. On all systems other than OpenVMS, the argument must ! be @code{IEEE_Float} and the pragma has no effect. On OpenVMS, the ! argument may be @code{VAX_Float} to specify the use of the VAX float ! format for the floating-point types in Standard. This requires that ! the standard runtime libraries be recompiled. See the description of the @code{GNAT LIBRARY} command in the OpenVMS version of the GNAT Users Guide for details on the use of this command. + @node Pragma Ident + @unnumberedsec Pragma Ident @findex Ident @noindent Syntax: ! @smallexample @c ada pragma Ident (static_string_EXPRESSION); @end smallexample @noindent This pragma provides a string identification in the generated object file, if the system supports the concept of this kind of identification string. This pragma is allowed only in the outermost declarative part or ! declarative items of a compilation unit. If more than one @code{Ident} ! pragma is given, only the last one processed is effective. @cindex OpenVMS On OpenVMS systems, the effect of the pragma is identical to the effect of ! the DEC Ada 83 pragma of the same name. Note that in DEC Ada 83, the ! maximum allowed length is 31 characters, so if it is important to ! maintain compatibility with this compiler, you should obey this length ! limit. + @node Pragma Import_Exception + @unnumberedsec Pragma Import_Exception @cindex OpenVMS @findex Import_Exception @noindent Syntax: ! @smallexample @c ada pragma Import_Exception ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL,] *************** declaration in an Ada program be defined *** 1533,1544 **** For further details on this pragma, see the DEC Ada Language Reference Manual, section 13.9a.3.1. @findex Import_Function - @item pragma Import_Function @dots{} @noindent Syntax: ! @smallexample pragma Import_Function ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] --- 1931,1943 ---- For further details on this pragma, see the DEC Ada Language Reference Manual, section 13.9a.3.1. + @node Pragma Import_Function + @unnumberedsec Pragma Import_Function @findex Import_Function @noindent Syntax: ! @smallexample @c ada pragma Import_Function ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] *************** EXTERNAL_SYMBOL ::= *** 1554,1560 **** PARAMETER_TYPES ::= null ! | SUBTYPE_MARK @{, SUBTYPE_MARK@} MECHANISM ::= MECHANISM_NAME --- 1953,1963 ---- PARAMETER_TYPES ::= null ! | TYPE_DESIGNATOR @{, TYPE_DESIGNATOR@} ! ! TYPE_DESIGNATOR ::= ! subtype_NAME ! | subtype_Name ' Access MECHANISM ::= MECHANISM_NAME *************** MECHANISM_NAME ::= *** 1571,1583 **** CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca @end smallexample This pragma is used in conjunction with a pragma @code{Import} to specify additional information for an imported function. The pragma @code{Import} (or equivalent pragma @code{Interface}) must precede the @code{Import_Function} pragma and both must appear in the same declarative part as the function specification. ! The @var{Internal_Name} argument must uniquely designate the function to which the pragma applies. If more than one function name exists of this name in the declarative part you must use the @code{Parameter_Types} and --- 1974,1987 ---- CLASS_NAME ::= ubs | ubsb | uba | s | sb | a | nca @end smallexample + @noindent This pragma is used in conjunction with a pragma @code{Import} to specify additional information for an imported function. The pragma @code{Import} (or equivalent pragma @code{Interface}) must precede the @code{Import_Function} pragma and both must appear in the same declarative part as the function specification. ! The @var{Internal} argument must uniquely designate the function to which the pragma applies. If more than one function name exists of this name in the declarative part you must use the @code{Parameter_Types} and *************** the declarative part you must use the @c *** 1585,1590 **** --- 1989,1996 ---- designation. Subtype marks in these parameters must exactly match the subtypes in the corresponding function specification, using positional notation to match parameters with subtype marks. + The form with an @code{'Access} attribute can be used to match an + anonymous access parameter. You may optionally use the @var{Mechanism} and @var{Result_Mechanism} parameters to specify passing mechanisms for the *************** is used. *** 1596,1602 **** @cindex OpenVMS @cindex Passing by descriptor ! Passing by descriptor is supported only on the to OpenVMS ports of GNAT@. @code{First_Optional_Parameter} applies only to OpenVMS ports of GNAT@. It specifies that the designated parameter and all following parameters --- 2002,2008 ---- @cindex OpenVMS @cindex Passing by descriptor ! Passing by descriptor is supported only on the OpenVMS ports of GNAT@. @code{First_Optional_Parameter} applies only to OpenVMS ports of GNAT@. It specifies that the designated parameter and all following parameters *************** parameters). All optional parameters mu *** 1607,1622 **** default parameter values that are either known at compile time expressions, or uses of the @code{'Null_Parameter} attribute. @findex Import_Object - @item pragma Import_Object @noindent Syntax: ! @smallexample pragma Import_Object [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL], ! [, [Size =>] EXTERNAL_SYMBOL]) EXTERNAL_SYMBOL ::= IDENTIFIER --- 2013,2029 ---- default parameter values that are either known at compile time expressions, or uses of the @code{'Null_Parameter} attribute. + @node Pragma Import_Object + @unnumberedsec Pragma Import_Object @findex Import_Object @noindent Syntax: ! @smallexample @c ada pragma Import_Object [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL], ! [, [Size =>] EXTERNAL_SYMBOL]); EXTERNAL_SYMBOL ::= IDENTIFIER *************** although you may do so (and probably sho *** 1632,1643 **** point of view). @var{size} is syntax checked, but otherwise ignored by GNAT@. @findex Import_Procedure - @item pragma Import_Procedure @noindent Syntax: ! @smallexample pragma Import_Procedure ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] --- 2039,2051 ---- point of view). @var{size} is syntax checked, but otherwise ignored by GNAT@. + @node Pragma Import_Procedure + @unnumberedsec Pragma Import_Procedure @findex Import_Procedure @noindent Syntax: ! @smallexample @c ada pragma Import_Procedure ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] *************** EXTERNAL_SYMBOL ::= *** 1651,1657 **** PARAMETER_TYPES ::= null ! | SUBTYPE_MARK @{, SUBTYPE_MARK@} MECHANISM ::= MECHANISM_NAME --- 2059,2069 ---- PARAMETER_TYPES ::= null ! | TYPE_DESIGNATOR @{, TYPE_DESIGNATOR@} ! ! TYPE_DESIGNATOR ::= ! subtype_NAME ! | subtype_Name ' Access MECHANISM ::= MECHANISM_NAME *************** This pragma is identical to @code{Import *** 1673,1684 **** applies to a procedure rather than a function and the parameters @code{Result_Type} and @code{Result_Mechanism} are not permitted. @findex Import_Valued_Procedure - @item pragma Import_Valued_Procedure @dots{} @noindent Syntax: ! @smallexample pragma Import_Valued_Procedure ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] --- 2085,2097 ---- applies to a procedure rather than a function and the parameters @code{Result_Type} and @code{Result_Mechanism} are not permitted. + @node Pragma Import_Valued_Procedure + @unnumberedsec Pragma Import_Valued_Procedure @findex Import_Valued_Procedure @noindent Syntax: ! @smallexample @c ada pragma Import_Valued_Procedure ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] *************** EXTERNAL_SYMBOL ::= *** 1692,1698 **** PARAMETER_TYPES ::= null ! | SUBTYPE_MARK @{, SUBTYPE_MARK@} MECHANISM ::= MECHANISM_NAME --- 2105,2115 ---- PARAMETER_TYPES ::= null ! | TYPE_DESIGNATOR @{, TYPE_DESIGNATOR@} ! ! TYPE_DESIGNATOR ::= ! subtype_NAME ! | subtype_Name ' Access MECHANISM ::= MECHANISM_NAME *************** Note that it is important to use this pr *** 1727,1744 **** pragma Import that specifies the desired convention, since otherwise the default convention is Ada, which is almost certainly not what is required. @findex Initialize_Scalars @cindex debugging with Initialize_Scalars - @item pragma Initialize_Scalars @noindent Syntax: ! @smallexample pragma Initialize_Scalars; @end smallexample @noindent ! This pragma is similar to @code{Normalize_Scalars} conceptually but has two important differences. First, there is no requirement for the pragma to be used uniformly in all units of a partition, in particular, it is fine to use this just for some or all of the application units of a partition, --- 2144,2162 ---- pragma Import that specifies the desired convention, since otherwise the default convention is Ada, which is almost certainly not what is required. + @node Pragma Initialize_Scalars + @unnumberedsec Pragma Initialize_Scalars @findex Initialize_Scalars @cindex debugging with Initialize_Scalars @noindent Syntax: ! @smallexample @c ada pragma Initialize_Scalars; @end smallexample @noindent ! This pragma is similar to @code{Normalize_Scalars} conceptually but has two important differences. First, there is no requirement for the pragma to be used uniformly in all units of a partition, in particular, it is fine to use this just for some or all of the application units of a partition, *************** uninitialized value. *** 1767,1797 **** Note that pragma @code{Initialize_Scalars} is particularly useful in conjunction with the enhanced validity checking that is now provided in GNAT, which checks for invalid values under more conditions. ! Using this feature (see description of the @code{-gnatv} flag in the users guide) in conjunction with pragma @code{Initialize_Scalars} provides a powerful new tool to assist in the detection of problems caused by uninitialized variables. @findex Inline_Always - @item pragma Inline_Always @noindent Syntax: ! @smallexample pragma Inline_Always (NAME [, NAME]); @end smallexample @noindent Similar to pragma @code{Inline} except that inlining is not subject to ! the use of option @code{-gnatn} for inter-unit inlining. @findex Inline_Generic - @item pragma Inline_Generic @noindent Syntax: ! @smallexample ! pragma Inline_Generic (generic_package_NAME) @end smallexample @noindent --- 2185,2218 ---- Note that pragma @code{Initialize_Scalars} is particularly useful in conjunction with the enhanced validity checking that is now provided in GNAT, which checks for invalid values under more conditions. ! Using this feature (see description of the @code{-gnatV} flag in the users guide) in conjunction with pragma @code{Initialize_Scalars} provides a powerful new tool to assist in the detection of problems caused by uninitialized variables. + @node Pragma Inline_Always + @unnumberedsec Pragma Inline_Always @findex Inline_Always @noindent Syntax: ! @smallexample @c ada pragma Inline_Always (NAME [, NAME]); @end smallexample @noindent Similar to pragma @code{Inline} except that inlining is not subject to ! the use of option @code{-gnatn} and the inlining happens regardless of ! whether this option is used. + @node Pragma Inline_Generic + @unnumberedsec Pragma Inline_Generic @findex Inline_Generic @noindent Syntax: ! @smallexample @c ada ! pragma Inline_Generic (generic_package_NAME); @end smallexample @noindent *************** This is implemented for compatibility wi *** 1799,1810 **** but otherwise ignored, by GNAT@. All generic instantiations are inlined by default when using GNAT@. @findex Interface - @item pragma Interface @noindent Syntax: ! @smallexample pragma Interface ( [Convention =>] convention_identifier, [Entity =>] local_name --- 2220,2232 ---- but otherwise ignored, by GNAT@. All generic instantiations are inlined by default when using GNAT@. + @node Pragma Interface + @unnumberedsec Pragma Interface @findex Interface @noindent Syntax: ! @smallexample @c ada pragma Interface ( [Convention =>] convention_identifier, [Entity =>] local_name *************** with Ada 83. The definition is upwards *** 1820,1832 **** with some extended implementations of this pragma in certain Ada 83 implementations. @findex Interface_Name - @item pragma Interface_Name @noindent Syntax: ! @smallexample ! pragma Interface_Name ( [Entity =>] LOCAL_NAME [, [External_Name =>] static_string_EXPRESSION] [, [Link_Name =>] static_string_EXPRESSION]); --- 2242,2255 ---- with some extended implementations of this pragma in certain Ada 83 implementations. + @node Pragma Interface_Name + @unnumberedsec Pragma Interface_Name @findex Interface_Name @noindent Syntax: ! @smallexample @c ada ! pragma Interface_Name ( [Entity =>] LOCAL_NAME [, [External_Name =>] static_string_EXPRESSION] [, [Link_Name =>] static_string_EXPRESSION]); *************** for an interfaced subprogram, and is pro *** 1838,1859 **** 83 compilers that use the pragma for this purpose. You must provide at least one of @var{External_Name} or @var{Link_Name}. @findex License - @item pragma License @cindex License checking @noindent Syntax: ! @smallexample pragma License (Unrestricted | GPL | Modified_GPL | Restricted); @end smallexample @noindent This pragma is provided to allow automated checking for appropriate license ! conditions with respect to the standard and modified GPL@. A pragma @code{License}, ! which is a configuration pragma that typically appears at the start of a ! source file or in a separate @file{gnat.adc} file, specifies the licensing ! conditions of a unit as follows: @itemize @bullet @item Unrestricted --- 2261,2399 ---- 83 compilers that use the pragma for this purpose. You must provide at least one of @var{External_Name} or @var{Link_Name}. + @node Pragma Interrupt_Handler + @unnumberedsec Pragma Interrupt_Handler + @findex Interrupt_Handler + @noindent + Syntax: + + @smallexample @c ada + pragma Interrupt_Handler (procedure_LOCAL_NAME); + @end smallexample + + @noindent + This program unit pragma is supported for parameterless protected procedures + as described in Annex C of the Ada Reference Manual. On the AAMP target + the pragma can also be specified for nonprotected parameterless procedures + that are declared at the library level (which includes procedures + declared at the top level of a library package). In the case of AAMP, + when this pragma is applied to a nonprotected procedure, the instruction + @code{IERET} is generated for returns from the procedure, enabling + maskable interrupts, in place of the normal return instruction. + + @node Pragma Interrupt_State + @unnumberedsec Pragma Interrupt_State + @findex Interrupt_State + @noindent + Syntax: + + @smallexample @c ada + pragma Interrupt_State (Name => value, State => SYSTEM | RUNTIME | USER); + @end smallexample + + @noindent + Normally certain interrupts are reserved to the implementation. Any attempt + to attach an interrupt causes Program_Error to be raised, as described in + RM C.3.2(22). A typical example is the @code{SIGINT} interrupt used in + many systems for an @kbd{Ctrl-C} interrupt. Normally this interrupt is + reserved to the implementation, so that @kbd{Ctrl-C} can be used to + interrupt execution. Additionally, signals such as @code{SIGSEGV}, + @code{SIGABRT}, @code{SIGFPE} and @code{SIGILL} are often mapped to specific + Ada exceptions, or used to implement run-time functions such as the + @code{abort} statement and stack overflow checking. + + Pragma @code{Interrupt_State} provides a general mechanism for overriding + such uses of interrupts. It subsumes the functionality of pragma + @code{Unreserve_All_Interrupts}. Pragma @code{Interrupt_State} is not + available on OS/2, Windows or VMS. On all other platforms than VxWorks, + it applies to signals; on VxWorks, it applies to vectored hardware interrupts + and may be used to mark interrupts required by the board support package + as reserved. + + Interrupts can be in one of three states: + @itemize @bullet + @item System + + The interrupt is reserved (no Ada handler can be installed), and the + Ada run-time may not install a handler. As a result you are guaranteed + standard system default action if this interrupt is raised. + + @item Runtime + + The interrupt is reserved (no Ada handler can be installed). The run time + is allowed to install a handler for internal control purposes, but is + not required to do so. + + @item User + + The interrupt is unreserved. The user may install a handler to provide + some other action. + @end itemize + + @noindent + These states are the allowed values of the @code{State} parameter of the + pragma. The @code{Name} parameter is a value of the type + @code{Ada.Interrupts.Interrupt_ID}. Typically, it is a name declared in + @code{Ada.Interrupts.Names}. + + This is a configuration pragma, and the binder will check that there + are no inconsistencies between different units in a partition in how a + given interrupt is specified. It may appear anywhere a pragma is legal. + + The effect is to move the interrupt to the specified state. + + By declaring interrupts to be SYSTEM, you guarantee the standard system + action, such as a core dump. + + By declaring interrupts to be USER, you guarantee that you can install + a handler. + + Note that certain signals on many operating systems cannot be caught and + handled by applications. In such cases, the pragma is ignored. See the + operating system documentation, or the value of the array @code{Reserved} + declared in the specification of package @code{System.OS_Interface}. + + Overriding the default state of signals used by the Ada runtime may interfere + with an application's runtime behavior in the cases of the synchronous signals, + and in the case of the signal used to implement the @code{abort} statement. + + @node Pragma Keep_Names + @unnumberedsec Pragma Keep_Names + @findex Keep_Names + @noindent + Syntax: + + @smallexample @c ada + pragma Keep_Names ([On =>] enumeration_first_subtype_LOCAL_NAME); + @end smallexample + + @noindent + The @var{LOCAL_NAME} argument + must refer to an enumeration first subtype + in the current declarative part. The effect is to retain the enumeration + literal names for use by @code{Image} and @code{Value} even if a global + @code{Discard_Names} pragma applies. This is useful when you want to + generally suppress enumeration literal names and for example you therefore + use a @code{Discard_Names} pragma in the @file{gnat.adc} file, but you + want to retain the names for specific enumeration types. + + @node Pragma License + @unnumberedsec Pragma License @findex License @cindex License checking @noindent Syntax: ! @smallexample @c ada pragma License (Unrestricted | GPL | Modified_GPL | Restricted); @end smallexample @noindent This pragma is provided to allow automated checking for appropriate license ! conditions with respect to the standard and modified GPL@. A pragma ! @code{License}, which is a configuration pragma that typically appears at ! the start of a source file or in a separate @file{gnat.adc} file, specifies ! the licensing conditions of a unit as follows: @itemize @bullet @item Unrestricted *************** are recognized, and license information *** 1890,1903 **** @itemize @bullet A GNAT license header starts with a line containing 78 hyphens. The following ! comment text is searched for the appearence of any of the following strings. If the string ``GNU General Public License'' is found, then the unit is assumed to have GPL license, unless the string ``As a special exception'' follows, in which case the license is assumed to be modified GPL@. If one of the strings ! ``This specification is adapated from the Ada Semantic Interface'' or ``This specification is derived from the Ada Reference Manual'' is found then the unit is assumed to be unrestricted. @end itemize --- 2430,2443 ---- @itemize @bullet A GNAT license header starts with a line containing 78 hyphens. The following ! comment text is searched for the appearance of any of the following strings. If the string ``GNU General Public License'' is found, then the unit is assumed to have GPL license, unless the string ``As a special exception'' follows, in which case the license is assumed to be modified GPL@. If one of the strings ! ``This specification is adapted from the Ada Semantic Interface'' or ``This specification is derived from the Ada Reference Manual'' is found then the unit is assumed to be unrestricted. @end itemize *************** These default actions means that a progr *** 1907,1917 **** will automatically get warnings if a GPL unit is inappropriately @code{with}'ed. For example, the program: ! @smallexample with Sem_Ch3; with GNAT.Sockets; procedure Secret_Stuff is ! @dots{} end Secret_Stuff @end smallexample --- 2447,2457 ---- will automatically get warnings if a GPL unit is inappropriately @code{with}'ed. For example, the program: ! @smallexample @c ada with Sem_Ch3; with GNAT.Sockets; procedure Secret_Stuff is ! @dots{} end Secret_Stuff @end smallexample *************** if compiled with pragma @code{License} ( *** 1927,1944 **** 2. with GNAT.Sockets; 3. procedure Secret_Stuff is @end smallexample @noindent Here we get a warning on @code{Sem_Ch3} since it is part of the GNAT compiler and is licensed under the ! GPL, but no warning for @code{GNAT.Sockets} which is part of the GNAT run time, and is therefore licensed under the modified GPL@. @findex Link_With - @item pragma Link_With @noindent Syntax: ! @smallexample pragma Link_With (static_string_EXPRESSION @{,static_string_EXPRESSION@}); @end smallexample --- 2467,2486 ---- 2. with GNAT.Sockets; 3. procedure Secret_Stuff is @end smallexample + @noindent Here we get a warning on @code{Sem_Ch3} since it is part of the GNAT compiler and is licensed under the ! GPL, but no warning for @code{GNAT.Sockets} which is part of the GNAT run time, and is therefore licensed under the modified GPL@. + @node Pragma Link_With + @unnumberedsec Pragma Link_With @findex Link_With @noindent Syntax: ! @smallexample @c ada pragma Link_With (static_string_EXPRESSION @{,static_string_EXPRESSION@}); @end smallexample *************** It has exactly the same effect as pragma *** 1948,1954 **** that spaces occurring within one of the string expressions are treated as separators. For example, in the following case: ! @smallexample pragma Link_With ("-labc -ldef"); @end smallexample --- 2490,2496 ---- that spaces occurring within one of the string expressions are treated as separators. For example, in the following case: ! @smallexample @c ada pragma Link_With ("-labc -ldef"); @end smallexample *************** results in passing the strings @code{-la *** 1957,1968 **** separate arguments to the linker. In addition pragma Link_With allows multiple arguments, with the same effect as successive pragmas. @findex Linker_Alias - @item pragma Linker_Alias @noindent Syntax: ! @smallexample pragma Linker_Alias ( [Entity =>] LOCAL_NAME [Alias =>] static_string_EXPRESSION); --- 2499,2511 ---- separate arguments to the linker. In addition pragma Link_With allows multiple arguments, with the same effect as successive pragmas. + @node Pragma Linker_Alias + @unnumberedsec Pragma Linker_Alias @findex Linker_Alias @noindent Syntax: ! @smallexample @c ada pragma Linker_Alias ( [Entity =>] LOCAL_NAME [Alias =>] static_string_EXPRESSION); *************** pragma Linker_Alias ( *** 1972,1983 **** This pragma establishes a linker alias for the given named entity. For further details on the exact effect, consult the GCC manual. @findex Linker_Section - @item pragma Linker_Section @noindent Syntax: ! @smallexample pragma Linker_Section ( [Entity =>] LOCAL_NAME [Section =>] static_string_EXPRESSION); --- 2515,2527 ---- This pragma establishes a linker alias for the given named entity. For further details on the exact effect, consult the GCC manual. + @node Pragma Linker_Section + @unnumberedsec Pragma Linker_Section @findex Linker_Section @noindent Syntax: ! @smallexample @c ada pragma Linker_Section ( [Entity =>] LOCAL_NAME [Section =>] static_string_EXPRESSION); *************** pragma Linker_Section ( *** 1987,2075 **** This pragma specifies the name of the linker section for the given entity. For further details on the exact effect, consult the GCC manual. ! @findex No_Run_Time ! @item pragma No_Run_Time ! @noindent ! Syntax: ! ! @smallexample ! pragma No_Run_Time; ! @end smallexample ! ! @noindent ! This is a configuration pragma that makes sure the user code does not ! use nor need anything from the GNAT run time. This is mostly useful in ! context where code certification is required. Please consult the ! @cite{GNAT Pro High-Integrity Edition User's Guide} for additional information. ! ! @findex Normalize_Scalars ! @item pragma Normalize_Scalars ! @noindent ! Syntax: ! ! @smallexample ! pragma Normalize_Scalars; ! @end smallexample ! ! @noindent ! This is a language defined pragma which is fully implemented in GNAT@. The ! effect is to cause all scalar objects that are not otherwise initialized ! to be initialized. The initial values are implementation dependent and ! are as follows: ! ! @table @code ! @item Standard.Character ! @noindent ! Objects whose root type is Standard.Character are initialized to ! Character'Last. This will be out of range of the subtype only if ! the subtype range excludes this value. ! ! @item Standard.Wide_Character ! @noindent ! Objects whose root type is Standard.Wide_Character are initialized to ! Wide_Character'Last. This will be out of range of the subtype only if ! the subtype range excludes this value. ! ! @item Integer types ! @noindent ! Objects of an integer type are initialized to base_type'First, where ! base_type is the base type of the object type. This will be out of range ! of the subtype only if the subtype range excludes this value. For example, ! if you declare the subtype: ! ! @smallexample ! subtype Ityp is integer range 1 .. 10; ! @end smallexample ! ! @noindent ! then objects of type x will be initialized to Integer'First, a negative ! number that is certainly outside the range of subtype @code{Ityp}. ! ! @item Real types ! Objects of all real types (fixed and floating) are initialized to ! base_type'First, where base_Type is the base type of the object type. ! This will be out of range of the subtype only if the subtype range ! excludes this value. ! ! @item Modular types ! Objects of a modular type are initialized to typ'Last. This will be out ! of range of the subtype only if the subtype excludes this value. ! ! @item Enumeration types ! Objects of an enumeration type are initialized to all one-bits, i.e.@: to ! the value @code{2 ** typ'Size - 1}. This will be out of range of the enumeration ! subtype in all cases except where the subtype contains exactly ! 2**8, 2**16, or 2**32 elements. ! ! @end table ! @cindex OpenVMS @findex Long_Float - @item pragma Long_Float @noindent Syntax: ! @smallexample pragma Long_Float (FLOAT_FORMAT); FLOAT_FORMAT ::= D_Float | G_Float --- 2531,2544 ---- This pragma specifies the name of the linker section for the given entity. For further details on the exact effect, consult the GCC manual. ! @node Pragma Long_Float ! @unnumberedsec Pragma Long_Float @cindex OpenVMS @findex Long_Float @noindent Syntax: ! @smallexample @c ada pragma Long_Float (FLOAT_FORMAT); FLOAT_FORMAT ::= D_Float | G_Float *************** It allows control over the internal repr *** 2081,2119 **** type @code{Long_Float} and for floating point type representations with @code{digits} specified in the range 7 through 15. For further details on this pragma, see the ! @cite{DEC Ada Language Reference Manual}, section 3.5.7b. Note that to use this ! pragma, the standard runtime libraries must be recompiled. See the description of the @code{GNAT LIBRARY} command in the OpenVMS version of the GNAT User's Guide for details on the use of this command. @findex Machine_Attribute - @item pragma Machine_Attribute @dots{} @noindent Syntax: ! @smallexample pragma Machine_Attribute ( [Attribute_Name =>] string_EXPRESSION, [Entity =>] LOCAL_NAME); @end smallexample Machine dependent attributes can be specified for types and/or declarations. Currently only subprogram entities are supported. This ! pragma is semantically equivalent to ! @code{__attribute__((@var{string_expression}))} in GNU C, where @code{@var{string_expression}} is recognized by the GNU C macros @code{VALID_MACHINE_TYPE_ATTRIBUTE} and @code{VALID_MACHINE_DECL_ATTRIBUTE} which are defined in the configuration header file @file{tm.h} for each machine. See the GCC manual for further information. @cindex OpenVMS @findex Main_Storage - @item pragma Main_Storage @noindent Syntax: ! @smallexample pragma Main_Storage (MAIN_STORAGE_OPTION [, MAIN_STORAGE_OPTION]); --- 2550,2591 ---- type @code{Long_Float} and for floating point type representations with @code{digits} specified in the range 7 through 15. For further details on this pragma, see the ! @cite{DEC Ada Language Reference Manual}, section 3.5.7b. Note that to use ! this pragma, the standard runtime libraries must be recompiled. See the description of the @code{GNAT LIBRARY} command in the OpenVMS version of the GNAT User's Guide for details on the use of this command. + @node Pragma Machine_Attribute + @unnumberedsec Pragma Machine_Attribute @findex Machine_Attribute @noindent Syntax: ! @smallexample @c ada pragma Machine_Attribute ( [Attribute_Name =>] string_EXPRESSION, [Entity =>] LOCAL_NAME); @end smallexample + @noindent Machine dependent attributes can be specified for types and/or declarations. Currently only subprogram entities are supported. This ! pragma is semantically equivalent to ! @code{__attribute__((@var{string_expression}))} in GNU C, where @code{@var{string_expression}} is recognized by the GNU C macros @code{VALID_MACHINE_TYPE_ATTRIBUTE} and @code{VALID_MACHINE_DECL_ATTRIBUTE} which are defined in the configuration header file @file{tm.h} for each machine. See the GCC manual for further information. + @node Pragma Main_Storage + @unnumberedsec Pragma Main_Storage @cindex OpenVMS @findex Main_Storage @noindent Syntax: ! @smallexample @c ada pragma Main_Storage (MAIN_STORAGE_OPTION [, MAIN_STORAGE_OPTION]); *************** MAIN_STORAGE_OPTION ::= *** 2124,2139 **** @end smallexample @noindent ! This pragma is provided for compatibility with OpenVMS Vax Systems. It has no effect in GNAT, other than being syntax checked. Note that the pragma also has no effect in DEC Ada 83 for OpenVMS Alpha Systems. @findex No_Return - @item pragma No_Return @noindent Syntax: ! @smallexample pragma No_Return (procedure_LOCAL_NAME); @end smallexample --- 2596,2612 ---- @end smallexample @noindent ! This pragma is provided for compatibility with OpenVMS VAX Systems. It has no effect in GNAT, other than being syntax checked. Note that the pragma also has no effect in DEC Ada 83 for OpenVMS Alpha Systems. + @node Pragma No_Return + @unnumberedsec Pragma No_Return @findex No_Return @noindent Syntax: ! @smallexample @c ada pragma No_Return (procedure_LOCAL_NAME); @end smallexample *************** Another use of this pragma is to suppres *** 2149,2160 **** missing returns in functions, where the last statement of a function statement sequence is a call to such a procedure. @findex Passive - @item pragma Passive @noindent Syntax: ! @smallexample pragma Passive ([Semaphore | No]); @end smallexample --- 2622,2719 ---- missing returns in functions, where the last statement of a function statement sequence is a call to such a procedure. + @node Pragma Normalize_Scalars + @unnumberedsec Pragma Normalize_Scalars + @findex Normalize_Scalars + @noindent + Syntax: + + @smallexample @c ada + pragma Normalize_Scalars; + @end smallexample + + @noindent + This is a language defined pragma which is fully implemented in GNAT@. The + effect is to cause all scalar objects that are not otherwise initialized + to be initialized. The initial values are implementation dependent and + are as follows: + + @table @code + @item Standard.Character + @noindent + Objects whose root type is Standard.Character are initialized to + Character'Last. This will be out of range of the subtype only if + the subtype range excludes this value. + + @item Standard.Wide_Character + @noindent + Objects whose root type is Standard.Wide_Character are initialized to + Wide_Character'Last. This will be out of range of the subtype only if + the subtype range excludes this value. + + @item Integer types + @noindent + Objects of an integer type are initialized to base_type'First, where + base_type is the base type of the object type. This will be out of range + of the subtype only if the subtype range excludes this value. For example, + if you declare the subtype: + + @smallexample @c ada + subtype Ityp is integer range 1 .. 10; + @end smallexample + + @noindent + then objects of type x will be initialized to Integer'First, a negative + number that is certainly outside the range of subtype @code{Ityp}. + + @item Real types + Objects of all real types (fixed and floating) are initialized to + base_type'First, where base_Type is the base type of the object type. + This will be out of range of the subtype only if the subtype range + excludes this value. + + @item Modular types + Objects of a modular type are initialized to typ'Last. This will be out + of range of the subtype only if the subtype excludes this value. + + @item Enumeration types + Objects of an enumeration type are initialized to all one-bits, i.e.@: to + the value @code{2 ** typ'Size - 1}. This will be out of range of the + enumeration subtype in all cases except where the subtype contains + exactly 2**8, 2**16, or 2**32 elements. + + @end table + + @node Pragma Obsolescent + @unnumberedsec Pragma Obsolescent + @findex Obsolescent + @noindent + Syntax: + + @smallexample @c ada + pragma Obsolescent [(static_string_EXPRESSION)]; + @end smallexample + + @noindent + This pragma must occur immediately following a subprogram + declaration. It indicates that the associated function or procedure + is considered obsolescent and should not be used. Typically this is + used when an API must be modified by eventually removing or modifying + existing subprograms. The pragma can be used at an intermediate stage + when the subprogram is still present, but will be removed later. + + The effect of this pragma is to output a warning message that the + subprogram is obsolescent if the appropriate warning option in the + compiler is activated. If a parameter is present, then a second + warning message is given containing this text. + + @node Pragma Passive + @unnumberedsec Pragma Passive @findex Passive @noindent Syntax: ! @smallexample @c ada pragma Passive ([Semaphore | No]); @end smallexample *************** pragma Passive ([Semaphore | No]); *** 2162,2180 **** Syntax checked, but otherwise ignored by GNAT@. This is recognized for compatibility with DEC Ada 83 implementations, where it is used within a task definition to request that a task be made passive. If the argument ! @code{Semaphore} is present, or no argument is omitted, then DEC Ada 83 treats the pragma as an assertion that the containing task is passive and that optimization of context switch with this task is permitted and desired. If the argument @code{No} is present, the task must not be optimized. GNAT does not attempt to optimize any tasks in this manner (since protected objects are available in place of passive tasks). ! @findex Polling ! @item pragma Polling @noindent Syntax: ! @smallexample pragma Polling (ON | OFF); @end smallexample --- 2721,2740 ---- Syntax checked, but otherwise ignored by GNAT@. This is recognized for compatibility with DEC Ada 83 implementations, where it is used within a task definition to request that a task be made passive. If the argument ! @code{Semaphore} is present, or the argument is omitted, then DEC Ada 83 treats the pragma as an assertion that the containing task is passive and that optimization of context switch with this task is permitted and desired. If the argument @code{No} is present, the task must not be optimized. GNAT does not attempt to optimize any tasks in this manner (since protected objects are available in place of passive tasks). ! @node Pragma Polling ! @unnumberedsec Pragma Polling ! @findex Polling @noindent Syntax: ! @smallexample @c ada pragma Polling (ON | OFF); @end smallexample *************** If @code{pragma Polling (ON)} is used th *** 2184,2231 **** the routine @code{Ada.Exceptions.Poll}. This routine is a separate unit in the runtime library, and can be found in file @file{a-excpol.adb}. ! Pragma @code{Polling} can appear as a configuration pragma (for example it can be ! placed in the @file{gnat.adc} file) to enable polling globally, or it can be used ! in the statement or declaration sequence to control polling more locally. A call to the polling routine is generated at the start of every loop and at the start of every subprogram call. This guarantees that the @code{Poll} routine is called frequently, and places an upper bound (determined by the complexity of the code) on the period between two @code{Poll} calls. ! The primary purpose of the polling interface is to enable asynchronous aborts on targets that cannot otherwise support it (for example Windows NT), but it may be used for any other purpose requiring periodic polling. The standard version is null, and can be replaced by a user program. This ! will require re-compilation of the @code{Ada.Exceptions} package that can be found ! in files @file{a-except.ads} and @file{a-except.adb}. A standard alternative unit (in file @file{4wexcpol.adb} in the standard GNAT distribution) is used to enable the asynchronous abort capability on ! targets that do not normally support the capability. The version of @code{Poll} ! in this file makes a call to the appropriate runtime routine to test for ! an abort condition. Note that polling can also be enabled by use of the @code{-gnatP} switch. See the @cite{GNAT User's Guide} for details. @findex Propagate_Exceptions @cindex Zero Cost Exceptions - @item pragma Propagate_Exceptions @noindent Syntax: ! @smallexample pragma Propagate_Exceptions (subprogram_LOCAL_NAME); @end smallexample @noindent This pragma indicates that the given entity, which is the name of an ! imported foreign-language subprogram may receive an Ada exception, and that the exception should be propagated. It is relevant only if zero cost exception handling is in use, and is thus never needed if ! the alternative @code{longjmp} / @code{setjmp} implementation of exceptions is used ! (although it is harmless to use it in such cases). The implementation of fast exceptions always properly propagates exceptions through Ada code, as described in the Ada Reference Manual. --- 2744,2793 ---- the routine @code{Ada.Exceptions.Poll}. This routine is a separate unit in the runtime library, and can be found in file @file{a-excpol.adb}. ! Pragma @code{Polling} can appear as a configuration pragma (for example it ! can be placed in the @file{gnat.adc} file) to enable polling globally, or it ! can be used in the statement or declaration sequence to control polling ! more locally. A call to the polling routine is generated at the start of every loop and at the start of every subprogram call. This guarantees that the @code{Poll} routine is called frequently, and places an upper bound (determined by the complexity of the code) on the period between two @code{Poll} calls. ! The primary purpose of the polling interface is to enable asynchronous aborts on targets that cannot otherwise support it (for example Windows NT), but it may be used for any other purpose requiring periodic polling. The standard version is null, and can be replaced by a user program. This ! will require re-compilation of the @code{Ada.Exceptions} package that can ! be found in files @file{a-except.ads} and @file{a-except.adb}. A standard alternative unit (in file @file{4wexcpol.adb} in the standard GNAT distribution) is used to enable the asynchronous abort capability on ! targets that do not normally support the capability. The version of ! @code{Poll} in this file makes a call to the appropriate runtime routine ! to test for an abort condition. Note that polling can also be enabled by use of the @code{-gnatP} switch. See the @cite{GNAT User's Guide} for details. + @node Pragma Propagate_Exceptions + @unnumberedsec Pragma Propagate_Exceptions @findex Propagate_Exceptions @cindex Zero Cost Exceptions @noindent Syntax: ! @smallexample @c ada pragma Propagate_Exceptions (subprogram_LOCAL_NAME); @end smallexample @noindent This pragma indicates that the given entity, which is the name of an ! imported foreign-language subprogram may receive an Ada exception, and that the exception should be propagated. It is relevant only if zero cost exception handling is in use, and is thus never needed if ! the alternative @code{longjmp} / @code{setjmp} implementation of ! exceptions is used (although it is harmless to use it in such cases). The implementation of fast exceptions always properly propagates exceptions through Ada code, as described in the Ada Reference Manual. *************** situation where @code{P1} calls *** 2235,2263 **** @code{P2}, and @code{P2} calls @code{P3}, where @code{P1} and @code{P3} are in Ada, but @code{P2} is in C@. @code{P3} raises an Ada exception. The question is whether or not ! it will be propagated through @code{P2} and can be handled in @code{P1}. ! For the @code{longjmp} / @code{setjmp} implementation of exceptions, the answer is ! always yes. For some targets on which zero cost exception handling ! is implemented, the answer is also always yes. However, there are ! some targets, notably in the current version all x86 architecture targets, in which the answer is that such propagation does not happen automatically. If such propagation is required on these ! targets, it is mandatory to use @code{Propagate_Exceptions} to name all foreign language routines through which Ada exceptions may be propagated. @findex Psect_Object - @item pragma Psect_Object @noindent Syntax: ! @smallexample ! pragma Psect_Object [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] ! [, [Size =>] EXTERNAL_SYMBOL] EXTERNAL_SYMBOL ::= IDENTIFIER --- 2797,2826 ---- @code{P2}, and @code{P2} calls @code{P3}, where @code{P1} and @code{P3} are in Ada, but @code{P2} is in C@. @code{P3} raises an Ada exception. The question is whether or not ! it will be propagated through @code{P2} and can be handled in @code{P1}. ! For the @code{longjmp} / @code{setjmp} implementation of exceptions, ! the answer is always yes. For some targets on which zero cost exception ! handling is implemented, the answer is also always yes. However, there ! are some targets, notably in the current version all x86 architecture targets, in which the answer is that such propagation does not happen automatically. If such propagation is required on these ! targets, it is mandatory to use @code{Propagate_Exceptions} to name all foreign language routines through which Ada exceptions may be propagated. + @node Pragma Psect_Object + @unnumberedsec Pragma Psect_Object @findex Psect_Object @noindent Syntax: ! @smallexample @c ada ! pragma Psect_Object ( [Internal =>] LOCAL_NAME, [, [External =>] EXTERNAL_SYMBOL] ! [, [Size =>] EXTERNAL_SYMBOL]); EXTERNAL_SYMBOL ::= IDENTIFIER *************** EXTERNAL_SYMBOL ::= *** 2267,2285 **** @noindent This pragma is identical in effect to pragma @code{Common_Object}. @findex Pure_Function - @item pragma Pure_Function @noindent Syntax: ! @smallexample pragma Pure_Function ([Entity =>] function_LOCAL_NAME); @end smallexample This pragma appears in the same declarative part as a function declaration (or a set of function declarations if more than one overloaded declaration exists, in which case the pragma applies ! to all entities). If specifies that the function @code{Entity} is to be considered pure for the purposes of code generation. This means that the compiler can assume that there are no side effects, and in particular that two calls with identical arguments produce the --- 2830,2850 ---- @noindent This pragma is identical in effect to pragma @code{Common_Object}. + @node Pragma Pure_Function + @unnumberedsec Pragma Pure_Function @findex Pure_Function @noindent Syntax: ! @smallexample @c ada pragma Pure_Function ([Entity =>] function_LOCAL_NAME); @end smallexample + @noindent This pragma appears in the same declarative part as a function declaration (or a set of function declarations if more than one overloaded declaration exists, in which case the pragma applies ! to all entities). It specifies that the function @code{Entity} is to be considered pure for the purposes of code generation. This means that the compiler can assume that there are no side effects, and in particular that two calls with identical arguments produce the *************** avoid re-computation). *** 2298,2324 **** @findex Pure Note: Most functions in a @code{Pure} package are automatically pure, and ! there is no need to use pragma @code{Pure_Function} for such functions. An exception is any function that has at least one formal of type @code{System.Address} or a type derived from it. Such functions are not considered pure by default, since the compiler assumes that the @code{Address} parameter may be functioning as a pointer and that the ! referenced data may change even if the address value does not. The use ! of pragma @code{Pure_Function} for such a function will override this default ! assumption, and cause the compiler to treat such a function as pure. Note: If pragma @code{Pure_Function} is applied to a renamed function, it applies to the underlying renamed function. This can be used to disambiguate cases of overloading where some but not all functions in a set of overloaded functions are to be designated as pure. @findex Ravenscar - @item pragma Ravenscar @noindent Syntax: ! @smallexample ! pragma Ravenscar @end smallexample @noindent --- 2863,2893 ---- @findex Pure Note: Most functions in a @code{Pure} package are automatically pure, and ! there is no need to use pragma @code{Pure_Function} for such functions. One exception is any function that has at least one formal of type @code{System.Address} or a type derived from it. Such functions are not considered pure by default, since the compiler assumes that the @code{Address} parameter may be functioning as a pointer and that the ! referenced data may change even if the address value does not. ! Similarly, imported functions are not consdered to be pure by default, ! since there is no way of checking that they are in fact pure. The use ! of pragma @code{Pure_Function} for such a function will override these default ! assumption, and cause the compiler to treat a designated subprogram as pure ! in these cases. Note: If pragma @code{Pure_Function} is applied to a renamed function, it applies to the underlying renamed function. This can be used to disambiguate cases of overloading where some but not all functions in a set of overloaded functions are to be designated as pure. + @node Pragma Ravenscar + @unnumberedsec Pragma Ravenscar @findex Ravenscar @noindent Syntax: ! @smallexample @c ada ! pragma Ravenscar; @end smallexample @noindent *************** A configuration pragma that establishes *** 2326,2340 **** @table @code @item No_Abort_Statements ! [RM D.7] There are no abort_statements, and there are no calls to Task_Identification.Abort_Task. @item No_Select_Statements There are no select_statements. @item No_Task_Hierarchy ! [RM D.7] All (non-environment) tasks depend ! directly on the environment task of the partition. @item No_Task_Allocators [RM D.7] There are no allocators for task types --- 2895,2909 ---- @table @code @item No_Abort_Statements ! [RM D.7] There are no abort_statements, and there are no calls to Task_Identification.Abort_Task. @item No_Select_Statements There are no select_statements. @item No_Task_Hierarchy ! [RM D.7] All (non-environment) tasks depend ! directly on the environment task of the partition. @item No_Task_Allocators [RM D.7] There are no allocators for task types *************** or types containing task subcomponents. *** 2349,2360 **** @item No_Dynamic_Interrupts There are no semantic dependencies on Ada.Interrupts. @item No_Protected_Type_Allocators There are no allocators for protected types or types containing protected subcomponents. @item No_Local_Protected_Objects ! Protected objects and access types that designate such objects shall be declared only at library level. @item No_Requeue --- 2918,2932 ---- @item No_Dynamic_Interrupts There are no semantic dependencies on Ada.Interrupts. + @item No_Implicit_Heap_Allocations + [RM D.7] No constructs are allowed to cause implicit heap allocation + @item No_Protected_Type_Allocators There are no allocators for protected types or types containing protected subcomponents. @item No_Local_Protected_Objects ! Protected objects and access types that designate such objects shall be declared only at library level. @item No_Requeue *************** There are no delay_relative_statements. *** 2370,2381 **** There are no semantic dependencies on the Ada.Task_Attributes package and there are no references to the attributes Callable and Terminated [RM 9.9]. - @item Static_Storage_Size - The expression for pragma Storage_Size is static. - @item Boolean_Entry_Barriers ! Entry barrier condition expressions shall be boolean ! objects which are declared in the protected type which contains the entry. @item Max_Asynchronous_Select_Nesting = 0 --- 2942,2950 ---- There are no semantic dependencies on the Ada.Task_Attributes package and there are no references to the attributes Callable and Terminated [RM 9.9]. @item Boolean_Entry_Barriers ! Entry barrier condition expressions shall be boolean ! objects which are declared in the protected type which contains the entry. @item Max_Asynchronous_Select_Nesting = 0 *************** the Ravenscar pragma, the value of Max_T *** 2393,2408 **** 0 (zero). @item Max_Protected_Entries = 1 ! [RM D.7] Specifies the maximum number of entries per ! protected type. The bounds of every entry family of ! a protected unit shall be static, or shall be defined ! by a discriminant of a subtype whose corresponding ! bound is static. For the Ravenscar pragma the value of Max_Protected_Entries is always 1. @item Max_Select_Alternatives = 0 [RM D.7] Specifies the maximum number of alternatives in a selective_accept. ! For the Ravenscar pragma the value if always 0. @item No_Task_Termination Tasks which terminate are erroneous. --- 2962,2977 ---- 0 (zero). @item Max_Protected_Entries = 1 ! [RM D.7] Specifies the maximum number of entries per ! protected type. The bounds of every entry family of ! a protected unit shall be static, or shall be defined ! by a discriminant of a subtype whose corresponding ! bound is static. For the Ravenscar pragma the value of Max_Protected_Entries is always 1. @item Max_Select_Alternatives = 0 [RM D.7] Specifies the maximum number of alternatives in a selective_accept. ! For the Ravenscar pragma the value is always 0. @item No_Task_Termination Tasks which terminate are erroneous. *************** Program_Error exception. *** 2415,2439 **** @noindent This set of restrictions corresponds to the definition of the ``Ravenscar ! Profile'' for limited tasking, devised and published by the @cite{International ! Real-Time Ada Workshop}, 1997. The above set is a superset of the restrictions provided by pragma ! @code{Restricted_Run_Time}, it includes six additional restrictions (@code{Boolean_Entry_Barriers}, @code{No_Select_Statements}, ! @code{No_Calendar}, @code{Static_Storage_Size}, @code{No_Relative_Delay} and @code{No_Task_Termination}). This means ! that pragma @code{Ravenscar}, like the pragma @code{Restricted_Run_Time}, automatically ! causes the use of a simplified, more efficient version of the tasking ! run-time system. @findex Restricted_Run_Time - @item pragma Restricted_Run_Time @noindent Syntax: ! @smallexample ! pragma Restricted_Run_Time @end smallexample @noindent --- 2984,3011 ---- @noindent This set of restrictions corresponds to the definition of the ``Ravenscar ! Profile'' for limited tasking, devised and published by the ! @cite{International Real-Time Ada Workshop}, 1997, ! and whose most recent description is available at ! @url{ftp://ftp.openravenscar.org/openravenscar/ravenscar00.pdf}. The above set is a superset of the restrictions provided by pragma ! @code{Restricted_Run_Time}, it includes five additional restrictions (@code{Boolean_Entry_Barriers}, @code{No_Select_Statements}, ! @code{No_Calendar}, @code{No_Relative_Delay} and @code{No_Task_Termination}). This means ! that pragma @code{Ravenscar}, like the pragma @code{Restricted_Run_Time}, ! automatically causes the use of a simplified, more efficient version ! of the tasking run-time system. + @node Pragma Restricted_Run_Time + @unnumberedsec Pragma Restricted_Run_Time @findex Restricted_Run_Time @noindent Syntax: ! @smallexample @c ada ! pragma Restricted_Run_Time; @end smallexample @noindent *************** A configuration pragma that establishes *** 2441,2447 **** @itemize @bullet @item No_Abort_Statements - @item No_Asynchronous_Control @item No_Entry_Queue @item No_Task_Hierarchy @item No_Task_Allocators --- 3013,3018 ---- *************** This set of restrictions causes the auto *** 2463,2489 **** version of the run time that provides improved performance for the limited set of tasking functionality permitted by this set of restrictions. ! @findex Share_Generic ! @item pragma Share_Generic @noindent Syntax: ! @smallexample ! pragma Share_Generic (NAME @{, NAME@}); @end smallexample @noindent ! This pragma is recognized for compatibility with other Ada compilers ! but is ignored by GNAT@. GNAT does not provide the capability for ! sharing of generic code. All generic instantiations result in making ! an inlined copy of the template with appropriate substitutions. @findex Source_File_Name - @item pragma Source_File_Name @noindent Syntax: ! @smallexample pragma Source_File_Name ( [Unit_Name =>] unit_NAME, Spec_File_Name => STRING_LITERAL); --- 3034,3065 ---- version of the run time that provides improved performance for the limited set of tasking functionality permitted by this set of restrictions. ! @node Pragma Restriction_Warnings ! @unnumberedsec Pragma Restriction_Warnings ! @findex Restriction_Warnings @noindent Syntax: ! @smallexample @c ada ! pragma Restriction_Warnings ! (restriction_IDENTIFIER @{, restriction_IDENTIFIER@}); @end smallexample @noindent ! This pragma allows a series of restriction identifiers to be ! specified (the list of allowed identifiers is the same as for ! pragma @code{Restrictions}). For each of these identifiers ! the compiler checks for violations of the restriction, but ! generates a warning message rather than an error message ! if the restriction is violated. + @node Pragma Source_File_Name + @unnumberedsec Pragma Source_File_Name @findex Source_File_Name @noindent Syntax: ! @smallexample @c ada pragma Source_File_Name ( [Unit_Name =>] unit_NAME, Spec_File_Name => STRING_LITERAL); *************** name for the spec or for the body. *** 2504,2512 **** Another form of the @code{Source_File_Name} pragma allows the specification of patterns defining alternative file naming schemes ! to apply to all files. ! @smallexample pragma Source_File_Name (Spec_File_Name => STRING_LITERAL [,Casing => CASING_SPEC] --- 3080,3088 ---- Another form of the @code{Source_File_Name} pragma allows the specification of patterns defining alternative file naming schemes ! to apply to all files. ! @smallexample @c ada pragma Source_File_Name (Spec_File_Name => STRING_LITERAL [,Casing => CASING_SPEC] *************** specifies the casing of the unit name in *** 2533,2550 **** The default is lower case. Finally the third argument allows for systematic replacement of any dots in the unit name by the specified string literal. For more details on the use of the @code{Source_File_Name} pragma, ! see the sections ``Using Other File Names'' and ``Alternative File Naming Schemes'' in the @cite{GNAT User's Guide}. @findex Source_Reference - @item pragma Source_Reference @noindent Syntax: ! @smallexample ! pragma Source_Reference (INTEGER_LITERAL, ! STRING_LITERAL); @end smallexample @noindent --- 3109,3146 ---- The default is lower case. Finally the third argument allows for systematic replacement of any dots in the unit name by the specified string literal. + A pragma Source_File_Name cannot appear after a + @ref{Pragma Source_File_Name_Project}. + For more details on the use of the @code{Source_File_Name} pragma, ! see the sections ``Using Other File Names'' and ``Alternative File Naming Schemes'' in the @cite{GNAT User's Guide}. + @node Pragma Source_File_Name_Project + @unnumberedsec Pragma Source_File_Name_Project + @findex Source_File_Name_Project + @noindent + + This pragma has the same syntax and semantics as pragma Source_File_Name. + It is only allowed as a stand alone configuration pragma. + It cannot appear after a @ref{Pragma Source_File_Name}, and + most importantly, once pragma Source_File_Name_Project appears, + no further Source_File_Name pragmas are allowed. + + The intention is that Source_File_Name_Project pragmas are always + generated by the Project Manager in a manner consistent with the naming + specified in a project file, and when naming is controlled in this manner, + it is not permissible to attempt to modify this naming scheme using + Source_File_Name pragmas (which would not be known to the project manager). + + @node Pragma Source_Reference + @unnumberedsec Pragma Source_Reference @findex Source_Reference @noindent Syntax: ! @smallexample @c ada ! pragma Source_Reference (INTEGER_LITERAL, STRING_LITERAL); @end smallexample @noindent *************** The second argument must be a string lit *** 2561,2572 **** string expression other than a string literal. This is because its value is needed for error messages issued by all phases of the compiler. @findex Stream_Convert - @item pragma Stream_Convert @noindent Syntax: ! @smallexample pragma Stream_Convert ( [Entity =>] type_LOCAL_NAME, [Read =>] function_NAME, --- 3157,3169 ---- string expression other than a string literal. This is because its value is needed for error messages issued by all phases of the compiler. + @node Pragma Stream_Convert + @unnumberedsec Pragma Stream_Convert @findex Stream_Convert @noindent Syntax: ! @smallexample @c ada pragma Stream_Convert ( [Entity =>] type_LOCAL_NAME, [Read =>] function_NAME, *************** renamings can be supplied to meet this r *** 2607,2613 **** The usage of this attribute is best illustrated by a simple example, taken from the GNAT implementation of package Ada.Strings.Unbounded: ! @smallexample function To_Unbounded (S : String) return Unbounded_String renames To_Unbounded_String; --- 3204,3210 ---- The usage of this attribute is best illustrated by a simple example, taken from the GNAT implementation of package Ada.Strings.Unbounded: ! @smallexample @c ada function To_Unbounded (S : String) return Unbounded_String renames To_Unbounded_String; *************** pragma Stream_Convert *** 2620,2626 **** The specifications of the referenced functions, as given in the Ada 95 Reference Manual are: ! @smallexample function To_Unbounded_String (Source : String) return Unbounded_String; --- 3217,3223 ---- The specifications of the referenced functions, as given in the Ada 95 Reference Manual are: ! @smallexample @c ada function To_Unbounded_String (Source : String) return Unbounded_String; *************** stream, then the representation of the i *** 2634,2652 **** format used for @code{Standard.String}, and this same representation is expected when a value of this type is read from the stream. @findex Style_Checks - @item pragma Style_Checks @noindent Syntax: ! @smallexample pragma Style_Checks (string_LITERAL | ALL_CHECKS | On | Off [, LOCAL_NAME]); @end smallexample @noindent This pragma is used in conjunction with compiler switches to control the ! built in style checking provided by GNAT@. The compiler switches, if set provide an initial setting for the switches, and this pragma may be used to modify these settings, or the settings may be provided entirely by the use of the pragma. This pragma can be used anywhere that a pragma --- 3231,3250 ---- format used for @code{Standard.String}, and this same representation is expected when a value of this type is read from the stream. + @node Pragma Style_Checks + @unnumberedsec Pragma Style_Checks @findex Style_Checks @noindent Syntax: ! @smallexample @c ada pragma Style_Checks (string_LITERAL | ALL_CHECKS | On | Off [, LOCAL_NAME]); @end smallexample @noindent This pragma is used in conjunction with compiler switches to control the ! built in style checking provided by GNAT@. The compiler switches, if set, provide an initial setting for the switches, and this pragma may be used to modify these settings, or the settings may be provided entirely by the use of the pragma. This pragma can be used anywhere that a pragma *************** used in the @code{-gnaty} switch to @cod *** 2660,2669 **** For example the following two methods can be used to enable layout checking: ! @smallexample pragma Style_Checks ("l"); gcc -c -gnatyl @dots{} @end smallexample @noindent The form ALL_CHECKS activates all standard checks (its use is equivalent --- 3258,3274 ---- For example the following two methods can be used to enable layout checking: ! @itemize @bullet ! @item ! @smallexample @c ada pragma Style_Checks ("l"); + @end smallexample + + @item + @smallexample gcc -c -gnatyl @dots{} @end smallexample + @end itemize @noindent The form ALL_CHECKS activates all standard checks (its use is equivalent *************** The forms with @code{Off} and @code{On} *** 2674,2680 **** can be used to temporarily disable style checks as shown in the following example: ! @smallexample @iftex @leftskip=0cm @end iftex --- 3279,3285 ---- can be used to temporarily disable style checks as shown in the following example: ! @smallexample @c ada @iftex @leftskip=0cm @end iftex *************** Finally the two argument form is allowed *** 2690,2696 **** @code{On} or @code{Off}. The effect is to turn of semantic style checks for the specified entity, as shown in the following example: ! @smallexample @iftex @leftskip=0cm @end iftex --- 3295,3301 ---- @code{On} or @code{Off}. The effect is to turn of semantic style checks for the specified entity, as shown in the following example: ! @smallexample @c ada @iftex @leftskip=0cm @end iftex *************** pragma Style_Checks (Off, Arg); *** 2701,2712 **** Rf2 : Integer := ARG; -- OK, no error @end smallexample @findex Subtitle - @item pragma Subtitle @noindent Syntax: ! @smallexample pragma Subtitle ([Subtitle =>] STRING_LITERAL); @end smallexample --- 3306,3318 ---- Rf2 : Integer := ARG; -- OK, no error @end smallexample + @node Pragma Subtitle + @unnumberedsec Pragma Subtitle @findex Subtitle @noindent Syntax: ! @smallexample @c ada pragma Subtitle ([Subtitle =>] STRING_LITERAL); @end smallexample *************** pragma Subtitle ([Subtitle =>] STRING_LI *** 2714,2725 **** This pragma is recognized for compatibility with other Ada compilers but is ignored by GNAT@. @findex Suppress_All - @item pragma Suppress_All @noindent Syntax: ! @smallexample pragma Suppress_All; @end smallexample --- 3320,3332 ---- This pragma is recognized for compatibility with other Ada compilers but is ignored by GNAT@. + @node Pragma Suppress_All + @unnumberedsec Pragma Suppress_All @findex Suppress_All @noindent Syntax: ! @smallexample @c ada pragma Suppress_All; @end smallexample *************** which it follows. This pragma is implem *** 2730,2743 **** Ada 83 usage. The use of pragma @code{Suppress (All_Checks)} as a normal configuration pragma is the preferred usage in GNAT@. @findex Suppress_Initialization @cindex Suppressing initialization @cindex Initialization, suppression of - @item pragma Suppress_Initialization @noindent Syntax: ! @smallexample pragma Suppress_Initialization ([Entity =>] type_Name); @end smallexample --- 3337,3374 ---- Ada 83 usage. The use of pragma @code{Suppress (All_Checks)} as a normal configuration pragma is the preferred usage in GNAT@. + @node Pragma Suppress_Exception_Locations + @unnumberedsec Pragma Suppress_Exception_Locations + @findex Suppress_Exception_Locations + @noindent + Syntax: + + @smallexample @c ada + pragma Suppress_Exception_Locations; + @end smallexample + + @noindent + In normal mode, a raise statement for an exception by default generates + an exception message giving the file name and line number for the location + of the raise. This is useful for debugging and logging purposes, but this + entails extra space for the strings for the messages. The configuration + pragma @code{Suppress_Exception_Locations} can be used to suppress the + generation of these strings, with the result that space is saved, but the + exception message for such raises is null. This configuration pragma may + appear in a global configuration pragma file, or in a specific unit as + usual. It is not required that this pragma be used consistently within + a partition, so it is fine to have some units within a partition compiled + with this pragma and others compiled in normal mode without it. + + @node Pragma Suppress_Initialization + @unnumberedsec Pragma Suppress_Initialization @findex Suppress_Initialization @cindex Suppressing initialization @cindex Initialization, suppression of @noindent Syntax: ! @smallexample @c ada pragma Suppress_Initialization ([Entity =>] type_Name); @end smallexample *************** pragma Suppress_Initialization ([Entity *** 2745,2756 **** This pragma suppresses any implicit or explicit initialization associated with the given type name for all variables of this type. @findex Task_Info - @item pragma Task_Info @noindent Syntax ! @smallexample pragma Task_Info (EXPRESSION); @end smallexample --- 3376,3388 ---- This pragma suppresses any implicit or explicit initialization associated with the given type name for all variables of this type. + @node Pragma Task_Info + @unnumberedsec Pragma Task_Info @findex Task_Info @noindent Syntax ! @smallexample @c ada pragma Task_Info (EXPRESSION); @end smallexample *************** This pragma appears within a task defini *** 2759,2776 **** @code{Priority}) and applies to the task in which it appears. The argument must be of type @code{System.Task_Info.Task_Info_Type}. The @code{Task_Info} pragma provides system dependent control over ! aspect of tasking implementation, for example, the ability to map tasks to specific processors. For details on the facilities available for the version of GNAT that you are using, see the documentation in the specification of package System.Task_Info in the runtime library. @findex Task_Name - @item pragma Task_Name @noindent Syntax ! @smallexample pragma Task_Name (string_EXPRESSION); @end smallexample --- 3391,3409 ---- @code{Priority}) and applies to the task in which it appears. The argument must be of type @code{System.Task_Info.Task_Info_Type}. The @code{Task_Info} pragma provides system dependent control over ! aspects of tasking implementation, for example, the ability to map tasks to specific processors. For details on the facilities available for the version of GNAT that you are using, see the documentation in the specification of package System.Task_Info in the runtime library. + @node Pragma Task_Name + @unnumberedsec Pragma Task_Name @findex Task_Name @noindent Syntax ! @smallexample @c ada pragma Task_Name (string_EXPRESSION); @end smallexample *************** and is accessible to tools like the debu *** 2789,2795 **** routine @code{Ada.Task_Identification.Image} will return this string, with a unique task address appended. ! @smallexample -- Example of the use of pragma Task_Name with Ada.Task_Identification; --- 3422,3428 ---- routine @code{Ada.Task_Identification.Image} will return this string, with a unique task address appended. ! @smallexample @c ada -- Example of the use of pragma Task_Name with Ada.Task_Identification; *************** procedure t3 is *** 2802,2814 **** task type Task_Typ (Name : access String) is pragma Task_Name (Name.all); end Task_Typ; ! task body Task_Typ is Nam : constant String := Image (Current_Task); begin Put_Line ("-->" & Nam (1 .. 14) & "<--"); end Task_Typ; ! type Ptr_Task is access Task_Typ; Task_Var : Ptr_Task; --- 3435,3447 ---- task type Task_Typ (Name : access String) is pragma Task_Name (Name.all); end Task_Typ; ! task body Task_Typ is Nam : constant String := Image (Current_Task); begin Put_Line ("-->" & Nam (1 .. 14) & "<--"); end Task_Typ; ! type Ptr_Task is access Task_Typ; Task_Var : Ptr_Task; *************** begin *** 2820,2835 **** end; @end smallexample @findex Task_Storage - @item pragma Task_Storage Syntax: ! @smallexample ! pragma Task_Storage [Task_Type =>] LOCAL_NAME, [Top_Guard =>] static_integer_EXPRESSION); @end smallexample This pragma specifies the length of the guard area for tasks. The guard area is an additional storage area allocated to a task. A value of zero means that either no guard area is created or a minimal guard area is --- 3453,3470 ---- end; @end smallexample + @node Pragma Task_Storage + @unnumberedsec Pragma Task_Storage @findex Task_Storage Syntax: ! @smallexample @c ada ! pragma Task_Storage ( [Task_Type =>] LOCAL_NAME, [Top_Guard =>] static_integer_EXPRESSION); @end smallexample + @noindent This pragma specifies the length of the guard area for tasks. The guard area is an additional storage area allocated to a task. A value of zero means that either no guard area is created or a minimal guard area is *************** created, depending on the target. This *** 2837,2848 **** @code{Storage_Size} attribute definition clause is allowed for a task type. @findex Time_Slice - @item pragma Time_Slice @noindent Syntax: ! @smallexample pragma Time_Slice (static_duration_EXPRESSION); @end smallexample --- 3472,3524 ---- @code{Storage_Size} attribute definition clause is allowed for a task type. + @node Pragma Thread_Body + @unnumberedsec Pragma Thread_Body + @findex Thread_Body + Syntax: + + @smallexample @c ada + pragma Thread_Body ( + [Entity =>] LOCAL_NAME, + [[Secondary_Stack_Size =>] static_integer_EXPRESSION)]; + @end smallexample + + @noindent + This pragma specifies that the subprogram whose name is given as the + @code{Entity} argument is a thread body, which will be activated + by being called via its Address from foreign code. The purpose is + to allow execution and registration of the foreign thread within the + Ada run-time system. + + See the library unit @code{System.Threads} for details on the expansion of + a thread body subprogram, including the calls made to subprograms + within System.Threads to register the task. This unit also lists the + targets and runtime systems for which this pragma is supported. + + A thread body subprogram may not be called directly from Ada code, and + it is not permitted to apply the Access (or Unrestricted_Access) attributes + to such a subprogram. The only legitimate way of calling such a subprogram + is to pass its Address to foreign code and then make the call from the + foreign code. + + A thread body subprogram may have any parameters, and it may be a function + returning a result. The convention of the thread body subprogram may be + set in the usual manner using @code{pragma Convention}. + + The secondary stack size parameter, if given, is used to set the size + of secondary stack for the thread. The secondary stack is allocated as + a local variable of the expanded thread body subprogram, and thus is + allocated out of the main thread stack size. If no secondary stack + size parameter is present, the default size (from the declaration in + @code{System.Secondary_Stack} is used. + + @node Pragma Time_Slice + @unnumberedsec Pragma Time_Slice @findex Time_Slice @noindent Syntax: ! @smallexample @c ada pragma Time_Slice (static_duration_EXPRESSION); @end smallexample *************** or if it appears in other than the main *** 2855,2866 **** Note that the effect of this pragma is identical to the effect of the DEC Ada 83 pragma of the same name when operating under OpenVMS systems. @findex Title - @item pragma Title @noindent Syntax: ! @smallexample pragma Title (TITLING_OPTION [, TITLING OPTION]); TITLING_OPTION ::= --- 3531,3543 ---- Note that the effect of this pragma is identical to the effect of the DEC Ada 83 pragma of the same name when operating under OpenVMS systems. + @node Pragma Title + @unnumberedsec Pragma Title @findex Title @noindent Syntax: ! @smallexample @c ada pragma Title (TITLING_OPTION [, TITLING OPTION]); TITLING_OPTION ::= *************** for this pragma, i.e.@: the parameters m *** 2879,2892 **** notation is used, and named and positional notation can be mixed following the normal rules for procedure calls in Ada. @cindex Unions in C @findex Unchecked_Union - @item pragma Unchecked_Union @noindent Syntax: ! @smallexample ! pragma Unchecked_Union (first_subtype_LOCAL_NAME) @end smallexample @noindent --- 3556,3570 ---- notation is used, and named and positional notation can be mixed following the normal rules for procedure calls in Ada. + @node Pragma Unchecked_Union + @unnumberedsec Pragma Unchecked_Union @cindex Unions in C @findex Unchecked_Union @noindent Syntax: ! @smallexample @c ada ! pragma Unchecked_Union (first_subtype_LOCAL_NAME); @end smallexample @noindent *************** No component has an explicit default val *** 2913,2918 **** --- 3591,3597 ---- No component has a non-static constraint. @end itemize + @noindent In addition, given a type that meets the above requirements, the following restrictions apply to its use throughout the program: *************** The type cannot be passed as the actual *** 2928,2933 **** --- 3607,3613 ---- discriminant. @end itemize + @noindent Equality and inequality operations on @code{unchecked_unions} are not available, since there is no discriminant to compare and the compiler does not even know how many bits to compare. It is implementation *************** the pragma, i.e.@: provided the above re *** 2945,2958 **** erroneous incorrect references to fields or erroneous comparisons occur, the semantics is exactly as described by the Ada reference manual. Pragma @code{Suppress (Discriminant_Check)} applies implicitly to the ! type and the default convention is C @findex Unimplemented_Unit - @item pragma Unimplemented_Unit @noindent Syntax: ! @smallexample pragma Unimplemented_Unit; @end smallexample --- 3625,3639 ---- erroneous incorrect references to fields or erroneous comparisons occur, the semantics is exactly as described by the Ada reference manual. Pragma @code{Suppress (Discriminant_Check)} applies implicitly to the ! type and the default convention is C. + @node Pragma Unimplemented_Unit + @unnumberedsec Pragma Unimplemented_Unit @findex Unimplemented_Unit @noindent Syntax: ! @smallexample @c ada pragma Unimplemented_Unit; @end smallexample *************** a clean manner. *** 2966,2978 **** The abort only happens if code is being generated. Thus you can use specs of unimplemented packages in syntax or semantic checking mode. @findex Unreferenced - @item pragma Unreferenced @cindex Warnings, unreferenced @noindent Syntax: ! @smallexample pragma Unreferenced (local_Name @{, local_Name@}); @end smallexample --- 3647,3684 ---- The abort only happens if code is being generated. Thus you can use specs of unimplemented packages in syntax or semantic checking mode. + @node Pragma Universal_Data + @unnumberedsec Pragma Universal_Data + @findex Universal_Data + @noindent + Syntax: + + @smallexample @c ada + pragma Universal_Data [(library_unit_Name)]; + @end smallexample + + @noindent + This pragma is supported only for the AAMP target and is ignored for + other targets. The pragma specifies that all library-level objects + (Counter 0 data) associated with the library unit are to be accessed + and updated using universal addressing (24-bit addresses for AAMP5) + rather than the default of 16-bit Data Environment (DENV) addressing. + Use of this pragma will generally result in less efficient code for + references to global data associated with the library unit, but + allows such data to be located anywhere in memory. This pragma is + a library unit pragma, but can also be used as a configuration pragma + (including use in the @file{gnat.adc} file). The functionality + of this pragma is also available by applying the -univ switch on the + compilations of units where universal addressing of the data is desired. + + @node Pragma Unreferenced + @unnumberedsec Pragma Unreferenced @findex Unreferenced @cindex Warnings, unreferenced @noindent Syntax: ! @smallexample @c ada pragma Unreferenced (local_Name @{, local_Name@}); @end smallexample *************** deliberately not referenced. This suppre *** 2982,2988 **** entities being unreferenced, and in addition a warning will be generated if one of these entities is in fact referenced. ! This is particularly useful for clearly signalling that a particular parameter is not referenced in some particular subprogram implementation and that this is deliberate. It can also be useful in the case of objects declared only for their initialization or finalization side --- 3688,3694 ---- entities being unreferenced, and in addition a warning will be generated if one of these entities is in fact referenced. ! This is particularly useful for clearly signaling that a particular parameter is not referenced in some particular subprogram implementation and that this is deliberate. It can also be useful in the case of objects declared only for their initialization or finalization side *************** If @code{local_Name} identifies more tha *** 2992,3003 **** current scope, then the entity most recently declared is the one to which the pragma applies. @findex Unreserve_All_Interrupts - @item pragma Unreserve_All_Interrupts @noindent Syntax: ! @smallexample pragma Unreserve_All_Interrupts; @end smallexample --- 3698,3714 ---- current scope, then the entity most recently declared is the one to which the pragma applies. + The left hand side of an assignment does not count as a reference for the + purpose of this pragma. Thus it is fine to assign to an entity for which + pragma Unreferenced is given. + + @node Pragma Unreserve_All_Interrupts + @unnumberedsec Pragma Unreserve_All_Interrupts @findex Unreserve_All_Interrupts @noindent Syntax: ! @smallexample @c ada pragma Unreserve_All_Interrupts; @end smallexample *************** pragma Unreserve_All_Interrupts; *** 3005,3011 **** Normally certain interrupts are reserved to the implementation. Any attempt to attach an interrupt causes Program_Error to be raised, as described in RM C.3.2(22). A typical example is the @code{SIGINT} interrupt used in ! many systems for an @kbd{Ctrl-C} interrupt. Normally this interrupt is reserved to the implementation, so that @kbd{Ctrl-C} can be used to interrupt execution. --- 3716,3722 ---- Normally certain interrupts are reserved to the implementation. Any attempt to attach an interrupt causes Program_Error to be raised, as described in RM C.3.2(22). A typical example is the @code{SIGINT} interrupt used in ! many systems for a @kbd{Ctrl-C} interrupt. Normally this interrupt is reserved to the implementation, so that @kbd{Ctrl-C} can be used to interrupt execution. *************** list of interrupts recognized for a give *** 3023,3034 **** this file also specifies what interrupts are affected by the use of the @code{Unreserve_All_Interrupts} pragma. @findex Unsuppress - @item pragma Unsuppress @noindent Syntax: ! @smallexample pragma Unsuppress (IDENTIFIER [, [On =>] NAME]); @end smallexample --- 3734,3750 ---- this file also specifies what interrupts are affected by the use of the @code{Unreserve_All_Interrupts} pragma. + For a more general facility for controlling what interrupts can be + handled, see pragma @code{Interrupt_State}, which subsumes the functionality + of the @code{Unreserve_All_Interrupts} pragma. + + @node Pragma Unsuppress + @unnumberedsec Pragma Unsuppress @findex Unsuppress @noindent Syntax: ! @smallexample @c ada pragma Unsuppress (IDENTIFIER [, [On =>] NAME]); @end smallexample *************** code depends on the checks for its corre *** 3044,3056 **** will compile correctly even if the compiler switches are set to suppress checks. @cindex @code{Size}, VADS compatibility @findex Use_VADS_Size - @item pragma Use_VADS_Size @noindent Syntax: ! @smallexample pragma Use_VADS_Size; @end smallexample --- 3760,3773 ---- will compile correctly even if the compiler switches are set to suppress checks. + @node Pragma Use_VADS_Size + @unnumberedsec Pragma Use_VADS_Size @cindex @code{Size}, VADS compatibility @findex Use_VADS_Size @noindent Syntax: ! @smallexample @c ada pragma Use_VADS_Size; @end smallexample *************** handling of legacy code which depends on *** 3063,3080 **** as implemented in the VADS compiler. See description of the VADS_Size attribute for further details. @findex Validity_Checks - @item pragma Validity_Checks @noindent Syntax: ! @smallexample pragma Validity_Checks (string_LITERAL | ALL_CHECKS | On | Off); @end smallexample @noindent This pragma is used in conjunction with compiler switches to control the ! built in validity checking provided by GNAT@. The compiler switches, if set provide an initial setting for the switches, and this pragma may be used to modify these settings, or the settings may be provided entirely by the use of the pragma. This pragma can be used anywhere that a pragma --- 3780,3798 ---- as implemented in the VADS compiler. See description of the VADS_Size attribute for further details. + @node Pragma Validity_Checks + @unnumberedsec Pragma Validity_Checks @findex Validity_Checks @noindent Syntax: ! @smallexample @c ada pragma Validity_Checks (string_LITERAL | ALL_CHECKS | On | Off); @end smallexample @noindent This pragma is used in conjunction with compiler switches to control the ! built-in validity checking provided by GNAT@. The compiler switches, if set provide an initial setting for the switches, and this pragma may be used to modify these settings, or the settings may be provided entirely by the use of the pragma. This pragma can be used anywhere that a pragma *************** GNAT users guide for details). For exam *** 3090,3099 **** can be used to enable validity checking for mode @code{in} and @code{in out} subprogram parameters: ! @smallexample pragma Validity_Checks ("im"); gcc -c -gnatVim @dots{} @end smallexample @noindent The form ALL_CHECKS activates all standard checks (its use is equivalent --- 3808,3824 ---- can be used to enable validity checking for mode @code{in} and @code{in out} subprogram parameters: ! @itemize @bullet ! @item ! @smallexample @c ada pragma Validity_Checks ("im"); + @end smallexample + + @item + @smallexample gcc -c -gnatVim @dots{} @end smallexample + @end itemize @noindent The form ALL_CHECKS activates all standard checks (its use is equivalent *************** The forms with @code{Off} and @code{On} *** 3103,3109 **** can be used to temporarily disable validity checks as shown in the following example: ! @smallexample @iftex @leftskip=0cm @end iftex --- 3828,3834 ---- can be used to temporarily disable validity checks as shown in the following example: ! @smallexample @c ada @iftex @leftskip=0cm @end iftex *************** pragma Validity_Checks (On); -- turn va *** 3114,3126 **** A := C; -- C will be validity checked @end smallexample @findex Volatile - @item pragma Volatile @noindent Syntax: ! @smallexample ! pragma Volatile (local_NAME) @end smallexample @noindent --- 3839,3852 ---- A := C; -- C will be validity checked @end smallexample + @node Pragma Volatile + @unnumberedsec Pragma Volatile @findex Volatile @noindent Syntax: ! @smallexample @c ada ! pragma Volatile (local_NAME); @end smallexample @noindent *************** in some Ada 83 compilers, including DEC *** 3131,3142 **** of pragma Volatile is upwards compatible with the implementation in Dec Ada 83. @findex Warnings - @item pragma Warnings @noindent Syntax: ! @smallexample pragma Warnings (On | Off [, LOCAL_NAME]); @end smallexample --- 3857,3869 ---- of pragma Volatile is upwards compatible with the implementation in Dec Ada 83. + @node Pragma Warnings + @unnumberedsec Pragma Warnings @findex Warnings @noindent Syntax: ! @smallexample @c ada pragma Warnings (On | Off [, LOCAL_NAME]); @end smallexample *************** the specified entity. This suppression *** 3155,3166 **** it occurs till the end of the extended scope of the variable (similar to the scope of @code{Suppress}). @findex Weak_External - @item pragma Weak_External @noindent Syntax: ! @smallexample pragma Weak_External ([Entity =>] LOCAL_NAME); @end smallexample --- 3882,3894 ---- it occurs till the end of the extended scope of the variable (similar to the scope of @code{Suppress}). + @node Pragma Weak_External + @unnumberedsec Pragma Weak_External @findex Weak_External @noindent Syntax: ! @smallexample @c ada pragma Weak_External ([Entity =>] LOCAL_NAME); @end smallexample *************** pragma Weak_External ([Entity =>] LOCAL_ *** 3168,3174 **** This pragma specifies that the given entity should be marked as a weak external (one that does not have to be resolved) for the linker. For further details, consult the GCC manual. - @end table @node Implementation Defined Attributes @chapter Implementation Defined Attributes --- 3896,3901 ---- *************** other compilers (although GNAT implement *** 3189,3197 **** platforms). Therefore if portability to other compilers is an important consideration, you should minimize the use of these attributes. ! @table @code @findex Abort_Signal - @item Abort_Signal @noindent @code{Standard'Abort_Signal} (@code{Standard} is the only allowed prefix) provides the entity for the special exception used to signal --- 3916,3973 ---- platforms). Therefore if portability to other compilers is an important consideration, you should minimize the use of these attributes. ! @menu ! * Abort_Signal:: ! * Address_Size:: ! * Asm_Input:: ! * Asm_Output:: ! * AST_Entry:: ! * Bit:: ! * Bit_Position:: ! * Code_Address:: ! * Default_Bit_Order:: ! * Elaborated:: ! * Elab_Body:: ! * Elab_Spec:: ! * Emax:: ! * Enum_Rep:: ! * Epsilon:: ! * Fixed_Value:: ! * Has_Discriminants:: ! * Img:: ! * Integer_Value:: ! * Large:: ! * Machine_Size:: ! * Mantissa:: ! * Max_Interrupt_Priority:: ! * Max_Priority:: ! * Maximum_Alignment:: ! * Mechanism_Code:: ! * Null_Parameter:: ! * Object_Size:: ! * Passed_By_Reference:: ! * Range_Length:: ! * Safe_Emax:: ! * Safe_Large:: ! * Small:: ! * Storage_Unit:: ! * Target_Name:: ! * Tick:: ! * To_Address:: ! * Type_Class:: ! * UET_Address:: ! * Unconstrained_Array:: ! * Universal_Literal_String:: ! * Unrestricted_Access:: ! * VADS_Size:: ! * Value_Size:: ! * Wchar_T_Size:: ! * Word_Size:: ! @end menu ! ! @node Abort_Signal ! @unnumberedsec Abort_Signal @findex Abort_Signal @noindent @code{Standard'Abort_Signal} (@code{Standard} is the only allowed prefix) provides the entity for the special exception used to signal *************** should only be used in the tasking runti *** 3200,3219 **** completely outside the normal semantics of Ada, for a user program to intercept the abort exception). @cindex Size of @code{Address} @findex Address_Size - @item Address_Size @noindent @code{Standard'Address_Size} (@code{Standard} is the only allowed prefix) is a static constant giving the number of bits in an ! @code{Address}. It is used primarily for constructing the definition of ! @code{Memory_Size} in package @code{Standard}, but may be freely used in user ! programs and has the advantage of being static, while a direct reference to System.Address'Size is non-static because Address is a private type. @findex Asm_Input - @item Asm_Input @noindent The @code{Asm_Input} attribute denotes a function that takes two parameters. The first is a string, the second is an expression of the --- 3976,3996 ---- completely outside the normal semantics of Ada, for a user program to intercept the abort exception). + @node Address_Size + @unnumberedsec Address_Size @cindex Size of @code{Address} @findex Address_Size @noindent @code{Standard'Address_Size} (@code{Standard} is the only allowed prefix) is a static constant giving the number of bits in an ! @code{Address}. It is the same value as System.Address'Size, ! but has the advantage of being static, while a direct reference to System.Address'Size is non-static because Address is a private type. + @node Asm_Input + @unnumberedsec Asm_Input @findex Asm_Input @noindent The @code{Asm_Input} attribute denotes a function that takes two parameters. The first is a string, the second is an expression of the *************** constant are the same as those used in t *** 3225,3232 **** the configuration file used to built the GCC back end. @ref{Machine Code Insertions} @findex Asm_Output - @item Asm_Output @noindent The @code{Asm_Output} attribute denotes a function that takes two parameters. The first is a string, the second is the name of a variable --- 4002,4010 ---- the configuration file used to built the GCC back end. @ref{Machine Code Insertions} + @node Asm_Output + @unnumberedsec Asm_Output @findex Asm_Output @noindent The @code{Asm_Output} attribute denotes a function that takes two parameters. The first is a string, the second is the name of a variable *************** GCC back end. If there are no output op *** 3240,3248 **** either be omitted, or explicitly given as @code{No_Output_Operands}. @ref{Machine Code Insertions} @cindex OpenVMS @findex AST_Entry - @item AST_Entry @noindent This attribute is implemented only in OpenVMS versions of GNAT@. Applied to the name of an entry, it yields a value of the predefined type AST_Handler --- 4018,4027 ---- either be omitted, or explicitly given as @code{No_Output_Operands}. @ref{Machine Code Insertions} + @node AST_Entry + @unnumberedsec AST_Entry @cindex OpenVMS @findex AST_Entry @noindent This attribute is implemented only in OpenVMS versions of GNAT@. Applied to the name of an entry, it yields a value of the predefined type AST_Handler *************** pragma @code{Extend_System (Aux_DEC)}). *** 3251,3258 **** be called when an AST occurs. For further details, refer to the @cite{DEC Ada Language Reference Manual}, section 9.12a. @findex Bit - @item Bit @code{@var{obj}'Bit}, where @var{obj} is any object, yields the bit offset within the storage unit (byte) that contains the first bit of storage allocated for the object. The value of this attribute is of the --- 4030,4038 ---- be called when an AST occurs. For further details, refer to the @cite{DEC Ada Language Reference Manual}, section 9.12a. + @node Bit + @unnumberedsec Bit @findex Bit @code{@var{obj}'Bit}, where @var{obj} is any object, yields the bit offset within the storage unit (byte) that contains the first bit of storage allocated for the object. The value of this attribute is of the *************** are subject to index checks. *** 3277,3284 **** This attribute is designed to be compatible with the DEC Ada 83 definition and implementation of the @code{Bit} attribute. @findex Bit_Position - @item Bit_Position @noindent @code{@var{R.C}'Bit}, where @var{R} is a record object and C is one of the fields of the record type, yields the bit --- 4057,4065 ---- This attribute is designed to be compatible with the DEC Ada 83 definition and implementation of the @code{Bit} attribute. + @node Bit_Position + @unnumberedsec Bit_Position @findex Bit_Position @noindent @code{@var{R.C}'Bit}, where @var{R} is a record object and C is one of the fields of the record type, yields the bit *************** type @code{Universal_Integer}. The valu *** 3288,3297 **** @var{C} and is independent of the alignment of the containing record @var{R}. @findex Code_Address @cindex Subprogram address @cindex Address of subprogram code - @item Code_Address @noindent The @code{'Address} attribute may be applied to subprograms in Ada 95, but the --- 4069,4079 ---- @var{C} and is independent of the alignment of the containing record @var{R}. + @node Code_Address + @unnumberedsec Code_Address @findex Code_Address @cindex Subprogram address @cindex Address of subprogram code @noindent The @code{'Address} attribute may be applied to subprograms in Ada 95, but the *************** intended effect from the Ada 95 referenc *** 3299,3305 **** an address value which can be used to call the subprogram by means of an address clause as in the following example: ! @smallexample procedure K is @dots{} procedure L; --- 4081,4087 ---- an address value which can be used to call the subprogram by means of an address clause as in the following example: ! @smallexample @c ada procedure K is @dots{} procedure L; *************** pragma Import (Ada, L); *** 3308,3335 **** @end smallexample @noindent ! A call to @code{L} is then expected to result in a call to @code{K}@. In Ada 83, where ! there were no access-to-subprogram values, this was a common work around ! for getting the effect of an indirect call. ! GNAT implements the above use of @code{Address} and the technique illustrated ! by the example code works correctly. However, for some purposes, it is useful to have the address of the start of the generated code for the subprogram. On some architectures, this is ! not necessarily the same as the @code{Address} value described above. For example, ! the @code{Address} value may reference a subprogram descriptor rather than the ! subprogram itself. ! The @code{'Code_Address} attribute, which can only be applied to ! subprogram entities, always returns the address of the start of the generated code of the specified subprogram, which may or may not be the same value as is returned by the corresponding @code{'Address} attribute. @cindex Big endian @cindex Little endian @findex Default_Bit_Order - @item Default_Bit_Order @noindent @code{Standard'Default_Bit_Order} (@code{Standard} is the only permissible prefix), provides the value @code{System.Default_Bit_Order} --- 4090,4118 ---- @end smallexample @noindent ! A call to @code{L} is then expected to result in a call to @code{K}@. ! In Ada 83, where there were no access-to-subprogram values, this was ! a common work around for getting the effect of an indirect call. ! GNAT implements the above use of @code{Address} and the technique ! illustrated by the example code works correctly. However, for some purposes, it is useful to have the address of the start of the generated code for the subprogram. On some architectures, this is ! not necessarily the same as the @code{Address} value described above. ! For example, the @code{Address} value may reference a subprogram ! descriptor rather than the subprogram itself. ! The @code{'Code_Address} attribute, which can only be applied to ! subprogram entities, always returns the address of the start of the generated code of the specified subprogram, which may or may not be the same value as is returned by the corresponding @code{'Address} attribute. + @node Default_Bit_Order + @unnumberedsec Default_Bit_Order @cindex Big endian @cindex Little endian @findex Default_Bit_Order @noindent @code{Standard'Default_Bit_Order} (@code{Standard} is the only permissible prefix), provides the value @code{System.Default_Bit_Order} *************** as a @code{Pos} value (0 for @code{High_ *** 3337,3344 **** @code{Low_Order_First}). This is used to construct the definition of @code{Default_Bit_Order} in package @code{System}. @findex Elaborated - @item Elaborated @noindent The prefix of the @code{'Elaborated} attribute must be a unit name. The value is a Boolean which indicates whether or not the given unit has been --- 4120,4128 ---- @code{Low_Order_First}). This is used to construct the definition of @code{Default_Bit_Order} in package @code{System}. + @node Elaborated + @unnumberedsec Elaborated @findex Elaborated @noindent The prefix of the @code{'Elaborated} attribute must be a unit name. The value is a Boolean which indicates whether or not the given unit has been *************** generated code for dynamic elaboration c *** 3347,3354 **** in user programs. The value will always be True once elaboration of all units has been completed. @findex Elab_Body - @item Elab_Body @noindent This attribute can only be applied to a program unit name. It returns the entity for the corresponding elaboration procedure for elaborating --- 4131,4139 ---- in user programs. The value will always be True once elaboration of all units has been completed. + @node Elab_Body + @unnumberedsec Elab_Body @findex Elab_Body @noindent This attribute can only be applied to a program unit name. It returns the entity for the corresponding elaboration procedure for elaborating *************** is useful to be able to call this elabor *** 3359,3366 **** e.g.@: if it is necessary to do selective re-elaboration to fix some error. @findex Elab_Spec - @item Elab_Spec @noindent This attribute can only be applied to a program unit name. It returns the entity for the corresponding elaboration procedure for elaborating --- 4144,4152 ---- e.g.@: if it is necessary to do selective re-elaboration to fix some error. + @node Elab_Spec + @unnumberedsec Elab_Spec @findex Elab_Spec @noindent This attribute can only be applied to a program unit name. It returns the entity for the corresponding elaboration procedure for elaborating *************** which it is useful to be able to call th *** 3371,3400 **** Ada code, e.g.@: if it is necessary to do selective re-elaboration to fix some error. @cindex Ada 83 attributes @findex Emax - @item Emax @noindent The @code{Emax} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. @cindex Representation of enums @findex Enum_Rep - @item Enum_Rep @noindent For every enumeration subtype @var{S}, @code{@var{S}'Enum_Rep} denotes a ! function with the following specification: ! @smallexample function @var{S}'Enum_Rep (Arg : @var{S}'Base) ! return Universal_Integer; @end smallexample @noindent It is also allowable to apply @code{Enum_Rep} directly to an object of an enumeration type or to a non-overloaded enumeration ! literal. In this case @code{@var{S}'Enum_Rep} is equivalent to @code{@var{typ}'Enum_Rep(@var{S})} where @var{typ} is the type of the enumeration literal or object. --- 4157,4188 ---- Ada code, e.g.@: if it is necessary to do selective re-elaboration to fix some error. + @node Emax + @unnumberedsec Emax @cindex Ada 83 attributes @findex Emax @noindent The @code{Emax} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. + @node Enum_Rep + @unnumberedsec Enum_Rep @cindex Representation of enums @findex Enum_Rep @noindent For every enumeration subtype @var{S}, @code{@var{S}'Enum_Rep} denotes a ! function with the following spec: ! @smallexample @c ada function @var{S}'Enum_Rep (Arg : @var{S}'Base) ! return @i{Universal_Integer}; @end smallexample @noindent It is also allowable to apply @code{Enum_Rep} directly to an object of an enumeration type or to a non-overloaded enumeration ! literal. In this case @code{@var{S}'Enum_Rep} is equivalent to @code{@var{typ}'Enum_Rep(@var{S})} where @var{typ} is the type of the enumeration literal or object. *************** value. This will be equal to value of t *** 3403,3453 **** absence of an enumeration representation clause. This is a static attribute (i.e.@: the result is static if the argument is static). ! @code{@var{S}'Enum_Rep} can also be used with integer types and objects, in which ! case it simply returns the integer value. The reason for this is to allow ! it to be used for @code{(<>)} discrete formal arguments in a generic unit that ! can be instantiated with either enumeration types or integer types. Note ! that if @code{Enum_Rep} is used on a modular type whose upper bound exceeds the ! upper bound of the largest signed integer type, and the argument is a ! variable, so that the universal integer calculation is done at run-time, ! then the call to @code{Enum_Rep} may raise @code{Constraint_Error}. @cindex Ada 83 attributes @findex Epsilon - @item Epsilon @noindent The @code{Epsilon} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. @findex Fixed_Value - @item Fixed_Value @noindent For every fixed-point type @var{S}, @code{@var{S}'Fixed_Value} denotes a function with the following specification: ! @smallexample ! function @var{S}'Fixed_Value (Arg : Universal_Integer) return @var{S}; @end smallexample @noindent The value returned is the fixed-point value @var{V} such that ! @smallexample @var{V} = Arg * @var{S}'Small @end smallexample @noindent ! The effect is thus equivalent to first converting the argument to the integer type used to represent @var{S}, and then doing an unchecked ! conversion to the fixed-point type. This attribute is primarily intended ! for use in implementation of the input-output functions for fixed-point ! values. @cindex Discriminants, testing for @findex Has_Discriminants - @item Has_Discriminants @noindent The prefix of the @code{Has_Discriminants} attribute is a type. The result is a Boolean value which is True if the type has discriminants, and False --- 4191,4246 ---- absence of an enumeration representation clause. This is a static attribute (i.e.@: the result is static if the argument is static). ! @code{@var{S}'Enum_Rep} can also be used with integer types and objects, ! in which case it simply returns the integer value. The reason for this ! is to allow it to be used for @code{(<>)} discrete formal arguments in ! a generic unit that can be instantiated with either enumeration types ! or integer types. Note that if @code{Enum_Rep} is used on a modular ! type whose upper bound exceeds the upper bound of the largest signed ! integer type, and the argument is a variable, so that the universal ! integer calculation is done at run-time, then the call to @code{Enum_Rep} ! may raise @code{Constraint_Error}. + @node Epsilon + @unnumberedsec Epsilon @cindex Ada 83 attributes @findex Epsilon @noindent The @code{Epsilon} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. + @node Fixed_Value + @unnumberedsec Fixed_Value @findex Fixed_Value @noindent For every fixed-point type @var{S}, @code{@var{S}'Fixed_Value} denotes a function with the following specification: ! @smallexample @c ada ! function @var{S}'Fixed_Value (Arg : @i{Universal_Integer}) return @var{S}; @end smallexample @noindent The value returned is the fixed-point value @var{V} such that ! @smallexample @c ada @var{V} = Arg * @var{S}'Small @end smallexample @noindent ! The effect is thus similar to first converting the argument to the integer type used to represent @var{S}, and then doing an unchecked ! conversion to the fixed-point type. The difference is ! that there are full range checks, to ensure that the result is in range. ! This attribute is primarily intended for use in implementation of the ! input-output functions for fixed-point values. + @node Has_Discriminants + @unnumberedsec Has_Discriminants @cindex Discriminants, testing for @findex Has_Discriminants @noindent The prefix of the @code{Has_Discriminants} attribute is a type. The result is a Boolean value which is True if the type has discriminants, and False *************** otherwise. The intended use of this att *** 3455,3560 **** definitions. If the attribute is applied to a generic private type, it indicates whether or not the corresponding actual type has discriminants. @findex Img - @item Img @noindent The @code{Img} attribute differs from @code{Image} in that it may be applied to objects as well as types, in which case it gives the @code{Image} for the subtype of the object. This is convenient for debugging: ! @smallexample Put_Line ("X = " & X'Img); @end smallexample @noindent has the same meaning as the more verbose: ! @smallexample ! Put_Line ("X = " & @var{type}'Image (X)); @end smallexample ! where @var{type} is the subtype of the object X@. @findex Integer_Value - @item Integer_Value @noindent For every integer type @var{S}, @code{@var{S}'Integer_Value} denotes a ! function with the following specification: ! @smallexample ! function @var{S}'Integer_Value (Arg : Universal_Fixed) return @var{S}; @end smallexample @noindent The value returned is the integer value @var{V}, such that ! @smallexample ! Arg = @var{V} * @var{type}'Small @end smallexample @noindent ! The effect is thus equivalent to first doing an unchecked convert from the fixed-point type to its corresponding implementation type, and then ! converting the result to the target integer type. This attribute is ! primarily intended for use in implementation of the standard ! input-output functions for fixed-point values. @cindex Ada 83 attributes @findex Large - @item Large @noindent The @code{Large} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. @findex Machine_Size - @item Machine_Size @noindent This attribute is identical to the @code{Object_Size} attribute. It is provided for compatibility with the DEC Ada 83 attribute of this name. ! @cindex Ada 83 attributes @findex Mantissa - @item Mantissa @noindent The @code{Mantissa} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. @cindex Interrupt priority, maximum @findex Max_Interrupt_Priority - @item Max_Interrupt_Priority @noindent @code{Standard'Max_Interrupt_Priority} (@code{Standard} is the only ! permissible prefix), provides the value ! @code{System.Max_Interrupt_Priority} and is intended primarily for ! constructing this definition in package @code{System}. @cindex Priority, maximum @findex Max_Priority - @item Max_Priority @noindent @code{Standard'Max_Priority} (@code{Standard} is the only permissible ! prefix) provides the value @code{System.Max_Priority} and is intended ! primarily for constructing this definition in package @code{System}. @cindex Alignment, maximum @findex Maximum_Alignment - @item Maximum_Alignment @noindent @code{Standard'Maximum_Alignment} (@code{Standard} is the only permissible prefix) provides the maximum useful alignment value for the target. This is a static value that can be used to specify the alignment for an object, guaranteeing that it is properly aligned in all ! cases. This is useful when an external object is imported and its ! alignment requirements are unknown. @cindex Return values, passing mechanism @cindex Parameters, passing mechanism @findex Mechanism_Code - @item Mechanism_Code @noindent @code{@var{function}'Mechanism_Code} yields an integer code for the mechanism used for the result of function, and --- 4248,4362 ---- definitions. If the attribute is applied to a generic private type, it indicates whether or not the corresponding actual type has discriminants. + @node Img + @unnumberedsec Img @findex Img @noindent The @code{Img} attribute differs from @code{Image} in that it may be applied to objects as well as types, in which case it gives the @code{Image} for the subtype of the object. This is convenient for debugging: ! @smallexample @c ada Put_Line ("X = " & X'Img); @end smallexample @noindent has the same meaning as the more verbose: ! @smallexample @c ada ! Put_Line ("X = " & @var{T}'Image (X)); @end smallexample ! @noindent ! where @var{T} is the (sub)type of the object @code{X}. + @node Integer_Value + @unnumberedsec Integer_Value @findex Integer_Value @noindent For every integer type @var{S}, @code{@var{S}'Integer_Value} denotes a ! function with the following spec: ! @smallexample @c ada ! function @var{S}'Integer_Value (Arg : @i{Universal_Fixed}) return @var{S}; @end smallexample @noindent The value returned is the integer value @var{V}, such that ! @smallexample @c ada ! Arg = @var{V} * @var{T}'Small @end smallexample @noindent ! where @var{T} is the type of @code{Arg}. ! The effect is thus similar to first doing an unchecked conversion from the fixed-point type to its corresponding implementation type, and then ! converting the result to the target integer type. The difference is ! that there are full range checks, to ensure that the result is in range. ! This attribute is primarily intended for use in implementation of the ! standard input-output functions for fixed-point values. + @node Large + @unnumberedsec Large @cindex Ada 83 attributes @findex Large @noindent The @code{Large} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. + @node Machine_Size + @unnumberedsec Machine_Size @findex Machine_Size @noindent This attribute is identical to the @code{Object_Size} attribute. It is provided for compatibility with the DEC Ada 83 attribute of this name. ! ! @node Mantissa ! @unnumberedsec Mantissa @cindex Ada 83 attributes @findex Mantissa @noindent The @code{Mantissa} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. + @node Max_Interrupt_Priority + @unnumberedsec Max_Interrupt_Priority @cindex Interrupt priority, maximum @findex Max_Interrupt_Priority @noindent @code{Standard'Max_Interrupt_Priority} (@code{Standard} is the only ! permissible prefix), provides the same value as ! @code{System.Max_Interrupt_Priority}. + @node Max_Priority + @unnumberedsec Max_Priority @cindex Priority, maximum @findex Max_Priority @noindent @code{Standard'Max_Priority} (@code{Standard} is the only permissible ! prefix) provides the same value as @code{System.Max_Priority}. + @node Maximum_Alignment + @unnumberedsec Maximum_Alignment @cindex Alignment, maximum @findex Maximum_Alignment @noindent @code{Standard'Maximum_Alignment} (@code{Standard} is the only permissible prefix) provides the maximum useful alignment value for the target. This is a static value that can be used to specify the alignment for an object, guaranteeing that it is properly aligned in all ! cases. + @node Mechanism_Code + @unnumberedsec Mechanism_Code @cindex Return values, passing mechanism @cindex Parameters, passing mechanism @findex Mechanism_Code @noindent @code{@var{function}'Mechanism_Code} yields an integer code for the mechanism used for the result of function, and *************** by descriptor (A: contiguous array) *** 3585,3596 **** by descriptor (NCA: non-contiguous array) @end table ! @cindex OpenVMS Values from 3 through 10 are only relevant to Digital OpenVMS implementations. @cindex Zero address, passing @findex Null_Parameter - @item Null_Parameter @noindent A reference @code{@var{T}'Null_Parameter} denotes an imaginary object of type or subtype @var{T} allocated at machine address zero. The attribute --- 4387,4400 ---- by descriptor (NCA: non-contiguous array) @end table ! @noindent Values from 3 through 10 are only relevant to Digital OpenVMS implementations. + @cindex OpenVMS + @node Null_Parameter + @unnumberedsec Null_Parameter @cindex Zero address, passing @findex Null_Parameter @noindent A reference @code{@var{T}'Null_Parameter} denotes an imaginary object of type or subtype @var{T} allocated at machine address zero. The attribute *************** passed for a record or other composite o *** 3607,3624 **** There is no way of indicating this without the @code{Null_Parameter} attribute. @cindex Size, used for objects @findex Object_Size - @item Object_Size @noindent The size of an object is not necessarily the same as the size of the type of an object. This is because by default object sizes are increased to be ! a multiple of the alignment of the object. For example, @code{Natural'Size} is 31, but by default objects of type @code{Natural} will have a size of 32 bits. Similarly, a record containing an integer and a character: ! @smallexample type Rec is record I : Integer; C : Character; --- 4411,4429 ---- There is no way of indicating this without the @code{Null_Parameter} attribute. + @node Object_Size + @unnumberedsec Object_Size @cindex Size, used for objects @findex Object_Size @noindent The size of an object is not necessarily the same as the size of the type of an object. This is because by default object sizes are increased to be ! a multiple of the alignment of the object. For example, @code{Natural'Size} is 31, but by default objects of type @code{Natural} will have a size of 32 bits. Similarly, a record containing an integer and a character: ! @smallexample @c ada type Rec is record I : Integer; C : Character; *************** end record; *** 3626,3632 **** @end smallexample @noindent ! will have a size of 40 (that is @code{Rec'Size} will be 40. The alignment will be 4, because of the integer field, and so the default size of record objects for this type will be 64 (8 bytes). --- 4431,4437 ---- @end smallexample @noindent ! will have a size of 40 (that is @code{Rec'Size} will be 40. The alignment will be 4, because of the integer field, and so the default size of record objects for this type will be 64 (8 bytes). *************** default object size of a type to be easi *** 3637,3647 **** @code{Natural'Object_Size} is 32, and @code{Rec'Object_Size} (for the record type in the above example) will be 64. Note also that, unlike the situation with the ! @code{Size} attribute as defined in the Ada RM, the @code{Object_Size} attribute can be specified individually for different subtypes. For example: ! @smallexample type R is new Integer; subtype R1 is R range 1 .. 10; subtype R2 is R range 1 .. 10; --- 4442,4452 ---- @code{Natural'Object_Size} is 32, and @code{Rec'Object_Size} (for the record type in the above example) will be 64. Note also that, unlike the situation with the ! @code{Size} attribute as defined in the Ada RM, the @code{Object_Size} attribute can be specified individually for different subtypes. For example: ! @smallexample @c ada type R is new Integer; subtype R1 is R range 1 .. 10; subtype R2 is R range 1 .. 10; *************** by default be 32 bits (four bytes). But *** 3657,3665 **** @code{R2} will be only 8 bits (one byte), since @code{R2'Object_Size} has been set to 8. @cindex Parameters, when passed by reference @findex Passed_By_Reference - @item Passed_By_Reference @noindent @code{@var{type}'Passed_By_Reference} for any subtype @var{type} returns a value of type @code{Boolean} value that is @code{True} if the type is --- 4462,4471 ---- @code{R2} will be only 8 bits (one byte), since @code{R2'Object_Size} has been set to 8. + @node Passed_By_Reference + @unnumberedsec Passed_By_Reference @cindex Parameters, when passed by reference @findex Passed_By_Reference @noindent @code{@var{type}'Passed_By_Reference} for any subtype @var{type} returns a value of type @code{Boolean} value that is @code{True} if the type is *************** normally passed by reference and @code{F *** 3667,3674 **** passed by copy in calls. For scalar types, the result is always @code{False} and is static. For non-scalar types, the result is non-static. @findex Range_Length - @item Range_Length @noindent @code{@var{type}'Range_Length} for any discrete type @var{type} yields the number of values represented by the subtype (zero for a null --- 4473,4481 ---- passed by copy in calls. For scalar types, the result is always @code{False} and is static. For non-scalar types, the result is non-static. + @node Range_Length + @unnumberedsec Range_Length @findex Range_Length @noindent @code{@var{type}'Range_Length} for any discrete type @var{type} yields the number of values represented by the subtype (zero for a null *************** range). The result is static for static *** 3676,3708 **** applied to the index subtype of a one dimensional array always gives the same result as @code{Range} applied to the array itself. @cindex Ada 83 attributes @findex Safe_Emax - @item Safe_Emax @noindent The @code{Safe_Emax} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. @cindex Ada 83 attributes @findex Safe_Large - @item Safe_Large - @noindent - The @code{Safe_Large} attribute is provided for compatibility with Ada 83. See - the Ada 83 reference manual for an exact description of the semantics of - this attribute. - - @cindex Ada 83 attributes - @findex Safe_Large - @item Safe_Large @noindent The @code{Safe_Large} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. @cindex Ada 83 attributes @findex Small - @item Small @noindent The @code{Small} attribute is defined in Ada 95 only for fixed-point types. GNAT also allows this attribute to be applied to floating-point types --- 4483,4510 ---- applied to the index subtype of a one dimensional array always gives the same result as @code{Range} applied to the array itself. + @node Safe_Emax + @unnumberedsec Safe_Emax @cindex Ada 83 attributes @findex Safe_Emax @noindent The @code{Safe_Emax} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. + @node Safe_Large + @unnumberedsec Safe_Large @cindex Ada 83 attributes @findex Safe_Large @noindent The @code{Safe_Large} attribute is provided for compatibility with Ada 83. See the Ada 83 reference manual for an exact description of the semantics of this attribute. + @node Small + @unnumberedsec Small @cindex Ada 83 attributes @findex Small @noindent The @code{Small} attribute is defined in Ada 95 only for fixed-point types. GNAT also allows this attribute to be applied to floating-point types *************** for compatibility with Ada 83. See *** 3710,3746 **** the Ada 83 reference manual for an exact description of the semantics of this attribute when applied to floating-point types. @findex Storage_Unit - @item Storage_Unit @noindent @code{Standard'Storage_Unit} (@code{Standard} is the only permissible ! prefix) provides the value @code{System.Storage_Unit} and is intended ! primarily for constructing this definition in package @code{System}. @findex Tick - @item Tick @noindent @code{Standard'Tick} (@code{Standard} is the only permissible prefix) ! provides the value of @code{System.Tick} and is intended primarily for ! constructing this definition in package @code{System}. @findex To_Address - @item To_Address @noindent The @code{System'To_Address} (@code{System} is the only permissible prefix) ! denotes a function identical to @code{System.Storage_Elements.To_Address} except that it is a static attribute. This means that if its argument is a static expression, then the result of the attribute is a static expression. The result is that such an expression can be used in contexts (e.g.@: preelaborable packages) which require a static expression and where the function call could not be used ! (since the function call is always non-static, even if its argument is static). @findex Type_Class - @item Type_Class @noindent @code{@var{type}'Type_Class} for any type or subtype @var{type} yields the value of the type class for the full type of @var{type}. If --- 4512,4560 ---- the Ada 83 reference manual for an exact description of the semantics of this attribute when applied to floating-point types. + @node Storage_Unit + @unnumberedsec Storage_Unit @findex Storage_Unit @noindent @code{Standard'Storage_Unit} (@code{Standard} is the only permissible ! prefix) provides the same value as @code{System.Storage_Unit}. + @node Target_Name + @unnumberedsec Target_Name + @findex Target_Name + @noindent + @code{Standard'Target_Name} (@code{Standard} is the only permissible + prefix) provides a static string value that identifies the target + for the current compilation. For GCC implementations, this is the + standard gcc target name without the terminating slash (for + example, GNAT 5.0 on windows yields "i586-pc-mingw32msv"). + + @node Tick + @unnumberedsec Tick @findex Tick @noindent @code{Standard'Tick} (@code{Standard} is the only permissible prefix) ! provides the same value as @code{System.Tick}, + @node To_Address + @unnumberedsec To_Address @findex To_Address @noindent The @code{System'To_Address} (@code{System} is the only permissible prefix) ! denotes a function identical to @code{System.Storage_Elements.To_Address} except that it is a static attribute. This means that if its argument is a static expression, then the result of the attribute is a static expression. The result is that such an expression can be used in contexts (e.g.@: preelaborable packages) which require a static expression and where the function call could not be used ! (since the function call is always non-static, even if its argument is static). + @node Type_Class + @unnumberedsec Type_Class @findex Type_Class @noindent @code{@var{type}'Type_Class} for any type or subtype @var{type} yields the value of the type class for the full type of @var{type}. If *************** the value of the type class for the full *** 3748,3754 **** corresponding actual subtype. The value of this attribute is of type @code{System.Aux_DEC.Type_Class}, which has the following definition: ! @smallexample type Type_Class is (Type_Class_Enumeration, Type_Class_Integer, --- 4562,4568 ---- corresponding actual subtype. The value of this attribute is of type @code{System.Aux_DEC.Type_Class}, which has the following definition: ! @smallexample @c ada type Type_Class is (Type_Class_Enumeration, Type_Class_Integer, *************** Protected types yield the value @code{Ty *** 3766,3773 **** applies to all concurrent types. This attribute is designed to be compatible with the DEC Ada 83 attribute of the same name. @findex UET_Address - @item UET_Address @noindent The @code{UET_Address} attribute can only be used for a prefix which denotes a library package. It yields the address of the unit exception --- 4580,4588 ---- applies to all concurrent types. This attribute is designed to be compatible with the DEC Ada 83 attribute of the same name. + @node UET_Address + @unnumberedsec UET_Address @findex UET_Address @noindent The @code{UET_Address} attribute can only be used for a prefix which denotes a library package. It yields the address of the unit exception *************** intended only for use within the GNAT im *** 3776,3784 **** @code{Ada.Exceptions} in files @file{a-except.ads} and @file{a-except.adb} for details on how this attribute is used in the implementation. @cindex Named numbers, representation of @findex Universal_Literal_String - @item Universal_Literal_String @noindent The prefix of @code{Universal_Literal_String} must be a named number. The static result is the string consisting of the characters of --- 4591,4611 ---- @code{Ada.Exceptions} in files @file{a-except.ads} and @file{a-except.adb} for details on how this attribute is used in the implementation. + @node Unconstrained_Array + @unnumberedsec Unconstrained_Array + @findex Unconstrained_Array + @noindent + The @code{Unconstrained_Array} attribute can be used with a prefix that + denotes any type or subtype. It is a static attribute that yields + @code{True} if the prefix designates an unconstrained array, + and @code{False} otherwise. In a generic instance, the result is + still static, and yields the result of applying this test to the + generic actual. + + @node Universal_Literal_String + @unnumberedsec Universal_Literal_String @cindex Named numbers, representation of @findex Universal_Literal_String @noindent The prefix of @code{Universal_Literal_String} must be a named number. The static result is the string consisting of the characters of *************** would preclude their use as numbers). T *** 3789,3797 **** construction of values of the floating-point attributes from the file @file{ttypef.ads}, but may also be used by user programs. @cindex @code{Access}, unrestricted @findex Unrestricted_Access - @item Unrestricted_Access @noindent The @code{Unrestricted_Access} attribute is similar to @code{Access} except that all accessibility and aliased view checks are omitted. This --- 4616,4625 ---- construction of values of the floating-point attributes from the file @file{ttypef.ads}, but may also be used by user programs. + @node Unrestricted_Access + @unnumberedsec Unrestricted_Access @cindex @code{Access}, unrestricted @findex Unrestricted_Access @noindent The @code{Unrestricted_Access} attribute is similar to @code{Access} except that all accessibility and aliased view checks are omitted. This *************** subprograms means that @code{Unrestricte *** 3805,3813 **** subprogram yields a value that can be called as long as the subprogram is in scope (normal Ada 95 accessibility rules restrict this usage). @cindex @code{Size}, VADS compatibility @findex VADS_Size - @item VADS_Size @noindent The @code{'VADS_Size} attribute is intended to make it easier to port legacy code which relies on the semantics of @code{'Size} as implemented --- 4633,4650 ---- subprogram yields a value that can be called as long as the subprogram is in scope (normal Ada 95 accessibility rules restrict this usage). + It is possible to use @code{Unrestricted_Access} for any type, but care + must be excercised if it is used to create pointers to unconstrained + objects. In this case, the resulting pointer has the same scope as the + context of the attribute, and may not be returned to some enclosing + scope. For instance, a function cannot use @code{Unrestricted_Access} + to create a unconstrained pointer and then return that value to the + caller. + + @node VADS_Size + @unnumberedsec VADS_Size @cindex @code{Size}, VADS compatibility @findex VADS_Size @noindent The @code{'VADS_Size} attribute is intended to make it easier to port legacy code which relies on the semantics of @code{'Size} as implemented *************** typical machines). In addition @code{'V *** 3819,3846 **** gives the result that would be obtained by applying the attribute to the corresponding type. @cindex @code{Size}, setting for not-first subtype @findex Value_Size - @item Value_Size @code{@var{type}'Value_Size} is the number of bits required to represent a value of the given subtype. It is the same as @code{@var{type}'Size}, but, unlike @code{Size}, may be set for non-first subtypes. @findex Wchar_T_Size - @item Wchar_T_Size @code{Standard'Wchar_T_Size} (@code{Standard} is the only permissible ! prefix) provides the size in bits of the C @code{wchar_t} type ! primarily for constructing the definition of this type in package @code{Interfaces.C}. @findex Word_Size - @item Word_Size @code{Standard'Word_Size} (@code{Standard} is the only permissible ! prefix) provides the value @code{System.Word_Size} and is intended ! primarily for constructing this definition in package @code{System}. ! @end table @node Implementation Advice @chapter Implementation Advice The main text of the Ada 95 Reference Manual describes the required behavior of all Ada 95 compilers, and the GNAT compiler conforms to these requirements. --- 4656,4687 ---- gives the result that would be obtained by applying the attribute to the corresponding type. + @node Value_Size + @unnumberedsec Value_Size @cindex @code{Size}, setting for not-first subtype @findex Value_Size @code{@var{type}'Value_Size} is the number of bits required to represent a value of the given subtype. It is the same as @code{@var{type}'Size}, but, unlike @code{Size}, may be set for non-first subtypes. + @node Wchar_T_Size + @unnumberedsec Wchar_T_Size @findex Wchar_T_Size @code{Standard'Wchar_T_Size} (@code{Standard} is the only permissible ! prefix) provides the size in bits of the C @code{wchar_t} type ! primarily for constructing the definition of this type in package @code{Interfaces.C}. + @node Word_Size + @unnumberedsec Word_Size @findex Word_Size @code{Standard'Word_Size} (@code{Standard} is the only permissible ! prefix) provides the value @code{System.Word_Size}. ! ! @c ------------------------ @node Implementation Advice @chapter Implementation Advice + @noindent The main text of the Ada 95 Reference Manual describes the required behavior of all Ada 95 compilers, and the GNAT compiler conforms to these requirements. *************** by the GNAT interpretation of this advic *** 3863,3871 **** number of cases, GNAT deliberately deviates from this advice, in which case the text describes what GNAT does and why. - @table @strong @cindex Error detection ! @item 1.1.3(20): Error Detection @sp 1 @cartouche If an implementation detects the use of an unsupported Specialized Needs --- 4704,4711 ---- number of cases, GNAT deliberately deviates from this advice, in which case the text describes what GNAT does and why. @cindex Error detection ! @unnumberedsec 1.1.3(20): Error Detection @sp 1 @cartouche If an implementation detects the use of an unsupported Specialized Needs *************** Not relevant. All specialized needs ann *** 3876,3882 **** or diagnosed at compile time. @cindex Child Units ! @item 1.1.3(31): Child Units @sp 1 @cartouche If an implementation wishes to provide implementation-defined --- 4716,4722 ---- or diagnosed at compile time. @cindex Child Units ! @unnumberedsec 1.1.3(31): Child Units @sp 1 @cartouche If an implementation wishes to provide implementation-defined *************** should normally do so by adding children *** 3886,3892 **** Followed. @cindex Bounded errors ! @item 1.1.5(12): Bounded Errors @sp 1 @cartouche If an implementation detects a bounded error or erroneous --- 4726,4732 ---- Followed. @cindex Bounded errors ! @unnumberedsec 1.1.5(12): Bounded Errors @sp 1 @cartouche If an implementation detects a bounded error or erroneous *************** error or erroneous execution. Not all s *** 3897,3903 **** runtime. @cindex Pragmas ! @item 2.8(16): Pragmas @sp 1 @cartouche Normally, implementation-defined pragmas should have no semantic effect --- 4737,4743 ---- runtime. @cindex Pragmas ! @unnumberedsec 2.8(16): Pragmas @sp 1 @cartouche Normally, implementation-defined pragmas should have no semantic effect *************** Affects legality *** 3935,3945 **** Affects semantics @end table In each of the above cases, it is essential to the purpose of the pragma that this advice not be followed. For details see the separate section on implementation defined pragmas. ! @item 2.8(17-19): Pragmas @sp 1 @cartouche Normally, an implementation should not define pragmas that can --- 4775,4786 ---- Affects semantics @end table + @noindent In each of the above cases, it is essential to the purpose of the pragma that this advice not be followed. For details see the separate section on implementation defined pragmas. ! @unnumberedsec 2.8(17-19): Pragmas @sp 1 @cartouche Normally, an implementation should not define pragmas that can *************** See response to paragraph 16 of this sam *** 3958,3964 **** @cindex Character Sets @cindex Alternative Character Sets ! @item 3.5.2(5): Alternative Character Sets @sp 1 @cartouche If an implementation supports a mode with alternative interpretations --- 4799,4805 ---- @cindex Character Sets @cindex Alternative Character Sets ! @unnumberedsec 3.5.2(5): Alternative Character Sets @sp 1 @cartouche If an implementation supports a mode with alternative interpretations *************** encoding. However, this only applies to *** 3980,3986 **** there is no such restriction. @cindex Integer types ! @item 3.5.4(28): Integer Types @sp 1 @cartouche --- 4821,4827 ---- there is no such restriction. @cindex Integer types ! @unnumberedsec 3.5.4(28): Integer Types @sp 1 @cartouche *************** provided in the library package @code{In *** 3994,4000 **** so this advice is not fully followed. These types are supported for convenient interface to C, and so that all hardware types of the machine are easily available. ! @item 3.5.4(29): Integer Types @sp 1 @cartouche --- 4835,4841 ---- so this advice is not fully followed. These types are supported for convenient interface to C, and so that all hardware types of the machine are easily available. ! @unnumberedsec 3.5.4(29): Integer Types @sp 1 @cartouche *************** implementation should support a non-bina *** 4005,4011 **** Followed. @cindex Enumeration values ! @item 3.5.5(8): Enumeration Values @sp 1 @cartouche For the evaluation of a call on @code{@var{S}'Pos} for an enumeration --- 4846,4852 ---- Followed. @cindex Enumeration values ! @unnumberedsec 3.5.5(8): Enumeration Values @sp 1 @cartouche For the evaluation of a call on @code{@var{S}'Pos} for an enumeration *************** enumeration_representation_clause. *** 4019,4025 **** Followed. @cindex Float types ! @item 3.5.7(17): Float Types @sp 1 @cartouche An implementation should support @code{Long_Float} in addition to --- 4860,4866 ---- Followed. @cindex Float types ! @unnumberedsec 3.5.7(17): Float Types @sp 1 @cartouche An implementation should support @code{Long_Float} in addition to *************** since this is a software rather than a h *** 4041,4047 **** @cindex Multidimensional arrays @cindex Arrays, multidimensional ! @item 3.6.2(11): Multidimensional Arrays @sp 1 @cartouche An implementation should normally represent multidimensional arrays in --- 4882,4888 ---- @cindex Multidimensional arrays @cindex Arrays, multidimensional ! @unnumberedsec 3.6.2(11): Multidimensional Arrays @sp 1 @cartouche An implementation should normally represent multidimensional arrays in *************** Fortran''). *** 4054,4060 **** Followed. @findex Duration'Small ! @item 9.6(30-31): Duration'Small @sp 1 @cartouche Whenever possible in an implementation, the value of @code{Duration'Small} --- 4895,4901 ---- Followed. @findex Duration'Small ! @unnumberedsec 9.6(30-31): Duration'Small @sp 1 @cartouche Whenever possible in an implementation, the value of @code{Duration'Small} *************** it need not be the same time base as use *** 4069,4075 **** @end cartouche Followed. ! @item 10.2.1(12): Consistent Representation @sp 1 @cartouche In an implementation, a type declared in a pre-elaborated package should --- 4910,4916 ---- @end cartouche Followed. ! @unnumberedsec 10.2.1(12): Consistent Representation @sp 1 @cartouche In an implementation, a type declared in a pre-elaborated package should *************** package. It is not easy to see how it w *** 4085,4091 **** advice without severely impacting efficiency of execution. @cindex Exception information ! @item 11.4.1(19): Exception Information @sp 1 @cartouche @code{Exception_Message} by default and @code{Exception_Information} --- 4926,4932 ---- advice without severely impacting efficiency of execution. @cindex Exception information ! @unnumberedsec 11.4.1(19): Exception Information @sp 1 @cartouche @code{Exception_Message} by default and @code{Exception_Information} *************** Pragma @code{Discard_Names}. *** 4108,4114 **** @cindex Suppression of checks @cindex Checks, suppression of ! @item 11.5(28): Suppression of Checks @sp 1 @cartouche The implementation should minimize the code executed for checks that --- 4949,4955 ---- @cindex Suppression of checks @cindex Checks, suppression of ! @unnumberedsec 11.5(28): Suppression of Checks @sp 1 @cartouche The implementation should minimize the code executed for checks that *************** have been suppressed. *** 4117,4123 **** Followed. @cindex Representation clauses ! @item 13.1 (21-24): Representation Clauses @sp 1 @cartouche The recommended level of support for all representation items is --- 4958,4964 ---- Followed. @cindex Representation clauses ! @unnumberedsec 13.1 (21-24): Representation Clauses @sp 1 @cartouche The recommended level of support for all representation items is *************** Followed. GNAT does not support non-sta *** 4135,4153 **** clauses unless they are constants declared before the entity. For example: ! @smallexample ! X : typ; ! for X'Address use To_address (16#2000#); @end smallexample @noindent will be rejected, since the To_Address expression is non-static. Instead ! write: ! @smallexample ! X_Address : constant Address : = ! To_Address ((16#2000#); ! X : typ; for X'Address use X_Address; @end smallexample --- 4976,4993 ---- clauses unless they are constants declared before the entity. For example: ! @smallexample @c ada ! X : Some_Type; ! for X'Address use To_address (16#2000#); @end smallexample @noindent will be rejected, since the To_Address expression is non-static. Instead ! write: ! @smallexample @c ada ! X_Address : constant Address : = To_Address (16#2000#); ! X : Some_Type; for X'Address use X_Address; @end smallexample *************** always be allocated at an addressable lo *** 4170,4176 **** Followed. @cindex Packed types ! @item 13.2(6-8): Packed Types @sp 1 @cartouche If a type is packed, then the implementation should try to minimize --- 5010,5016 ---- Followed. @cindex Packed types ! @unnumberedsec 13.2(6-8): Packed Types @sp 1 @cartouche If a type is packed, then the implementation should try to minimize *************** word boundaries to improve the packing. *** 4190,4196 **** greater than the word size may be allocated an integral number of words. @end cartouche Followed. Tight packing of arrays is supported for all component sizes ! up to 64-bits. @sp 1 @cartouche --- 5030,5040 ---- greater than the word size may be allocated an integral number of words. @end cartouche Followed. Tight packing of arrays is supported for all component sizes ! up to 64-bits. If the array component size is 1 (that is to say, if ! the component is a boolean type or an enumeration type with two values) ! then values of the type are implicitly initialized to zero. This ! happens both for objects of the packed type, and for objects that have a ! subcomponent of the packed type. @sp 1 @cartouche *************** subprograms. *** 4199,4205 **** @end cartouche Followed. @cindex @code{Address} clauses ! @item 13.3(14-19): Address Clauses @sp 1 @cartouche --- 5043,5049 ---- @end cartouche Followed. @cindex @code{Address} clauses ! @unnumberedsec 13.3(14-19): Address Clauses @sp 1 @cartouche *************** An implementation should support @code{A *** 4226,4239 **** subprograms. @end cartouche Followed. ! @sp 1 @cartouche Objects (including subcomponents) that are aliased or of a by-reference type should be allocated on storage element boundaries. @end cartouche Followed. ! @sp 1 @cartouche If the @code{Address} of an object is specified, or it is imported or exported, --- 5070,5083 ---- subprograms. @end cartouche Followed. ! @sp 1 @cartouche Objects (including subcomponents) that are aliased or of a by-reference type should be allocated on storage element boundaries. @end cartouche Followed. ! @sp 1 @cartouche If the @code{Address} of an object is specified, or it is imported or exported, *************** assumptions of no aliases. *** 4243,4249 **** Followed. @cindex @code{Alignment} clauses ! @item 13.3(29-35): Alignment Clauses @sp 1 @cartouche The recommended level of support for the @code{Alignment} attribute for --- 5087,5093 ---- Followed. @cindex @code{Alignment} clauses ! @unnumberedsec 13.3(29-35): Alignment Clauses @sp 1 @cartouche The recommended level of support for the @code{Alignment} attribute for *************** and multiples of the number of storage e *** 4254,4260 **** following: @end cartouche Followed. ! @sp 1 @cartouche An implementation need not support specified @code{Alignment}s for --- 5098,5104 ---- following: @end cartouche Followed. ! @sp 1 @cartouche An implementation need not support specified @code{Alignment}s for *************** combinations of @code{Size}s and @code{A *** 4262,4268 **** loaded and stored by available machine instructions. @end cartouche Followed. ! @sp 1 @cartouche An implementation need not support specified @code{Alignment}s that are --- 5106,5112 ---- loaded and stored by available machine instructions. @end cartouche Followed. ! @sp 1 @cartouche An implementation need not support specified @code{Alignment}s that are *************** objects is: *** 4279,4285 **** Same as above, for subtypes, but in addition: @end cartouche Followed. ! @sp 1 @cartouche For stand-alone library-level objects of statically constrained --- 5123,5129 ---- Same as above, for subtypes, but in addition: @end cartouche Followed. ! @sp 1 @cartouche For stand-alone library-level objects of statically constrained *************** be supported for such objects, but not f *** 4290,4296 **** Followed. @cindex @code{Size} clauses ! @item 13.3(42-43): Size Clauses @sp 1 @cartouche The recommended level of support for the @code{Size} attribute of --- 5134,5140 ---- Followed. @cindex @code{Size} clauses ! @unnumberedsec 13.3(42-43): Size Clauses @sp 1 @cartouche The recommended level of support for the @code{Size} attribute of *************** object's @code{Alignment} (if the @code{ *** 4303,4309 **** @end cartouche Followed. ! @item 13.3(50-56): Size Clauses @sp 1 @cartouche If the @code{Size} of a subtype is specified, and allows for efficient --- 5147,5153 ---- @end cartouche Followed. ! @unnumberedsec 13.3(50-56): Size Clauses @sp 1 @cartouche If the @code{Size} of a subtype is specified, and allows for efficient *************** point at. *** 4346,4352 **** Followed. @cindex @code{Component_Size} clauses ! @item 13.3(71-73): Component Size Clauses @sp 1 @cartouche The recommended level of support for the @code{Component_Size} --- 5190,5196 ---- Followed. @cindex @code{Component_Size} clauses ! @unnumberedsec 13.3(71-73): Component Size Clauses @sp 1 @cartouche The recommended level of support for the @code{Component_Size} *************** Followed. *** 4373,4379 **** @cindex Enumeration representation clauses @cindex Representation clauses, enumeration ! @item 13.4(9-10): Enumeration Representation Clauses @sp 1 @cartouche The recommended level of support for enumeration representation clauses --- 5217,5223 ---- @cindex Enumeration representation clauses @cindex Representation clauses, enumeration ! @unnumberedsec 13.4(9-10): Enumeration Representation Clauses @sp 1 @cartouche The recommended level of support for enumeration representation clauses *************** Followed. *** 4387,4393 **** @cindex Record representation clauses @cindex Representation clauses, records ! @item 13.5.1(17-22): Record Representation Clauses @sp 1 @cartouche The recommended level of support for --- 5231,5237 ---- @cindex Record representation clauses @cindex Representation clauses, records ! @unnumberedsec 13.5.1(17-22): Record Representation Clauses @sp 1 @cartouche The recommended level of support for *************** A storage place should be supported if i *** 4407,4413 **** boundary that obeys the @code{Alignment} of the component subtype. @end cartouche Followed. ! @sp 1 @cartouche If the default bit ordering applies to the declaration of a given type, --- 5251,5257 ---- boundary that obeys the @code{Alignment} of the component subtype. @end cartouche Followed. ! @sp 1 @cartouche If the default bit ordering applies to the declaration of a given type, *************** Followed. The above advice on record re *** 4437,4443 **** and all mentioned features are implemented. @cindex Storage place attributes ! @item 13.5.2(5): Storage Place Attributes @sp 1 @cartouche If a component is represented using some form of pointer (such as an --- 5281,5287 ---- and all mentioned features are implemented. @cindex Storage place attributes ! @unnumberedsec 13.5.2(5): Storage Place Attributes @sp 1 @cartouche If a component is represented using some form of pointer (such as an *************** attributes. *** 4451,4457 **** Followed. There are no such components in GNAT@. @cindex Bit ordering ! @item 13.5.3(7-8): Bit Ordering @sp 1 @cartouche The recommended level of support for the non-default bit ordering is: --- 5295,5301 ---- Followed. There are no such components in GNAT@. @cindex Bit ordering ! @unnumberedsec 13.5.3(7-8): Bit Ordering @sp 1 @cartouche The recommended level of support for the non-default bit ordering is: *************** Followed. Word size does not equal stor *** 4466,4472 **** Thus non-default bit ordering is not supported. @cindex @code{Address}, as private type ! @item 13.7(37): Address as Private @sp 1 @cartouche @code{Address} should be of a private type. --- 5310,5316 ---- Thus non-default bit ordering is not supported. @cindex @code{Address}, as private type ! @unnumberedsec 13.7(37): Address as Private @sp 1 @cartouche @code{Address} should be of a private type. *************** Followed. *** 4475,4481 **** @cindex Operations, on @code{Address} @cindex @code{Address}, operations of ! @item 13.7.1(16): Address Operations @sp 1 @cartouche Operations in @code{System} and its children should reflect the target --- 5319,5325 ---- @cindex Operations, on @code{Address} @cindex @code{Address}, operations of ! @unnumberedsec 13.7.1(16): Address Operations @sp 1 @cartouche Operations in @code{System} and its children should reflect the target *************** Followed. Address arithmetic is modular *** 4487,4499 **** operation raises @code{Program_Error}, since all operations make sense. @cindex Unchecked conversion ! @item 13.9(14-17): Unchecked Conversion @sp 1 @cartouche The @code{Size} of an array object should not include its bounds; hence, the bounds should not be part of the converted data. @end cartouche ! Followed. @sp 1 @cartouche --- 5331,5343 ---- operation raises @code{Program_Error}, since all operations make sense. @cindex Unchecked conversion ! @unnumberedsec 13.9(14-17): Unchecked Conversion @sp 1 @cartouche The @code{Size} of an array object should not include its bounds; hence, the bounds should not be part of the converted data. @end cartouche ! Followed. @sp 1 @cartouche *************** component subtype is one of the subtypes *** 4521,4530 **** and for record subtypes without discriminants whose component subtypes are described in this paragraph. @end cartouche ! Followed. @cindex Heap usage, implicit ! @item 13.11(23-25): Implicit Heap Usage @sp 1 @cartouche An implementation should document any cases in which it dynamically --- 5365,5374 ---- and for record subtypes without discriminants whose component subtypes are described in this paragraph. @end cartouche ! Followed. @cindex Heap usage, implicit ! @unnumberedsec 13.11(23-25): Implicit Heap Usage @sp 1 @cartouche An implementation should document any cases in which it dynamically *************** stack is used for returning variable len *** 4549,4559 **** @sp 1 @cartouche ! A default (implementation-provided) storage pool for an access-to-constant type should not have overhead to support deallocation of individual objects. @end cartouche ! Followed. @sp 1 @cartouche --- 5393,5403 ---- @sp 1 @cartouche ! A default (implementation-provided) storage pool for an access-to-constant type should not have overhead to support deallocation of individual objects. @end cartouche ! Followed. @sp 1 @cartouche *************** A storage pool for an anonymous access t *** 4561,4579 **** point of an allocator for the type, and be reclaimed when the designated object becomes inaccessible. @end cartouche ! Followed. @cindex Unchecked deallocation ! @item 13.11.2(17): Unchecked De-allocation @sp 1 @cartouche For a standard storage pool, @code{Free} should actually reclaim the storage. @end cartouche ! Followed. @cindex Stream oriented attributes ! @item 13.13.2(17): Stream Oriented Attributes @sp 1 @cartouche If a stream element is the same size as a storage element, then the --- 5405,5423 ---- point of an allocator for the type, and be reclaimed when the designated object becomes inaccessible. @end cartouche ! Followed. @cindex Unchecked deallocation ! @unnumberedsec 13.11.2(17): Unchecked De-allocation @sp 1 @cartouche For a standard storage pool, @code{Free} should actually reclaim the storage. @end cartouche ! Followed. @cindex Stream oriented attributes ! @unnumberedsec 13.13.2(17): Stream Oriented Attributes @sp 1 @cartouche If a stream element is the same size as a storage element, then the *************** normal in-memory representation should b *** 4582,4591 **** should use the smallest number of stream elements needed to represent all values in the base range of the scalar type. @end cartouche - Followed. In particular, the interpretation chosen is that of AI-195, - which specifies that the size to be used is that of the first subtype. ! @item A.1(52): Implementation Advice @sp 1 @cartouche If an implementation provides additional named predefined integer types, --- 5426,5464 ---- should use the smallest number of stream elements needed to represent all values in the base range of the scalar type. @end cartouche ! Followed. By default, GNAT uses the interpretation suggested by AI-195, ! which specifies using the size of the first subtype. ! However, such an implementation is based on direct binary ! representations and is therefore target- and endianness-dependent. ! To address this issue, GNAT also supplies an alternate implementation ! of the stream attributes @code{Read} and @code{Write}, ! which uses the target-independent XDR standard representation ! for scalar types. ! @cindex XDR representation ! @cindex @code{Read} attribute ! @cindex @code{Write} attribute ! @cindex Stream oriented attributes ! The XDR implementation is provided as an alternative body of the ! @code{System.Stream_Attributes} package, in the file ! @file{s-strxdr.adb} in the GNAT library. ! There is no @file{s-strxdr.ads} file. ! In order to install the XDR implementation, do the following: ! @enumerate ! @item Replace the default implementation of the ! @code{System.Stream_Attributes} package with the XDR implementation. ! For example on a Unix platform issue the commands: ! @smallexample ! $ mv s-stratt.adb s-strold.adb ! $ mv s-strxdr.adb s-stratt.adb ! @end smallexample ! ! @item ! Rebuild the GNAT run-time library as documented in the ! @cite{GNAT User's Guide} ! @end enumerate ! ! @unnumberedsec A.1(52): Names of Predefined Numeric Types @sp 1 @cartouche If an implementation provides additional named predefined integer types, *************** then the names should end with @samp{Int *** 4594,4603 **** predefined floating point types, then the names should end with @samp{Float} as in @samp{Long_Float}. @end cartouche ! Followed. @findex Ada.Characters.Handling ! @item A.3.2(49): @code{Ada.Characters.Handling} @sp 1 @cartouche If an implementation provides a localized definition of @code{Character} --- 5467,5476 ---- predefined floating point types, then the names should end with @samp{Float} as in @samp{Long_Float}. @end cartouche ! Followed. @findex Ada.Characters.Handling ! @unnumberedsec A.3.2(49): @code{Ada.Characters.Handling} @sp 1 @cartouche If an implementation provides a localized definition of @code{Character} *************** or @code{Wide_Character}, then the effec *** 4605,4629 **** @code{Characters.Handling} should reflect the localizations. See also 3.5.2. @end cartouche ! Followed. GNAT provides no such localized definitions. @cindex Bounded-length strings ! @item A.4.4(106): Bounded-Length String Handling @sp 1 @cartouche Bounded string objects should not be implemented by implicit pointers and dynamic allocation. @end cartouche ! Followed. No implicit pointers or dynamic allocation are used. @cindex Random number generation ! @item A.5.2(46-47): Random Number Generation @sp 1 @cartouche Any storage associated with an object of type @code{Generator} should be reclaimed on exit from the scope of the object. @end cartouche ! Followed. @sp 1 @cartouche --- 5478,5502 ---- @code{Characters.Handling} should reflect the localizations. See also 3.5.2. @end cartouche ! Followed. GNAT provides no such localized definitions. @cindex Bounded-length strings ! @unnumberedsec A.4.4(106): Bounded-Length String Handling @sp 1 @cartouche Bounded string objects should not be implemented by implicit pointers and dynamic allocation. @end cartouche ! Followed. No implicit pointers or dynamic allocation are used. @cindex Random number generation ! @unnumberedsec A.5.2(46-47): Random Number Generation @sp 1 @cartouche Any storage associated with an object of type @code{Generator} should be reclaimed on exit from the scope of the object. @end cartouche ! Followed. @sp 1 @cartouche *************** between initiator values and generator s *** 4636,4645 **** varying function of the initiator value. @end cartouche Followed. The generator period is sufficiently long for the first ! condition here to hold true. @findex Get_Immediate ! @item A.10.7(23): @code{Get_Immediate} @sp 1 @cartouche The @code{Get_Immediate} procedures should be implemented with --- 5509,5518 ---- varying function of the initiator value. @end cartouche Followed. The generator period is sufficiently long for the first ! condition here to hold true. @findex Get_Immediate ! @unnumberedsec A.10.7(23): @code{Get_Immediate} @sp 1 @cartouche The @code{Get_Immediate} procedures should be implemented with *************** associated with a keyboard-like device, *** 4650,4659 **** underlying operating system should be disabled during the execution of @code{Get_Immediate}. @end cartouche ! Followed. @findex Export ! @item B.1(39-41): Pragma @code{Export} @sp 1 @cartouche If an implementation supports pragma @code{Export} to a given language, --- 5523,5536 ---- underlying operating system should be disabled during the execution of @code{Get_Immediate}. @end cartouche ! Followed on all targets except VxWorks. For VxWorks, there is no way to ! provide this functionality that does not result in the input buffer being ! flushed before the @code{Get_Immediate} call. A special unit ! @code{Interfaces.Vxworks.IO} is provided that contains routines to enable ! this functionality. @findex Export ! @unnumberedsec B.1(39-41): Pragma @code{Export} @sp 1 @cartouche If an implementation supports pragma @code{Export} to a given language, *************** elaboration code for library units. @co *** 4667,4673 **** finalization code. These subprograms should have no effect the second and subsequent time they are called. @end cartouche ! Followed. @sp 1 @cartouche --- 5544,5550 ---- finalization code. These subprograms should have no effect the second and subsequent time they are called. @end cartouche ! Followed. @sp 1 @cartouche *************** for objects of @var{L}-compatible types *** 4688,4698 **** presuming the other language has corresponding features. Pragma @code{Convention} need not be supported for scalar types. @end cartouche ! Followed. @cindex Package @code{Interfaces} @findex Interfaces ! @item B.2(12-13): Package @code{Interfaces} @sp 1 @cartouche For each implementation-defined convention identifier, there should be a --- 5565,5575 ---- presuming the other language has corresponding features. Pragma @code{Convention} need not be supported for scalar types. @end cartouche ! Followed. @cindex Package @code{Interfaces} @findex Interfaces ! @unnumberedsec B.2(12-13): Package @code{Interfaces} @sp 1 @cartouche For each implementation-defined convention identifier, there should be a *************** An implementation supporting an interfac *** 4713,4722 **** provide the corresponding package or packages described in the following clauses. @end cartouche ! Followed. GNAT provides all the packages described in this section. @cindex C, interfacing with ! @item B.3(63-71): Interfacing with C @sp 1 @cartouche An implementation should support the following interface correspondences --- 5590,5599 ---- provide the corresponding package or packages described in the following clauses. @end cartouche ! Followed. GNAT provides all the packages described in this section. @cindex C, interfacing with ! @unnumberedsec B.3(63-71): Interfacing with C @sp 1 @cartouche An implementation should support the following interface correspondences *************** Followed. *** 4728,4747 **** @cartouche An Ada procedure corresponds to a void-returning C function. @end cartouche ! Followed. @sp 1 @cartouche An Ada function corresponds to a non-void C function. @end cartouche ! Followed. @sp 1 @cartouche An Ada @code{in} scalar parameter is passed as a scalar argument to a C function. @end cartouche ! Followed. @sp 1 @cartouche --- 5605,5624 ---- @cartouche An Ada procedure corresponds to a void-returning C function. @end cartouche ! Followed. @sp 1 @cartouche An Ada function corresponds to a non-void C function. @end cartouche ! Followed. @sp 1 @cartouche An Ada @code{in} scalar parameter is passed as a scalar argument to a C function. @end cartouche ! Followed. @sp 1 @cartouche *************** An Ada @code{in} parameter of an access- *** 4749,4755 **** type @var{T} is passed as a @code{@var{t}*} argument to a C function, where @var{t} is the C type corresponding to the Ada type @var{T}. @end cartouche ! Followed. @sp 1 @cartouche --- 5626,5632 ---- type @var{T} is passed as a @code{@var{t}*} argument to a C function, where @var{t} is the C type corresponding to the Ada type @var{T}. @end cartouche ! Followed. @sp 1 @cartouche *************** the Ada type @var{T}. In the case of an *** 4760,4766 **** @code{in out} parameter, a pointer to a temporary copy is used to preserve by-copy semantics. @end cartouche ! Followed. @sp 1 @cartouche --- 5637,5643 ---- @code{in out} parameter, a pointer to a temporary copy is used to preserve by-copy semantics. @end cartouche ! Followed. @sp 1 @cartouche *************** An Ada parameter of an array type with c *** 4778,4784 **** mode, is passed as a @code{@var{t}*} argument to a C function, where @var{t} is the C type corresponding to the Ada type @var{T}. @end cartouche ! Followed. @sp 1 @cartouche --- 5655,5661 ---- mode, is passed as a @code{@var{t}*} argument to a C function, where @var{t} is the C type corresponding to the Ada type @var{T}. @end cartouche ! Followed. @sp 1 @cartouche *************** An Ada parameter of an access-to-subprog *** 4786,4795 **** to a C function whose prototype corresponds to the designated subprogram's specification. @end cartouche ! Followed. @cindex COBOL, interfacing with ! @item B.4(95-98): Interfacing with COBOL @sp 1 @cartouche An Ada implementation should support the following interface --- 5663,5672 ---- to a C function whose prototype corresponds to the designated subprogram's specification. @end cartouche ! Followed. @cindex COBOL, interfacing with ! @unnumberedsec B.4(95-98): Interfacing with COBOL @sp 1 @cartouche An Ada implementation should support the following interface *************** Followed. *** 4802,4815 **** An Ada access @var{T} parameter is passed as a @samp{BY REFERENCE} data item of the COBOL type corresponding to @var{T}. @end cartouche ! Followed. @sp 1 @cartouche An Ada in scalar parameter is passed as a @samp{BY CONTENT} data item of the corresponding COBOL type. @end cartouche ! Followed. @sp 1 @cartouche --- 5679,5692 ---- An Ada access @var{T} parameter is passed as a @samp{BY REFERENCE} data item of the COBOL type corresponding to @var{T}. @end cartouche ! Followed. @sp 1 @cartouche An Ada in scalar parameter is passed as a @samp{BY CONTENT} data item of the corresponding COBOL type. @end cartouche ! Followed. @sp 1 @cartouche *************** Any other Ada parameter is passed as a @ *** 4817,4826 **** COBOL type corresponding to the Ada parameter type; for scalars, a local copy is used if necessary to ensure by-copy semantics. @end cartouche ! Followed. @cindex Fortran, interfacing with ! @item B.5(22-26): Interfacing with Fortran @sp 1 @cartouche An Ada implementation should support the following interface --- 5694,5703 ---- COBOL type corresponding to the Ada parameter type; for scalars, a local copy is used if necessary to ensure by-copy semantics. @end cartouche ! Followed. @cindex Fortran, interfacing with ! @unnumberedsec B.5(22-26): Interfacing with Fortran @sp 1 @cartouche An Ada implementation should support the following interface *************** designated subprogram's specification. *** 4861,4867 **** Followed. @cindex Machine operations ! @item C.1(3-5): Access to Machine Operations @sp 1 @cartouche The machine code or intrinsic support should allow access to all --- 5738,5744 ---- Followed. @cindex Machine operations ! @unnumberedsec C.1(3-5): Access to Machine Operations @sp 1 @cartouche The machine code or intrinsic support should allow access to all *************** The interfacing pragmas (see Annex B) sh *** 4876,4882 **** assembler; the default assembler should be associated with the convention identifier @code{Assembler}. @end cartouche ! Followed. @sp 1 @cartouche --- 5753,5759 ---- assembler; the default assembler should be associated with the convention identifier @code{Assembler}. @end cartouche ! Followed. @sp 1 @cartouche *************** from the Ada code. The implementation s *** 4887,4895 **** machine code or assembler subprogram is allowed to read or update every object that is specified as exported. @end cartouche ! Followed. ! @item C.1(10-16): Access to Machine Operations @sp 1 @cartouche The implementation should ensure that little or no overhead is --- 5764,5772 ---- machine code or assembler subprogram is allowed to read or update every object that is specified as exported. @end cartouche ! Followed. ! @unnumberedsec C.1(10-16): Access to Machine Operations @sp 1 @cartouche The implementation should ensure that little or no overhead is *************** Direct operations on I/O ports. *** 4938,4944 **** Followed on any target supporting such operations. @cindex Interrupt support ! @item C.3(28): Interrupt Support @sp 1 @cartouche If the @code{Ceiling_Locking} policy is not in effect, the --- 5815,5821 ---- Followed on any target supporting such operations. @cindex Interrupt support ! @unnumberedsec C.3(28): Interrupt Support @sp 1 @cartouche If the @code{Ceiling_Locking} policy is not in effect, the *************** Followed. The underlying system does no *** 4950,4956 **** of interrupt blocking. @cindex Protected procedure handlers ! @item C.3.1(20-21): Protected Procedure Handlers @sp 1 @cartouche Whenever possible, the implementation should allow interrupt handlers to --- 5827,5833 ---- of interrupt blocking. @cindex Protected procedure handlers ! @unnumberedsec C.3.1(20-21): Protected Procedure Handlers @sp 1 @cartouche Whenever possible, the implementation should allow interrupt handlers to *************** be called directly by the hardware. *** 4958,4964 **** @end cartouche @c SGI info: @ignore ! This is never possible under IRIX, so this is followed by default. @end ignore Followed on any target where the underlying operating system permits such direct calls. --- 5835,5841 ---- @end cartouche @c SGI info: @ignore ! This is never possible under IRIX, so this is followed by default. @end ignore Followed on any target where the underlying operating system permits such direct calls. *************** such direct calls. *** 4968,4978 **** Whenever practical, violations of any implementation-defined restrictions should be detected before run time. @end cartouche ! Followed. Compile time warnings are given when possible. @cindex Package @code{Interrupts} @findex Interrupts ! @item C.3.2(25): Package @code{Interrupts} @sp 1 @cartouche --- 5845,5855 ---- Whenever practical, violations of any implementation-defined restrictions should be detected before run time. @end cartouche ! Followed. Compile time warnings are given when possible. @cindex Package @code{Interrupts} @findex Interrupts ! @unnumberedsec C.3.2(25): Package @code{Interrupts} @sp 1 @cartouche *************** such form of a handler, a type analogous *** 4982,4991 **** should be specified in a child package of @code{Interrupts}, with the same operations as in the predefined package Interrupts. @end cartouche ! Followed. @cindex Pre-elaboration requirements ! @item C.4(14): Pre-elaboration Requirements @sp 1 @cartouche It is recommended that pre-elaborated packages be implemented in such a --- 5859,5868 ---- should be specified in a child package of @code{Interrupts}, with the same operations as in the predefined package Interrupts. @end cartouche ! Followed. @cindex Pre-elaboration requirements ! @unnumberedsec C.4(14): Pre-elaboration Requirements @sp 1 @cartouche It is recommended that pre-elaborated packages be implemented in such a *************** Requirements. *** 4996,5002 **** Followed. Executable code is generated in some cases, e.g.@: loops to initialize large arrays. ! @item C.5(8): Pragma @code{Discard_Names} @sp 1 @cartouche --- 5873,5879 ---- Followed. Executable code is generated in some cases, e.g.@: loops to initialize large arrays. ! @unnumberedsec C.5(8): Pragma @code{Discard_Names} @sp 1 @cartouche *************** Followed. *** 5008,5014 **** @cindex Package @code{Task_Attributes} @findex Task_Attributes ! @item C.7.2(30): The Package Task_Attributes @sp 1 @cartouche Some implementations are targeted to domains in which memory use at run --- 5885,5891 ---- @cindex Package @code{Task_Attributes} @findex Task_Attributes ! @unnumberedsec C.7.2(30): The Package Task_Attributes @sp 1 @cartouche Some implementations are targeted to domains in which memory use at run *************** attributes, or by using the pre-allocate *** 5020,5029 **** attribute objects, and the heap for the others. In the latter case, @var{N} should be documented. @end cartouche ! Not followed. This implementation is not targeted to such a domain. @cindex Locking Policies ! @item D.3(17): Locking Policies @sp 1 @cartouche --- 5897,5906 ---- attribute objects, and the heap for the others. In the latter case, @var{N} should be documented. @end cartouche ! Not followed. This implementation is not targeted to such a domain. @cindex Locking Policies ! @unnumberedsec D.3(17): Locking Policies @sp 1 @cartouche *************** Followed. A single implementation-defin *** 5034,5049 **** whose name (@code{Inheritance_Locking}) follows this suggestion. @cindex Entry queuing policies ! @item D.4(16): Entry Queuing Policies @sp 1 @cartouche Names that end with @samp{_Queuing} should be used for all implementation-defined queuing policies. @end cartouche ! Followed. No such implementation-defined queueing policies exist. @cindex Preemptive abort ! @item D.6(9-10): Preemptive Abort @sp 1 @cartouche Even though the @code{abort_statement} is included in the list of --- 5911,5926 ---- whose name (@code{Inheritance_Locking}) follows this suggestion. @cindex Entry queuing policies ! @unnumberedsec D.4(16): Entry Queuing Policies @sp 1 @cartouche Names that end with @samp{_Queuing} should be used for all implementation-defined queuing policies. @end cartouche ! Followed. No such implementation-defined queuing policies exist. @cindex Preemptive abort ! @unnumberedsec D.6(9-10): Preemptive Abort @sp 1 @cartouche Even though the @code{abort_statement} is included in the list of *************** potentially blocking operations (see 9.5 *** 5051,5057 **** statement be implemented in a way that never requires the task executing the @code{abort_statement} to block. @end cartouche ! Followed. @sp 1 @cartouche --- 5928,5934 ---- statement be implemented in a way that never requires the task executing the @code{abort_statement} to block. @end cartouche ! Followed. @sp 1 @cartouche *************** On a multi-processor, the delay associat *** 5059,5068 **** another processor should be bounded; the implementation should use periodic polling, if necessary, to achieve this. @end cartouche ! Followed. @cindex Tasking restrictions ! @item D.7(21): Tasking Restrictions @sp 1 @cartouche When feasible, the implementation should take advantage of the specified --- 5936,5945 ---- another processor should be bounded; the implementation should use periodic polling, if necessary, to achieve this. @end cartouche ! Followed. @cindex Tasking restrictions ! @unnumberedsec D.7(21): Tasking Restrictions @sp 1 @cartouche When feasible, the implementation should take advantage of the specified *************** of restrictions are specified. See prag *** 5074,5080 **** @code{Restricted_Run_Time} for more details. @cindex Time, monotonic ! @item D.8(47-49): Monotonic Time @sp 1 @cartouche When appropriate, implementations should provide configuration --- 5951,5957 ---- @code{Restricted_Run_Time} for more details. @cindex Time, monotonic ! @unnumberedsec D.8(47-49): Monotonic Time @sp 1 @cartouche When appropriate, implementations should provide configuration *************** and are thus not supported. *** 5088,5094 **** It is recommended that @code{Calendar.Clock} and @code{Real_Time.Clock} be implemented as transformations of the same time base. @end cartouche ! Followed. @sp 1 @cartouche --- 5965,5971 ---- It is recommended that @code{Calendar.Clock} and @code{Real_Time.Clock} be implemented as transformations of the same time base. @end cartouche ! Followed. @sp 1 @cartouche *************** It is recommended that the @dfn{best} ti *** 5096,5106 **** the underlying system be available to the application through @code{Clock}. @dfn{Best} may mean highest accuracy or largest range. @end cartouche ! Followed. @cindex Partition communication subsystem @cindex PCS ! @item E.5(28-29): Partition Communication Subsystem @sp 1 @cartouche Whenever possible, the PCS on the called partition should allow for --- 5973,5983 ---- the underlying system be available to the application through @code{Clock}. @dfn{Best} may mean highest accuracy or largest range. @end cartouche ! Followed. @cindex Partition communication subsystem @cindex PCS ! @unnumberedsec E.5(28-29): Partition Communication Subsystem @sp 1 @cartouche Whenever possible, the PCS on the called partition should allow for *************** should allow them to block until the cor *** 5109,5115 **** returns. @end cartouche Followed by GLADE, a separately supplied PCS that can be used with ! GNAT. @sp 1 @cartouche --- 5986,5992 ---- returns. @end cartouche Followed by GLADE, a separately supplied PCS that can be used with ! GNAT. @sp 1 @cartouche *************** should raise @code{Storage_Error} if it *** 5118,5127 **** write the @code{Item} into the stream. @end cartouche Followed by GLADE, a separately supplied PCS that can be used with ! GNAT@. @cindex COBOL support ! @item F(7): COBOL Support @sp 1 @cartouche If COBOL (respectively, C) is widely supported in the target --- 5995,6004 ---- write the @code{Item} into the stream. @end cartouche Followed by GLADE, a separately supplied PCS that can be used with ! GNAT@. @cindex COBOL support ! @unnumberedsec F(7): COBOL Support @sp 1 @cartouche If COBOL (respectively, C) is widely supported in the target *************** should provide the child package @code{I *** 5132,5141 **** pragmas (see Annex B), thus allowing Ada programs to interface with programs written in that language. @end cartouche ! Followed. @cindex Decimal radix support ! @item F.1(2): Decimal Radix Support @sp 1 @cartouche Packed decimal should be used as the internal representation for objects --- 6009,6018 ---- pragmas (see Annex B), thus allowing Ada programs to interface with programs written in that language. @end cartouche ! Followed. @cindex Decimal radix support ! @unnumberedsec F.1(2): Decimal Radix Support @sp 1 @cartouche Packed decimal should be used as the internal representation for objects *************** Not followed. GNAT ignores @var{S}'Mach *** 5145,5151 **** representations. @cindex Numerics ! @item G: Numerics @sp 2 @cartouche If Fortran (respectively, C) is widely supported in the target --- 6022,6028 ---- representations. @cindex Numerics ! @unnumberedsec G: Numerics @sp 2 @cartouche If Fortran (respectively, C) is widely supported in the target *************** programs written in that language. *** 5159,5165 **** Followed. @cindex Complex types ! @item G.1.1(56-58): Complex Types @sp 2 @cartouche Because the usual mathematical meaning of multiplication of a complex --- 6036,6042 ---- Followed. @cindex Complex types ! @unnumberedsec G.1.1(56-58): Complex Types @sp 2 @cartouche Because the usual mathematical meaning of multiplication of a complex *************** case of multiplication of a complex oper *** 5176,5182 **** operand, and in the case of division of a complex operand by a real or pure-imaginary operand. @end cartouche ! Not followed. @sp 1 @cartouche --- 6053,6059 ---- operand, and in the case of division of a complex operand by a real or pure-imaginary operand. @end cartouche ! Not followed. @sp 1 @cartouche *************** Analogous advice applies in the case of *** 5195,5201 **** and a pure-imaginary operand, and in the case of subtraction of a complex operand and a real or pure-imaginary operand. @end cartouche ! Not followed. @sp 1 @cartouche --- 6072,6078 ---- and a pure-imaginary operand, and in the case of subtraction of a complex operand and a real or pure-imaginary operand. @end cartouche ! Not followed. @sp 1 @cartouche *************** of the @code{Compose_From_Polar} functio *** 5210,5219 **** parameter has a value of zero and the @code{Modulus} parameter has a nonnegative (respectively, negative) value. @end cartouche ! Followed. @cindex Complex elementary functions ! @item G.1.2(49): Complex Elementary Functions @sp 1 @cartouche Implementations in which @code{Complex_Types.Real'Signed_Zeros} is --- 6087,6096 ---- parameter has a value of zero and the @code{Modulus} parameter has a nonnegative (respectively, negative) value. @end cartouche ! Followed. @cindex Complex elementary functions ! @unnumberedsec G.1.2(49): Complex Elementary Functions @sp 1 @cartouche Implementations in which @code{Complex_Types.Real'Signed_Zeros} is *************** elementary functions have zero component *** 5226,5235 **** a parameter component at the origin, or is always positive or always negative. @end cartouche ! Followed. @cindex Accuracy requirements ! @item G.2.4(19): Accuracy Requirements @sp 1 @cartouche The versions of the forward trigonometric functions without a --- 6103,6112 ---- a parameter component at the origin, or is always positive or always negative. @end cartouche ! Followed. @cindex Accuracy requirements ! @unnumberedsec G.2.4(19): Accuracy Requirements @sp 1 @cartouche The versions of the forward trigonometric functions without a *************** version of @code{Log} without a @code{Ba *** 5241,5251 **** implemented by calling the corresponding version with a @code{Base} parameter of @code{Numerics.e}. @end cartouche ! Followed. @cindex Complex arithmetic accuracy @cindex Accuracy, complex arithmetic ! @item G.2.6(15): Complex Arithmetic Accuracy @sp 1 @cartouche --- 6118,6128 ---- implemented by calling the corresponding version with a @code{Base} parameter of @code{Numerics.e}. @end cartouche ! Followed. @cindex Complex arithmetic accuracy @cindex Accuracy, complex arithmetic ! @unnumberedsec G.2.6(15): Complex Arithmetic Accuracy @sp 1 @cartouche *************** accuracy in some portions of the domain. *** 5257,5265 **** @end cartouche Followed. ! @end table @node Implementation Defined Characteristics @chapter Implementation Defined Characteristics In addition to the implementation dependent pragmas and attributes, and the implementation advice, there are a number of other features of Ada 95 that are potentially implementation dependent. These are mentioned --- 6134,6144 ---- @end cartouche Followed. ! @c ----------------------------------------- @node Implementation Defined Characteristics @chapter Implementation Defined Characteristics + + @noindent In addition to the implementation dependent pragmas and attributes, and the implementation advice, there are a number of other features of Ada 95 that are potentially implementation dependent. These are mentioned *************** followed by a description in italic font *** 5272,5278 **** @c SGI info: @ignore in the ProDev Ada ! implementation on IRIX 5.3 operating system or greater @end ignore handles the implementation dependence. --- 6151,6157 ---- @c SGI info: @ignore in the ProDev Ada ! implementation on IRIX 5.3 operating system or greater @end ignore handles the implementation dependence. *************** further details. *** 5414,5420 **** for them. See 3.5.4(26). @end cartouche @noindent ! There are no nonstandard integer types. @sp 1 @cartouche --- 6293,6299 ---- for them. See 3.5.4(26). @end cartouche @noindent ! There are no nonstandard integer types. @sp 1 @cartouche *************** There are no nonstandard integer types. *** 5423,5429 **** them. See 3.5.6(8). @end cartouche @noindent ! There are no nonstandard real types. @sp 1 @cartouche --- 6302,6308 ---- them. See 3.5.6(8). @end cartouche @noindent ! There are no nonstandard real types. @sp 1 @cartouche *************** There are no nonstandard real types. *** 5432,5438 **** are supported for floating point types. See 3.5.7(7). @end cartouche @noindent ! The precision and range is as defined by the IEEE standard. @sp 1 @cartouche --- 6311,6317 ---- are supported for floating point types. See 3.5.7(7). @end cartouche @noindent ! The precision and range is as defined by the IEEE standard. @sp 1 @cartouche *************** The precision and range is as defined by *** 5442,5454 **** @end cartouche @noindent @table @code ! @item Short_Float 32 bit IEEE short ! @item Float ! (Short) 32 bit IEEE short ! @item Long_Float ! 64 bit IEEE long ! @item Long_Long_Float 64 bit IEEE long (80 bit IEEE long on x86 processors) @end table --- 6321,6333 ---- @end cartouche @noindent @table @code ! @item Short_Float 32 bit IEEE short ! @item Float ! (Short) 32 bit IEEE short ! @item Long_Float ! 64 bit IEEE long ! @item Long_Long_Float 64 bit IEEE long (80 bit IEEE long on x86 processors) @end table *************** The precision and range is as defined by *** 5458,5464 **** @strong{18}. The small of an ordinary fixed point type. See 3.5.9(8). @end cartouche @noindent ! @code{Fine_Delta} is 2**(@minus{}63) @sp 1 @cartouche --- 6337,6343 ---- @strong{18}. The small of an ordinary fixed point type. See 3.5.9(8). @end cartouche @noindent ! @code{Fine_Delta} is 2**(@minus{}63) @sp 1 @cartouche *************** decimal integer are allocated. *** 5498,5504 **** @strong{22}. Any implementation-defined time types. See 9.6(6). @end cartouche @noindent ! There are no implementation-defined time types. @sp 1 @cartouche --- 6377,6383 ---- @strong{22}. Any implementation-defined time types. See 9.6(6). @end cartouche @noindent ! There are no implementation-defined time types. @sp 1 @cartouche *************** setting for local time, as accessed by t *** 5537,5543 **** @code{select_statements}. See 9.6(29). @end cartouche @noindent ! There are no such limits. @sp 1 @cartouche --- 6416,6422 ---- @code{select_statements}. See 9.6(29). @end cartouche @noindent ! There are no such limits. @sp 1 @cartouche *************** compilation. *** 5578,5584 **** and replacing compilation units. See 10.1.4(3). @end cartouche @noindent ! See separate section on compilation model. @sp 1 @cartouche --- 6457,6463 ---- and replacing compilation units. See 10.1.4(3). @end cartouche @noindent ! See separate section on compilation model. @sp 1 @cartouche *************** units are required, e.g.@: by foreign la *** 5598,5609 **** mentioned in the context clause of one of the needed Ada units. If the partition contains no main program, or if the main program is in ! a language other than Ada, then GNAT ! provides the binder options @code{-z} and @code{-n} respectively, and in this case a ! list of units can be explicitly supplied to the binder for inclusion in ! the partition (all units needed by these units will also be included ! automatically). For full details on the use of these options, refer to ! the @cite{GNAT User's Guide} sections on Binding and Linking. @sp 1 @cartouche --- 6477,6489 ---- mentioned in the context clause of one of the needed Ada units. If the partition contains no main program, or if the main program is in ! a language other than Ada, then GNAT ! provides the binder options @code{-z} and @code{-n} respectively, and in ! this case a list of units can be explicitly supplied to the binder for ! inclusion in the partition (all units needed by these units will also ! be included automatically). For full details on the use of these ! options, refer to the @cite{GNAT User's Guide} sections on Binding ! and Linking. @sp 1 @cartouche *************** which compilation units are needed by a *** 5614,5620 **** @end cartouche @noindent The units needed by a given compilation unit are as defined in ! the Ada Reference Manual section 10.2(2-6). There are no implementation-defined pragmas or other implementation-defined means for specifying needed units. --- 6494,6500 ---- @end cartouche @noindent The units needed by a given compilation unit are as defined in ! the Ada Reference Manual section 10.2(2-6). There are no implementation-defined pragmas or other implementation-defined means for specifying needed units. *************** subprogram. See 10.2(21). *** 5653,5659 **** @noindent The main program has no parameters. It may be a procedure, or a function returning an integer type. In the latter case, the returned integer ! value is the return code of the program. @sp 1 @cartouche --- 6533,6540 ---- @noindent The main program has no parameters. It may be a procedure, or a function returning an integer type. In the latter case, the returned integer ! value is the return code of the program (overriding any value that ! may have been set by a call to @code{Ada.Command_Line.Set_Exit_Status}). @sp 1 @cartouche *************** the last line is a single @code{LF} char *** 5758,5764 **** @strong{42}. Implementation-defined check names. See 11.5(27). @end cartouche @noindent ! No implementation-defined check names are supported. @sp 1 @cartouche --- 6639,6645 ---- @strong{42}. Implementation-defined check names. See 11.5(27). @end cartouche @noindent ! No implementation-defined check names are supported. @sp 1 @cartouche *************** is made to queue more than the specified *** 5952,5957 **** --- 6833,6846 ---- This restriction ensures at compile time that there is no implicit or explicit dependence on the package @code{Ada.Calendar}. + @item No_Direct_Boolean_Operators + @findex No_Direct_Boolean_Operators + This restrcition ensures that no logical (and/or/xor) or comparison + operators are used on operands of type Boolean (or any type derived + from Boolean). This is intended for use in safety critical programs + where the certification protocol requires the use of short-circuit + (and then, or else) forms for all composite boolean operations. + @item No_Dynamic_Interrupts @findex No_Dynamic_Interrupts This restriction ensures at compile time that there is no attempt to *************** in a task can be executed at elaboration *** 5973,5987 **** @item No_Exception_Handlers @findex No_Exception_Handlers This restriction ensures at compile time that there are no explicit ! exception handlers. @item No_Implicit_Conditionals @findex No_Implicit_Conditionals This restriction ensures that the generated code does not contain any implicit conditionals, either by modifying the generated code where possible, or by rejecting any construct that would otherwise generate an implicit ! conditional. The details and use of this restriction are described in ! more detail in the High Integrity product documentation. @item No_Implicit_Loops @findex No_Implicit_Loops --- 6862,6907 ---- @item No_Exception_Handlers @findex No_Exception_Handlers This restriction ensures at compile time that there are no explicit ! exception handlers. It also indicates that no exception propagation will ! be provided. In this mode, exceptions may be raised but will result in ! an immediate call to the last chance handler, a routine that the user ! must define with the following profile: ! ! procedure Last_Chance_Handler ! (Source_Location : System.Address; Line : Integer); ! pragma Export (C, Last_Chance_Handler, ! "__gnat_last_chance_handler"); ! ! The parameter is a C null-terminated string representing a message to be ! associated with the exception (typically the source location of the raise ! statement generated by the compiler). The Line parameter when non-zero ! represents the line number in the source program where the raise occurs. ! ! @item No_Exception_Streams ! @findex No_Exception_Streams ! This restriction ensures at compile time that no stream operations for ! types Exception_Id or Exception_Occurrence are used. This also makes it ! impossible to pass exceptions to or from a partition with this restriction ! in a distributed environment. If this exception is active, then the generated ! code is simplified by omitting the otherwise-required global registration ! of exceptions when they are declared. @item No_Implicit_Conditionals @findex No_Implicit_Conditionals This restriction ensures that the generated code does not contain any implicit conditionals, either by modifying the generated code where possible, or by rejecting any construct that would otherwise generate an implicit ! conditional. ! ! @item No_Implicit_Dynamic_Code ! @findex No_Implicit_Dynamic_Code ! This restriction prevents the compiler from building ``trampolines''. ! This is a structure that is built on the stack and contains dynamic ! code to be executed at run time. A trampoline is needed to indirectly ! address a nested subprogram (that is a subprogram that is not at the ! library level). The restriction prevents the use of any of the ! attributes @code{Address}, @code{Access} or @code{Unrestricted_Access} ! being applied to a subprogram that is not at the library level. @item No_Implicit_Loops @findex No_Implicit_Loops *************** This restriction ensures that the genera *** 5989,5996 **** implicit @code{for} loops, either by modifying the generated code where possible, or by rejecting any construct that would otherwise generate an implicit ! @code{for} loop. The details and use of this restriction are described in ! more detail in the High Integrity product documentation. @item No_Local_Protected_Objects @findex No_Local_Protected_Objects --- 6909,6922 ---- implicit @code{for} loops, either by modifying the generated code where possible, or by rejecting any construct that would otherwise generate an implicit ! @code{for} loop. ! ! @item No_Initialize_Scalars ! @findex No_Initialize_Scalars ! This restriction ensures that no unit in the partition is compiled with ! pragma Initialize_Scalars. This allows the generation of more efficient ! code, and in particular eliminates dummy null initialization routines that ! are otherwise generated for some record and array types. @item No_Local_Protected_Objects @findex No_Local_Protected_Objects *************** This restriction ensures at compile time *** 6008,6020 **** contain any reference to the secondary stack. The secondary stack is used to implement functions returning unconstrained objects (arrays or records) on some targets. - The details and use of this restriction are described in - more detail in the High Integrity product documentation. @item No_Select_Statements @findex No_Select_Statements This restriction ensures at compile time no select statements of any kind ! are permitted, that is the keyword @code{select} may not appear. This is one of the restrictions of the Ravenscar profile for limited tasking (see also pragma @code{Ravenscar}). --- 6934,6944 ---- contain any reference to the secondary stack. The secondary stack is used to implement functions returning unconstrained objects (arrays or records) on some targets. @item No_Select_Statements @findex No_Select_Statements This restriction ensures at compile time no select statements of any kind ! are permitted, that is the keyword @code{select} may not appear. This is one of the restrictions of the Ravenscar profile for limited tasking (see also pragma @code{Ravenscar}). *************** other compilation units in the partition *** 6081,6095 **** @findex No_Elaboration_Code This restriction ensures at compile time that no elaboration code is generated. Note that this is not the same condition as is enforced ! by pragma @code{Preelaborate}. There are cases in which pragma @code{Preelaborate} ! still permits code to be generated (e.g.@: code to initialize a large ! array to all zeroes), and there are cases of units which do not meet ! the requirements for pragma @code{Preelaborate}, but for which no elaboration ! code is generated. Generally, it is the case that preelaborable units ! will meet the restrictions, with the exception of large aggregates ! initialized with an others_clause, and exception declarations (which ! generate calls to a run-time registry procedure). Note that this restriction ! is enforced on a unit by unit basis, it need not be obeyed consistently throughout a partition. @item No_Entry_Queue --- 7005,7020 ---- @findex No_Elaboration_Code This restriction ensures at compile time that no elaboration code is generated. Note that this is not the same condition as is enforced ! by pragma @code{Preelaborate}. There are cases in which pragma ! @code{Preelaborate} still permits code to be generated (e.g.@: code ! to initialize a large array to all zeroes), and there are cases of units ! which do not meet the requirements for pragma @code{Preelaborate}, ! but for which no elaboration code is generated. Generally, it is ! the case that preelaborable units will meet the restrictions, with ! the exception of large aggregates initialized with an others_clause, ! and exception declarations (which generate calls to a run-time ! registry procedure). Note that this restriction is enforced on ! a unit by unit basis, it need not be obeyed consistently throughout a partition. @item No_Entry_Queue *************** The algorithm is documented in the sourc *** 6209,6215 **** state. See A.5.2(38). @end cartouche @noindent ! See the documentation contained in the file @file{a-numran.adb}. @sp 1 @cartouche --- 7134,7140 ---- state. See A.5.2(38). @end cartouche @noindent ! See the documentation contained in the file @file{a-numran.adb}. @sp 1 @cartouche *************** The following convention names are suppo *** 6297,6327 **** @table @code @item Ada Ada ! @item Assembler ! Assembly language ! @item Asm Synonym for Assembler ! @item Assembly Synonym for Assembler @item C C @item C_Pass_By_Copy Allowed only for record types, like C, but also notes that record is to be passed by copy rather than reference. ! @item COBOL ! COBOL ! @item CPP ! C++ @item Default Treated the same as C @item External Treated the same as C ! @item Fortran ! Fortran ! @item Intrinsic For support of pragma @code{Import} with convention Intrinsic, see separate section on Intrinsic Subprograms. ! @item Stdcall Stdcall (used for Windows implementations only). This convention correspond to the WINAPI (previously called Pascal convention) C/C++ convention under Windows. A function with this convention cleans the stack before exit. --- 7222,7252 ---- @table @code @item Ada Ada ! @item Assembler ! Assembly language ! @item Asm Synonym for Assembler ! @item Assembly Synonym for Assembler @item C C @item C_Pass_By_Copy Allowed only for record types, like C, but also notes that record is to be passed by copy rather than reference. ! @item COBOL ! COBOL ! @item CPP ! C++ @item Default Treated the same as C @item External Treated the same as C ! @item Fortran ! Fortran ! @item Intrinsic For support of pragma @code{Import} with convention Intrinsic, see separate section on Intrinsic Subprograms. ! @item Stdcall Stdcall (used for Windows implementations only). This convention correspond to the WINAPI (previously called Pascal convention) C/C++ convention under Windows. A function with this convention cleans the stack before exit. *************** The string passed to @code{Linker_Option *** 6374,6380 **** an argument to the link command, unless it contains Ascii.NUL characters. NUL characters if they appear act as argument separators, so for example ! @smallexample pragma Linker_Options ("-labc" & ASCII.Nul & "-ldef"); @end smallexample --- 7299,7305 ---- an argument to the link command, unless it contains Ascii.NUL characters. NUL characters if they appear act as argument separators, so for example ! @smallexample @c ada pragma Linker_Options ("-labc" & ASCII.Nul & "-ldef"); @end smallexample *************** See files with prefix @file{i-} in the d *** 6417,6434 **** @table @code @item Floating Float ! @item Long_Floating ! (Floating) Long_Float ! @item Binary ! Integer ! @item Long_Binary ! Long_Long_Integer ! @item Decimal_Element ! Character ! @item COBOL_Character ! Character @end table For initialization, see the file @file{i-cobol.ads} in the distributed library. @sp 1 --- 7342,7360 ---- @table @code @item Floating Float ! @item Long_Floating ! (Floating) Long_Float ! @item Binary ! Integer ! @item Long_Binary ! Long_Long_Integer ! @item Decimal_Element ! Character ! @item COBOL_Character ! Character @end table + @noindent For initialization, see the file @file{i-cobol.ads} in the distributed library. @sp 1 *************** except under control of the debugger. *** 6476,6482 **** @end cartouche @noindent Pragma @code{Discard_Names} causes names of enumeration literals to ! be suppressed. In the presence of this pragma, the Image attribute provides the image of the Pos of the literal, and Value accepts Pos values. --- 7402,7408 ---- @end cartouche @noindent Pragma @code{Discard_Names} causes names of enumeration literals to ! be suppressed. In the presence of this pragma, the Image attribute provides the image of the Pos of the literal, and Value accepts Pos values. *************** The ceiling priority of internal protect *** 6650,6656 **** @strong{101}. Implementation-defined queuing policies. See D.4(1). @end cartouche @noindent ! There are no implementation-defined queueing policies. @sp 1 @cartouche --- 7576,7582 ---- @strong{101}. Implementation-defined queuing policies. See D.4(1). @end cartouche @noindent ! There are no implementation-defined queueing policies. @sp 1 @cartouche *************** task creation. *** 6680,6686 **** @code{Restrictions}. See D.7(20). @end cartouche @noindent ! There are no such implementation-defined aspects. @sp 1 @cartouche --- 7606,7612 ---- @code{Restrictions}. See D.7(20). @end cartouche @noindent ! There are no such implementation-defined aspects. @sp 1 @cartouche *************** negative exponent), when the floating po *** 6894,6900 **** as multiplication by a reciprocal. See G.2.1(16). @end cartouche @noindent ! Not relevant, division is IEEE exact. @sp 1 @cartouche --- 7820,7826 ---- as multiplication by a reciprocal. See G.2.1(16). @end cartouche @noindent ! Not relevant, division is IEEE exact. @sp 1 @cartouche *************** elementary function reference in overflo *** 6971,6977 **** @code{False}. See G.2.6(5). @end cartouche @noindent ! IEEE infinite and Nan values are produced as appropriate. @sp 1 @cartouche --- 7897,7903 ---- @code{False}. See G.2.6(5). @end cartouche @noindent ! IEEE infinite and Nan values are produced as appropriate. @sp 1 @cartouche *************** There are no restrictions on pragma @cod *** 7042,7050 **** * Source_Location:: @end menu GNAT allows a user application program to write the declaration: ! @smallexample pragma Import (Intrinsic, name); @end smallexample --- 7968,7977 ---- * Source_Location:: @end menu + @noindent GNAT allows a user application program to write the declaration: ! @smallexample @c ada pragma Import (Intrinsic, name); @end smallexample *************** All the predefined numeric operators in *** 7067,7079 **** in @code{pragma Import (Intrinsic,..)} declarations. In the binary operator case, the operands must have the same size. The operand or operands must also be appropriate for ! the operator. For example, for addition, the operands must both be floating-point or both be fixed-point, and the right operand for @code{"**"} must have a root type of @code{Standard.Integer'Base}. You can use an intrinsic operator declaration as in the following example: ! @smallexample type Int1 is new Integer; type Int2 is new Integer; --- 7994,8006 ---- in @code{pragma Import (Intrinsic,..)} declarations. In the binary operator case, the operands must have the same size. The operand or operands must also be appropriate for ! the operator. For example, for addition, the operands must both be floating-point or both be fixed-point, and the right operand for @code{"**"} must have a root type of @code{Standard.Integer'Base}. You can use an intrinsic operator declaration as in the following example: ! @smallexample @c ada type Int1 is new Integer; type Int2 is new Integer; *************** for the predefined modular types in pack *** 7163,7169 **** GNAT it is possible to define a Rotate_Left function for a user defined modular type or any signed integer type as in this example: ! @smallexample function Shift_Left (Value : My_Modular_Type; Amount : Natural) --- 8090,8096 ---- GNAT it is possible to define a Rotate_Left function for a user defined modular type or any signed integer type as in this example: ! @smallexample @c ada function Shift_Left (Value : My_Modular_Type; Amount : Natural) *************** default alignments are always a power of *** 7267,7282 **** values are as follows: @itemize @bullet ! @item Primitive Types ! For primitive types, the alignment is the maximum of the actual size of ! objects of the type, and the maximum alignment supported by the target. ! For example, for type Long_Float, the object size is 8 bytes, and the default alignment will be 8 on any target that supports alignments this large, but on some targets, the maximum alignment may be smaller ! than 8, in which case objects of type Long_Float will be maximally aligned. ! @item Arrays For arrays, the alignment is equal to the alignment of the component type for the normal case where no packing or component size is given. If the array is packed, and the packing is effective (see separate section on --- 8194,8213 ---- values are as follows: @itemize @bullet ! @item @emph{Primitive Types}. ! For primitive types, the alignment is the minimum of the actual size of ! objects of the type divided by @code{Storage_Unit}, ! and the maximum alignment supported by the target. ! (This maximum alignment is given by the GNAT-specific attribute ! @code{Standard'Maximum_Alignment}; see @ref{Maximum_Alignment}.) ! @cindex @code{Maximum_Alignment} attribute ! For example, for type @code{Long_Float}, the object size is 8 bytes, and the default alignment will be 8 on any target that supports alignments this large, but on some targets, the maximum alignment may be smaller ! than 8, in which case objects of type @code{Long_Float} will be maximally aligned. ! @item @emph{Arrays}. For arrays, the alignment is equal to the alignment of the component type for the normal case where no packing or component size is given. If the array is packed, and the packing is effective (see separate section on *************** arrays, which are handled internally as *** 7286,7307 **** will be as described for primitive types, e.g.@: a packed array of length 31 bits will have an object size of four bytes, and an alignment of 4. ! @item Records For the normal non-packed case, the alignment of a record is equal to the maximum alignment of any of its components. For tagged records, this includes the implicit access type used for the tag. If a pragma @code{Pack} is used and all fields are packable (see separate section on pragma @code{Pack}), then the resulting alignment is 1. ! A special case is when the size of the record is given explicitly, or a ! full record representation clause is given, and the size of the record ! is 2, 4, or 8 bytes. In this case, an alignment is chosen to match the size of the record. For example, if we have: ! @smallexample type Small is record A, B : Character; end record; @end smallexample @noindent --- 8217,8246 ---- will be as described for primitive types, e.g.@: a packed array of length 31 bits will have an object size of four bytes, and an alignment of 4. ! @item @emph{Records}. For the normal non-packed case, the alignment of a record is equal to the maximum alignment of any of its components. For tagged records, this includes the implicit access type used for the tag. If a pragma @code{Pack} is used and all fields are packable (see separate section on pragma @code{Pack}), then the resulting alignment is 1. ! A special case is when: ! @itemize @bullet ! @item ! the size of the record is given explicitly, or a ! full record representation clause is given, and ! @item ! the size of the record is 2, 4, or 8 bytes. ! @end itemize ! @noindent ! In this case, an alignment is chosen to match the size of the record. For example, if we have: ! @smallexample @c ada type Small is record A, B : Character; end record; + for Small'Size use 16; @end smallexample @noindent *************** strict alignment. *** 7316,7401 **** An alignment clause may always specify a larger alignment than the default value, up to some maximum value dependent on the target (obtainable by using the ! attribute reference System'Maximum_Alignment). The only case in which it is permissible to specify a smaller alignment than the default value ! is in the case of a record for which a record representation clause is ! given. In this case, packable fields for which a component clause is given still result in a default alignment corresponding to the original type, but this may be overridden, since these components in fact only require an alignment of one byte. For example, given ! @smallexample ! type v is record ! a : integer; end record; ! for v use record ! a at 0 range 0 .. 31; end record; ! for v'alignment use 1; @end smallexample @noindent @cindex Alignment, default ! The default alignment for the type @code{v} is 4, as a result of the ! integer field in the record, but since this field is placed with a component clause, it is permissible, as shown, to override the default ! alignment of the record to a smaller value. @node Size Clauses @section Size Clauses @cindex Size Clause @noindent ! The default size of types is as specified in the reference manual. For ! objects, GNAT will generally increase the type size so that the object ! size is a multiple of storage units, and also a multiple of the ! alignment. For example ! @smallexample type Smallint is range 1 .. 6; type Rec is record ! y1 : integer; ! y2 : boolean; end record; @end smallexample @noindent ! In this example, @code{Smallint} ! has a size of 3, as specified by the RM rules, ! but objects of this type will have a size of 8, since objects by default occupy an integral number of storage units. On some targets, notably older versions of the Digital Alpha, the size of stand alone objects of this type may be 32, reflecting the inability of the hardware to do byte load/stores. ! Similarly, the size of type @code{Rec} is 40 bits, but the alignment is 4, so objects of this type will have their size increased to 64 bits so that it is a multiple ! of the alignment. The reason for this decision, which is ! in accordance with the specific note in RM 13.3(43): ! @smallexample ! A Size clause should be supported for an object if the specified ! Size is at least as large as its subtype's Size, and corresponds to a size in storage elements that is a multiple of the object's ! Alignment (if the Alignment is nonzero). ! @end smallexample @noindent An explicit size clause may be used to override the default size by increasing it. For example, if we have: ! @smallexample type My_Boolean is new Boolean; for My_Boolean'Size use 32; @end smallexample @noindent ! then objects of this type will always be 32 bits long. In the case of discrete types, the size can be increased up to 64 bits, with the effect that the entire specified field is used to hold the value, sign- or zero-extended as appropriate. If more than 64 bits is specified, then --- 8255,8347 ---- An alignment clause may always specify a larger alignment than the default value, up to some maximum value dependent on the target (obtainable by using the ! attribute reference @code{Standard'Maximum_Alignment}). ! The only case where it is permissible to specify a smaller alignment than the default value ! is for a record with a record representation clause. ! In this case, packable fields for which a component clause is given still result in a default alignment corresponding to the original type, but this may be overridden, since these components in fact only require an alignment of one byte. For example, given ! @smallexample @c ada ! type V is record ! A : Integer; end record; ! for V use record ! A at 0 range 0 .. 31; end record; ! for V'alignment use 1; @end smallexample @noindent @cindex Alignment, default ! The default alignment for the type @code{V} is 4, as a result of the ! Integer field in the record, but since this field is placed with a component clause, it is permissible, as shown, to override the default ! alignment of the record with a smaller value. @node Size Clauses @section Size Clauses @cindex Size Clause @noindent ! The default size for a type @code{T} is obtainable through the ! language-defined attribute @code{T'Size} and also through the ! equivalent GNAT-defined attribute @code{T'Value_Size}. ! For objects of type @code{T}, GNAT will generally increase the type size ! so that the object size (obtainable through the GNAT-defined attribute ! @code{T'Object_Size}) ! is a multiple of @code{T'Alignment * Storage_Unit}. ! For example ! @smallexample @c ada type Smallint is range 1 .. 6; type Rec is record ! Y1 : integer; ! Y2 : boolean; end record; @end smallexample @noindent ! In this example, @code{Smallint'Size} = @code{Smallint'Value_Size} = 3, ! as specified by the RM rules, ! but objects of this type will have a size of 8 ! (@code{Smallint'Object_Size} = 8), since objects by default occupy an integral number of storage units. On some targets, notably older versions of the Digital Alpha, the size of stand alone objects of this type may be 32, reflecting the inability of the hardware to do byte load/stores. ! Similarly, the size of type @code{Rec} is 40 bits ! (@code{Rec'Size} = @code{Rec'Value_Size} = 40), but the alignment is 4, so objects of this type will have their size increased to 64 bits so that it is a multiple ! of the alignment (in bits). The reason for this decision, which is ! in accordance with the specific Implementation Advice in RM 13.3(43): ! @quotation ! A @code{Size} clause should be supported for an object if the specified ! @code{Size} is at least as large as its subtype's @code{Size}, and corresponds to a size in storage elements that is a multiple of the object's ! @code{Alignment} (if the @code{Alignment} is nonzero). ! @end quotation @noindent An explicit size clause may be used to override the default size by increasing it. For example, if we have: ! @smallexample @c ada type My_Boolean is new Boolean; for My_Boolean'Size use 32; @end smallexample @noindent ! then values of this type will always be 32 bits long. In the case of discrete types, the size can be increased up to 64 bits, with the effect that the entire specified field is used to hold the value, sign- or zero-extended as appropriate. If more than 64 bits is specified, then *************** Similarly the size of records and arrays *** 7406,7412 **** is to add padding bits after the value. This also causes a warning message to be generated. ! The largest Size value permitted in GNAT is 2**32@minus{}1. Since this is a Size in bits, this corresponds to an object of size 256 megabytes (minus one). This limitation is true on all targets. The reason for this limitation is that it improves the quality of the code in many cases --- 8352,8358 ---- is to add padding bits after the value. This also causes a warning message to be generated. ! The largest Size value permitted in GNAT is 2**31@minus{}1. Since this is a Size in bits, this corresponds to an object of size 256 megabytes (minus one). This limitation is true on all targets. The reason for this limitation is that it improves the quality of the code in many cases *************** type Integer. *** 7420,7439 **** @noindent For tasks, the @code{Storage_Size} clause specifies the amount of space to be allocated for the task stack. This cannot be extended, and if the ! stack is exhausted, then @code{Storage_Error} will be raised if stack ! checking is enabled. If the default size of 20K bytes is insufficient, then you need to use a @code{Storage_Size} attribute definition clause, or a @code{Storage_Size} pragma in the task definition to set the appropriate required size. A useful technique is to include in every task definition a pragma of the form: ! @smallexample pragma Storage_Size (Default_Stack_Size); @end smallexample @noindent ! Then Default_Stack_Size can be defined in a global package, and modified ! as required. Any tasks requiring different task stack sizes from the default can have an appropriate alternative reference in the pragma. For access types, the @code{Storage_Size} clause specifies the maximum --- 8366,8385 ---- @noindent For tasks, the @code{Storage_Size} clause specifies the amount of space to be allocated for the task stack. This cannot be extended, and if the ! stack is exhausted, then @code{Storage_Error} will be raised (if stack ! checking is enabled). If the default size of 20K bytes is insufficient, then you need to use a @code{Storage_Size} attribute definition clause, or a @code{Storage_Size} pragma in the task definition to set the appropriate required size. A useful technique is to include in every task definition a pragma of the form: ! @smallexample @c ada pragma Storage_Size (Default_Stack_Size); @end smallexample @noindent ! Then @code{Default_Stack_Size} can be defined in a global package, and ! modified as required. Any tasks requiring stack sizes different from the default can have an appropriate alternative reference in the pragma. For access types, the @code{Storage_Size} clause specifies the maximum *************** items can be allocated from the pool, an *** 7451,7470 **** time, and all the overhead normally associated with maintaining a fixed size storage pool is eliminated. Consider the following example: ! @smallexample procedure p is type R is array (Natural) of Character; type P is access all R; for P'Storage_Size use 0; -- Above access type intended only for interfacing purposes ! y : P; ! procedure g (m : P); pragma Import (C, g); ! -- @dots{} ! begin -- @dots{} y := new R; --- 8397,8416 ---- time, and all the overhead normally associated with maintaining a fixed size storage pool is eliminated. Consider the following example: ! @smallexample @c ada procedure p is type R is array (Natural) of Character; type P is access all R; for P'Storage_Size use 0; -- Above access type intended only for interfacing purposes ! y : P; ! procedure g (m : P); pragma Import (C, g); ! -- @dots{} ! begin -- @dots{} y := new R; *************** case of such an access declaration. *** 7491,7501 **** @cindex Variant record objects, size @noindent ! An issue arises in the case of variant record objects of whether Size gives information about a particular variant, or the maximum size required for any variant. Consider the following program ! @smallexample with Text_IO; use Text_IO; procedure q is type R1 (A : Boolean := False) is record --- 8437,8447 ---- @cindex Variant record objects, size @noindent ! In the case of variant record objects, there is a question whether Size gives information about a particular variant, or the maximum size required for any variant. Consider the following program ! @smallexample @c ada with Text_IO; use Text_IO; procedure q is type R1 (A : Boolean := False) is record *************** procedure q is *** 7504,7510 **** when False => null; end case; end record; ! V1 : R1 (False); V2 : R1; --- 8450,8456 ---- when False => null; end case; end record; ! V1 : R1 (False); V2 : R1; *************** is actually allocated for the actual). *** 7552,7558 **** Consider the following modified version of the above program: ! @smallexample with Text_IO; use Text_IO; procedure q is type R1 (A : Boolean := False) is record --- 8498,8504 ---- Consider the following modified version of the above program: ! @smallexample @c ada with Text_IO; use Text_IO; procedure q is type R1 (A : Boolean := False) is record *************** procedure q is *** 7561,7567 **** when False => null; end case; end record; ! V2 : R1; function Size (V : R1) return Integer is --- 8507,8513 ---- when False => null; end case; end record; ! V2 : R1; function Size (V : R1) return Integer is *************** represent successive values of the type. *** 7608,7614 **** For example, suppose we have the declaration: ! @smallexample type Small is range -7 .. -4; for Small'Size use 2; @end smallexample --- 8554,8560 ---- For example, suppose we have the declaration: ! @smallexample @c ada type Small is range -7 .. -4; for Small'Size use 2; @end smallexample *************** scheme: *** 7628,7634 **** @noindent Biased representation is only used if the specified @code{Size} clause cannot be accepted in any other manner. These reduced sizes that force ! biased representation can be used for all discrete types except for enumeration types for which a representation clause is given. @node Value_Size and Object_Size Clauses --- 8574,8580 ---- @noindent Biased representation is only used if the specified @code{Size} clause cannot be accepted in any other manner. These reduced sizes that force ! biased representation can be used for all discrete types except for enumeration types for which a representation clause is given. @node Value_Size and Object_Size Clauses *************** enumeration types for which a representa *** 7638,7661 **** @cindex Size, of objects @noindent ! In Ada 95, the @code{Size} of a discrete type is the minimum number of bits ! required to hold values of the type. Although this interpretation was allowed in Ada 83, it was not required, and this requirement in practice can cause some significant difficulties. For example, in most Ada 83 ! compilers, @code{Natural'Size} was 32. However, in Ada-95, @code{Natural'Size} is typically 31. This means that code may change in behavior when moving from Ada 83 to Ada 95. For example, consider: ! @smallexample type Rec is record; A : Natural; B : Natural; end record; for Rec use record ! for A use at 0 range 0 .. Natural'Size - 1; ! for B use at 0 range Natural'Size .. 2 * Natural'Size - 1; end record; @end smallexample --- 8584,8607 ---- @cindex Size, of objects @noindent ! In Ada 95, @code{T'Size} for a type @code{T} is the minimum number of bits ! required to hold values of type @code{T}. Although this interpretation was allowed in Ada 83, it was not required, and this requirement in practice can cause some significant difficulties. For example, in most Ada 83 ! compilers, @code{Natural'Size} was 32. However, in Ada 95, @code{Natural'Size} is typically 31. This means that code may change in behavior when moving from Ada 83 to Ada 95. For example, consider: ! @smallexample @c ada type Rec is record; A : Natural; B : Natural; end record; for Rec use record ! at 0 range 0 .. Natural'Size - 1; ! at 0 range Natural'Size .. 2 * Natural'Size - 1; end record; @end smallexample *************** from Ada 83 to Ada 95. For example, con *** 7663,7673 **** In the above code, since the typical size of @code{Natural} objects is 32 bits and @code{Natural'Size} is 31, the above code can cause unexpected inefficient packing in Ada 95, and in general there are ! surprising cases where the fact that the object size can exceed the size of the type causes surprises. To help get around this problem GNAT provides two implementation ! dependent attributes @code{Value_Size} and @code{Object_Size}. When applied to a type, these attributes yield the size of the type (corresponding to the RM defined size attribute), and the size of objects of the type respectively. --- 8609,8619 ---- In the above code, since the typical size of @code{Natural} objects is 32 bits and @code{Natural'Size} is 31, the above code can cause unexpected inefficient packing in Ada 95, and in general there are ! cases where the fact that the object size can exceed the size of the type causes surprises. To help get around this problem GNAT provides two implementation ! defined attributes, @code{Value_Size} and @code{Object_Size}. When applied to a type, these attributes yield the size of the type (corresponding to the RM defined size attribute), and the size of objects of the type respectively. *************** pad this up if necessary for efficiency, *** 7680,7694 **** character might be stored in 32 bits on a machine with no efficient byte access instructions such as the Alpha. ! The default rules for the value of @code{Object_Size} for fixed-point and discrete types are as follows: @itemize @bullet @item The @code{Object_Size} for base subtypes reflect the natural hardware ! size in bits (run the utility @code{gnatpsta} to find those values for numeric types). ! Enumeration types and fixed-point base subtypes have 8, 16, 32 or 64 ! bits for this size, depending on the range of values to be stored. @item The @code{Object_Size} of a subtype is the same as the --- 8626,8641 ---- character might be stored in 32 bits on a machine with no efficient byte access instructions such as the Alpha. ! The default rules for the value of @code{Object_Size} for discrete types are as follows: @itemize @bullet @item The @code{Object_Size} for base subtypes reflect the natural hardware ! size in bits (run the utility @code{gnatpsta} to find those values for ! numeric types). Enumeration types and fixed-point base subtypes have ! 8, 16, 32 or 64 bits for this size, depending on the range of values ! to be stored. @item The @code{Object_Size} of a subtype is the same as the *************** from the parent first subtype. *** 7703,7711 **** @noindent The @code{Value_Size} attribute ! is the number of bits required to store a value ! of the type. This size can be referred to using the @code{Value_Size} ! attribute. This value is used to determine how tightly to pack records or arrays with components of this type, and also affects the semantics of unchecked conversion (unchecked conversions where the @code{Value_Size} values differ generate a warning, and are potentially --- 8650,8658 ---- @noindent The @code{Value_Size} attribute ! is the (minimum) number of bits required to store a value ! of the type. ! This value is used to determine how tightly to pack records or arrays with components of this type, and also affects the semantics of unchecked conversion (unchecked conversions where the @code{Value_Size} values differ generate a warning, and are potentially *************** reference aliased objects whose subtypes *** 7754,7766 **** values as a result of explicit attribute definition clauses, then it is erroneous to convert from one access subtype to the other. ! At the implementation level, Esize stores the Object_SIze and the RM_Size field stores the @code{Value_Size} (and hence the value of the @code{Size} attribute, which, as noted above, is equivalent to @code{Value_Size}). To get a feel for the difference, consider the following examples (note ! that in each case the base is short_short_integer with a size of 8): @smallexample Object_Size Value_Size --- 8701,8713 ---- values as a result of explicit attribute definition clauses, then it is erroneous to convert from one access subtype to the other. ! At the implementation level, Esize stores the Object_Size and the RM_Size field stores the @code{Value_Size} (and hence the value of the @code{Size} attribute, which, as noted above, is equivalent to @code{Value_Size}). To get a feel for the difference, consider the following examples (note ! that in each case the base is @code{Short_Short_Integer} with a size of 8): @smallexample Object_Size Value_Size *************** that in each case the base is short_shor *** 7768,7789 **** type x1 is range 0 .. 5; 8 3 type x2 is range 0 .. 5; ! for x2'size use 12; 12 12 ! subtype x3 is x2 range 0 .. 3; 12 2 subtype x4 is x2'base range 0 .. 10; 8 4 ! subtype x5 is x2 range 0 .. dynamic; 12 (7) ! subtype x6 is x2'base range 0 .. dynamic; 8 (7) @end smallexample @noindent ! Note: the entries marked (7) are not actually specified by the Ada 95 RM, but it seems in the spirit of the RM rules to allocate the minimum number ! of bits known to be large enough to hold the given range of values. So far, so good, but GNAT has to obey the RM rules, so the question is under what conditions must the RM @code{Size} be used. --- 8715,8737 ---- type x1 is range 0 .. 5; 8 3 type x2 is range 0 .. 5; ! for x2'size use 12; 16 12 ! subtype x3 is x2 range 0 .. 3; 16 2 subtype x4 is x2'base range 0 .. 10; 8 4 ! subtype x5 is x2 range 0 .. dynamic; 16 3* ! subtype x6 is x2'base range 0 .. dynamic; 8 3* @end smallexample @noindent ! Note: the entries marked ``3*'' are not actually specified by the Ada 95 RM, but it seems in the spirit of the RM rules to allocate the minimum number ! of bits (here 3, given the range for @code{x2}) ! known to be large enough to hold the given range of values. So far, so good, but GNAT has to obey the RM rules, so the question is under what conditions must the RM @code{Size} be used. *************** Warning about sizes not matching for unc *** 7802,7808 **** @end itemize @noindent ! For types other than discrete and fixed-point types, the @code{Object_Size} and Value_Size are the same (and equivalent to the RM attribute @code{Size}). Only @code{Size} may be specified for such types. --- 8750,8778 ---- @end itemize @noindent ! For record types, the @code{Object_Size} is always a multiple of the ! alignment of the type (this is true for all types). In some cases the ! @code{Value_Size} can be smaller. Consider: ! ! @smallexample ! type R is record ! X : Integer; ! Y : Character; ! end record; ! @end smallexample ! ! @noindent ! On a typical 32-bit architecture, the X component will be four bytes, and ! require four-byte alignment, and the Y component will be one byte. In this ! case @code{R'Value_Size} will be 40 (bits) since this is the minimum size ! required to store a value of this type, and for example, it is permissible ! to have a component of type R in an outer record whose component size is ! specified to be 48 bits. However, @code{R'Object_Size} will be 64 (bits), ! since it must be rounded up so that this value is a multiple of the ! alignment (4 bytes = 32 bits). ! ! @noindent ! For all other types, the @code{Object_Size} and Value_Size are the same (and equivalent to the RM attribute @code{Size}). Only @code{Size} may be specified for such types. *************** specified must not be smaller than the S *** 7823,7831 **** accurately honor all packing requests in this range. For example, if we have: ! @smallexample type r is array (1 .. 8) of Natural; ! for r'Size use 31; @end smallexample @noindent --- 8793,8801 ---- accurately honor all packing requests in this range. For example, if we have: ! @smallexample @c ada type r is array (1 .. 8) of Natural; ! for r'Component_Size use 31; @end smallexample @noindent *************** example if we are on a little-endian mac *** 7860,7866 **** being the default, then the following two declarations have exactly the same effect: ! @smallexample type R1 is record A : Boolean; B : Integer range 1 .. 120; --- 8830,8836 ---- being the default, then the following two declarations have exactly the same effect: ! @smallexample @c ada type R1 is record A : Boolean; B : Integer range 1 .. 120; *************** that the @code{Bit_Order} specification *** 7897,7903 **** In particular, the following attempt at getting an endian-independent integer does not work: ! @smallexample type R2 is record A : Integer; end record; --- 8867,8873 ---- In particular, the following attempt at getting an endian-independent integer does not work: ! @smallexample @c ada type R2 is record A : Integer; end record; *************** definition of the effect of defining @co *** 7948,7969 **** non-standard bit order is described in section 15.5.3 of the Ada Reference Manual: ! @smallexample 2 A bit ordering is a method of interpreting the meaning of the storage place attributes. ! @end smallexample @noindent To understand the precise definition of storage place attributes in this context, we visit section 13.5.1 of the manual: ! @smallexample 13 A record_representation_clause (without the mod_clause) specifies the layout. The storage place attributes (see 13.5.2) are taken from the values of the position, first_bit, and last_bit expressions after normalizing those values so that first_bit is less than Storage_Unit. ! @end smallexample @noindent The critical point here is that storage places are taken from --- 8918,8939 ---- non-standard bit order is described in section 15.5.3 of the Ada Reference Manual: ! @quotation 2 A bit ordering is a method of interpreting the meaning of the storage place attributes. ! @end quotation @noindent To understand the precise definition of storage place attributes in this context, we visit section 13.5.1 of the manual: ! @quotation 13 A record_representation_clause (without the mod_clause) specifies the layout. The storage place attributes (see 13.5.2) are taken from the values of the position, first_bit, and last_bit expressions after normalizing those values so that first_bit is less than Storage_Unit. ! @end quotation @noindent The critical point here is that storage places are taken from *************** the values after normalization, not befo *** 7971,7977 **** interpretation applies to normalized values. The interpretation is described in the later part of the 15.5.3 paragraph: ! @smallexample 2 A bit ordering is a method of interpreting the meaning of the storage place attributes. High_Order_First (known in the vernacular as ``big endian'') means that the first bit of a --- 8941,8947 ---- interpretation applies to normalized values. The interpretation is described in the later part of the 15.5.3 paragraph: ! @quotation 2 A bit ordering is a method of interpreting the meaning of the storage place attributes. High_Order_First (known in the vernacular as ``big endian'') means that the first bit of a *************** the sequence of bits that represent a co *** 7980,7986 **** integer value). Low_Order_First (known in the vernacular as ``little endian'') means the opposite: the first bit is the least significant. ! @end smallexample @noindent Note that the numbering is with respect to the bits of a storage --- 8950,8956 ---- integer value). Low_Order_First (known in the vernacular as ``little endian'') means the opposite: the first bit is the least significant. ! @end quotation @noindent Note that the numbering is with respect to the bits of a storage *************** the remaining 7 bits are called V1, V2, *** 7999,8005 **** On a big-endian machine, we can write the following representation clause ! @smallexample type Data is record Master_Control : Bit; Master_V1 : Bit; --- 8969,8975 ---- On a big-endian machine, we can write the following representation clause ! @smallexample @c ada type Data is record Master_Control : Bit; Master_V1 : Bit; *************** On a big-endian machine, we can write th *** 8043,8049 **** Now if we move this to a little endian machine, then the bit ordering within the byte is backwards, so we have to rewrite the record rep clause as: ! @smallexample for Data use record Master_Control at 0 range 7 .. 7; Master_V1 at 0 range 6 .. 6; --- 9013,9019 ---- Now if we move this to a little endian machine, then the bit ordering within the byte is backwards, so we have to rewrite the record rep clause as: ! @smallexample @c ada for Data use record Master_Control at 0 range 7 .. 7; Master_V1 at 0 range 6 .. 6; *************** the byte is backwards, so we have to rew *** 8064,8069 **** --- 9034,9040 ---- end record; @end smallexample + @noindent It is a nuisance to have to rewrite the clause, especially if the code has to be maintained on both machines. However, this is a case that we can handle with the *************** machines, but it is indeed implemented i *** 8073,8079 **** This means that we can simply use the first record clause, together with the declaration ! @smallexample for Data'Bit_Order use High_Order_First; @end smallexample --- 9044,9050 ---- This means that we can simply use the first record clause, together with the declaration ! @smallexample @c ada for Data'Bit_Order use High_Order_First; @end smallexample *************** ends up in, only where it ends up in tha *** 8088,8094 **** To make this clear, let us rewrite the record rep clause of the previous example as: ! @smallexample for Data'Bit_Order use High_Order_First; for Data use record Master_Control at 0 range 0 .. 0; --- 9059,9065 ---- To make this clear, let us rewrite the record rep clause of the previous example as: ! @smallexample @c ada for Data'Bit_Order use High_Order_First; for Data use record Master_Control at 0 range 0 .. 0; *************** example as: *** 8113,8119 **** @noindent This is exactly equivalent to saying (a repeat of the first example): ! @smallexample for Data'Bit_Order use High_Order_First; for Data use record Master_Control at 0 range 0 .. 0; --- 9084,9090 ---- @noindent This is exactly equivalent to saying (a repeat of the first example): ! @smallexample @c ada for Data'Bit_Order use High_Order_First; for Data use record Master_Control at 0 range 0 .. 0; *************** This is exactly equivalent to saying (a *** 8139,8145 **** Why are they equivalent? Well take a specific field, the @code{Slave_V2} field. The storage place attributes are obtained by normalizing the values given so that the @code{First_Bit} value is less than 8. After ! nromalizing the values (0,10,10) we get (1,2,2) which is exactly what we specified in the other case. Now one might expect that the @code{Bit_Order} attribute might affect --- 9110,9116 ---- Why are they equivalent? Well take a specific field, the @code{Slave_V2} field. The storage place attributes are obtained by normalizing the values given so that the @code{First_Bit} value is less than 8. After ! normalizing the values (0,10,10) we get (1,2,2) which is exactly what we specified in the other case. Now one might expect that the @code{Bit_Order} attribute might affect *************** If you do need to control byte ordering *** 8158,8164 **** values must be used. If in our example, the slave byte came first on some machines we might write: ! @smallexample Master_Byte_First constant Boolean := @dots{}; Master_Byte : constant Natural := --- 9129,9135 ---- values must be used. If in our example, the slave byte came first on some machines we might write: ! @smallexample @c ada Master_Byte_First constant Boolean := @dots{}; Master_Byte : constant Natural := *************** following cases: *** 8205,8212 **** @item Any scalar type @item - Any fixed-point type - @item Any type whose size is specified with a size clause @item Any packed array type with a static size --- 9176,9181 ---- *************** For all these cases, if the component su *** 8218,8226 **** component size were specified giving the component subtype size. For example if we have: ! @smallexample type r is range 0 .. 17; ! type ar is array (1 .. 8) of r; pragma Pack (ar); @end smallexample --- 9187,9195 ---- component size were specified giving the component subtype size. For example if we have: ! @smallexample @c ada type r is range 0 .. 17; ! type ar is array (1 .. 8) of r; pragma Pack (ar); @end smallexample *************** of bits. If the length is greater than *** 8246,8268 **** time, then the packed array is represented as an array of bytes, and the length is always a multiple of 8 bits. @node Pragma Pack for Records @section Pragma Pack for Records @cindex Pragma Pack (for records) @noindent ! Pragma @code{Pack} applied to a record will pack the components to reduce wasted ! space from alignment gaps and by reducing the amount of space taken by ! components. We distinguish between package components and non-packable ! components. Components of the following types are considered packable: ! @itemize @bullet @item ! All scalar types are packable. ! ! @item ! All fixed-point types are represented internally as integers, and ! are packable. @item Small packed arrays, whose size does not exceed 64 bits, and where the --- 9215,9290 ---- time, then the packed array is represented as an array of bytes, and the length is always a multiple of 8 bits. + Note that to represent a packed array as a modular type, the alignment must + be suitable for the modular type involved. For example, on typical machines + a 32-bit packed array will be represented by a 32-bit modular integer with + an alignment of four bytes. If you explicitly override the default alignment + with an alignment clause that is too small, the modular representation + cannot be used. For example, consider the following set of declarations: + + @smallexample @c ada + type R is range 1 .. 3; + type S is array (1 .. 31) of R; + for S'Component_Size use 2; + for S'Size use 62; + for S'Alignment use 1; + @end smallexample + + @noindent + If the alignment clause were not present, then a 62-bit modular + representation would be chosen (typically with an alignment of 4 or 8 + bytes depending on the target). But the default alignment is overridden + with the explicit alignment clause. This means that the modular + representation cannot be used, and instead the array of bytes + representation must be used, meaning that the length must be a multiple + of 8. Thus the above set of declarations will result in a diagnostic + rejecting the size clause and noting that the minimum size allowed is 64. + + @cindex Pragma Pack (for type Natural) + @cindex Pragma Pack warning + + One special case that is worth noting occurs when the base type of the + component size is 8/16/32 and the subtype is one bit less. Notably this + occurs with subtype @code{Natural}. Consider: + + @smallexample @c ada + type Arr is array (1 .. 32) of Natural; + pragma Pack (Arr); + @end smallexample + + @noindent + In all commonly used Ada 83 compilers, this pragma Pack would be ignored, + since typically @code{Natural'Size} is 32 in Ada 83, and in any case most + Ada 83 compilers did not attempt 31 bit packing. + + In Ada 95, @code{Natural'Size} is required to be 31. Furthermore, GNAT really + does pack 31-bit subtype to 31 bits. This may result in a substantial + unintended performance penalty when porting legacy Ada 83 code. To help + prevent this, GNAT generates a warning in such cases. If you really want 31 + bit packing in a case like this, you can set the component size explicitly: + + @smallexample @c ada + type Arr is array (1 .. 32) of Natural; + for Arr'Component_Size use 31; + @end smallexample + + @noindent + Here 31-bit packing is achieved as required, and no warning is generated, + since in this case the programmer intention is clear. + @node Pragma Pack for Records @section Pragma Pack for Records @cindex Pragma Pack (for records) @noindent ! Pragma @code{Pack} applied to a record will pack the components to reduce ! wasted space from alignment gaps and by reducing the amount of space ! taken by components. We distinguish between @emph{packable} components and ! @emph{non-packable} components. ! Components of the following types are considered packable: @itemize @bullet @item ! All primitive types are packable. @item Small packed arrays, whose size does not exceed 64 bits, and where the *************** their @code{Size} value, and are packed *** 8277,8288 **** can start on an arbitrary bit boundary. All other types are non-packable, they occupy an integral number of ! storage units, and are placed at a boundary corresponding to their alignment requirements. For example, consider the record ! @smallexample type Rb1 is array (1 .. 13) of Boolean; pragma Pack (rb1); --- 9299,9310 ---- can start on an arbitrary bit boundary. All other types are non-packable, they occupy an integral number of ! storage units, and are placed at a boundary corresponding to their alignment requirements. For example, consider the record ! @smallexample @c ada type Rb1 is array (1 .. 13) of Boolean; pragma Pack (rb1); *************** For example, consider the record *** 8303,8309 **** @noindent The representation for the record x2 is as follows: ! @smallexample for x2'Size use 224; for x2 use record l1 at 0 range 0 .. 0; --- 9325,9331 ---- @noindent The representation for the record x2 is as follows: ! @smallexample @c ada for x2'Size use 224; for x2 use record l1 at 0 range 0 .. 0; *************** and @code{l2} are *** 8321,8327 **** of length equal to their sizes, and placed at specific bit boundaries (and not byte boundaries) to eliminate padding. But @code{l3} is of a non-packable float type, so ! it is on the next appropriate alignment boundary. The next two fields are fully packable, so @code{l4} and @code{l5} are minimally packed with no gaps. However, type @code{Rb2} is a packed --- 9343,9349 ---- of length equal to their sizes, and placed at specific bit boundaries (and not byte boundaries) to eliminate padding. But @code{l3} is of a non-packable float type, so ! it is on the next appropriate alignment boundary. The next two fields are fully packable, so @code{l4} and @code{l5} are minimally packed with no gaps. However, type @code{Rb2} is a packed *************** Packed arrays with a size up to and incl *** 8349,8355 **** internally using a modular type with the appropriate number of bits, and thus the same lack of restriction applies. For example, if you declare: ! @smallexample type R is array (1 .. 49) of Boolean; pragma Pack (R); for R'Size use 49; --- 9371,9377 ---- internally using a modular type with the appropriate number of bits, and thus the same lack of restriction applies. For example, if you declare: ! @smallexample @c ada type R is array (1 .. 49) of Boolean; pragma Pack (R); for R'Size use 49; *************** thus the same lack of restriction applie *** 8359,8369 **** --- 9381,9419 ---- then a component clause for a component of type R may start on any specified bit boundary, and may specify a value of 49 bits or greater. + The rules for other types are different for GNAT 3 and GNAT 5 versions + (based on GCC 2 and GCC 3 respectively). In GNAT 5, larger components + may also be placed on arbitrary boundaries, so for example, the following + is permitted: + + @smallexample @c ada + type R is array (1 .. 79) of Boolean; + pragma Pack (R); + for R'Size use 79; + + type Q is record + G, H : Boolean; + L, M : R; + end record; + + for Q use record + G at 0 range 0 .. 0; + H at 0 range 1 .. 1; + L at 0 range 2 .. 80; + R at 0 range 81 .. 159; + end record; + @end smallexample + + @noindent + In GNAT 3, there are more severe restrictions on larger components. For non-primitive types, including packed arrays with a size greater than 64 bits, component clauses must respect the alignment requirement of the type, in particular, always starting on a byte boundary, and the length must be a multiple of the storage unit. + The following rules regarding tagged types are enforced in both GNAT 3 and + GNAT 5: + The tag field of a tagged type always occupies an address sized field at the start of the record. No component clause may attempt to overlay this tag. *************** The only restriction on enumeration clau *** 8379,8385 **** must be representable. For the signed case, if one or more of the representation values are negative, all values must be in the range: ! @smallexample System.Min_Int .. System.Max_Int @end smallexample --- 9429,9435 ---- must be representable. For the signed case, if one or more of the representation values are negative, all values must be in the range: ! @smallexample @c ada System.Min_Int .. System.Max_Int @end smallexample *************** representation values are negative, all *** 8387,8393 **** For the unsigned case, where all values are non negative, the values must be in the range: ! @smallexample 0 .. System.Max_Binary_Modulus; @end smallexample --- 9437,9443 ---- For the unsigned case, where all values are non negative, the values must be in the range: ! @smallexample @c ada 0 .. System.Max_Binary_Modulus; @end smallexample *************** If an array has an index type which is a *** 8403,8409 **** enumeration clause has been applied, then the array is stored in a compact manner. Consider the declarations: ! @smallexample type r is (A, B, C); for r use (A => 1, B => 5, C => 10); type t is array (r) of Character; --- 9453,9459 ---- enumeration clause has been applied, then the array is stored in a compact manner. Consider the declarations: ! @smallexample @c ada type r is (A, B, C); for r use (A => 1, B => 5, C => 10); type t is array (r) of Character; *************** positional values, (i.e.@: the value del *** 8423,8445 **** The reference manual allows a general restriction on representation clauses, as found in RM 13.1(22): ! @smallexample ! An implementation need not support representation ! items containing nonstatic expressions, except that ! an implementation should support a representation item ! for a given entity if each nonstatic expression in the ! representation item is a name that statically denotes ! a constant declared before the entity. ! @end smallexample @noindent In practice this is applicable only to address clauses, since this is the only case in which a non-static expression is permitted by the syntax. As the AARM notes in sections 13.1 (22.a-22.h): ! @smallexample ! 22.a Reason: This is to avoid the following sort ! of thing: 22.b X : Integer := F(@dots{}); Y : Address := G(@dots{}); --- 9473,9494 ---- The reference manual allows a general restriction on representation clauses, as found in RM 13.1(22): ! @quotation ! An implementation need not support representation ! items containing nonstatic expressions, except that ! an implementation should support a representation item ! for a given entity if each nonstatic expression in the ! representation item is a name that statically denotes ! a constant declared before the entity. ! @end quotation @noindent In practice this is applicable only to address clauses, since this is the only case in which a non-static expression is permitted by the syntax. As the AARM notes in sections 13.1 (22.a-22.h): ! @display ! 22.a Reason: This is to avoid the following sort of thing: 22.b X : Integer := F(@dots{}); Y : Address := G(@dots{}); *************** the AARM notes in sections 13.1 (22.a-22 *** 8467,8473 **** Address are hardly ever static, but their value might be known at compile time anyway in many cases. ! @end smallexample @noindent GNAT does indeed permit many additional cases of non-static expressions. In --- 9516,9522 ---- Address are hardly ever static, but their value might be known at compile time anyway in many cases. ! @end display @noindent GNAT does indeed permit many additional cases of non-static expressions. In *************** The type of the item is non-elementary ( *** 8484,8501 **** @item There is explicit or implicit initialization required for the object. @item The address value is non-static. Here GNAT is more permissive than the RM, and allows the address value to be the address of a previously declared stand-alone variable, as long as it does not itself have an address clause. ! @smallexample ! Anchor : Some_Initialized_Type; Overlay : Some_Initialized_Type; for Overlay'Address use Anchor'Address; @end smallexample However, the prefix of the address clause cannot be an array component, or a component of a discriminated record. --- 9533,9554 ---- @item There is explicit or implicit initialization required for the object. + Note that access values are always implicitly initialized, and also + in GNAT, certain bit-packed arrays (those having a dynamic length or + a length greater than 64) will also be implicitly initialized to zero. @item The address value is non-static. Here GNAT is more permissive than the RM, and allows the address value to be the address of a previously declared stand-alone variable, as long as it does not itself have an address clause. ! @smallexample @c ada ! Anchor : Some_Initialized_Type; Overlay : Some_Initialized_Type; for Overlay'Address use Anchor'Address; @end smallexample + @noindent However, the prefix of the address clause cannot be an array component, or a component of a discriminated record. *************** a component of a discriminated record. *** 8505,8530 **** As noted above in section 22.h, address values are typically non-static. In particular the To_Address function, even if applied to a literal value, is a non-static function call. To avoid this minor annoyance, GNAT provides ! the implementation defined attribute 'To_Address. The following two expressions have identical values: - Another issue with address clauses is the interaction with alignment - requirements. When an address clause is given for an object, the address - value must be consistent with the alignment of the object (which is usually - the same as the alignment of the type of the object). If an address clause - is given that specifies an inappropriately aligned address value, then the - program execution is erroneous. - - Since this source of erroneous behavior can have unfortunate effects, GNAT - checks (at compile time if possible, generating a warning, or at execution - time with a run-time check) that the alignment is appropriate. If the - run-time check fails, then @code{Program_Error} is raised. This run-time - check is suppressed if range checks are suppressed, or if - @code{pragma Restrictions (No_Elaboration_Code)} is in effect. - @findex Attribute @findex To_Address ! @smallexample To_Address (16#1234_0000#) System'To_Address (16#1234_0000#); @end smallexample --- 9558,9569 ---- As noted above in section 22.h, address values are typically non-static. In particular the To_Address function, even if applied to a literal value, is a non-static function call. To avoid this minor annoyance, GNAT provides ! the implementation defined attribute 'To_Address. The following two expressions have identical values: @findex Attribute @findex To_Address ! @smallexample @c ada To_Address (16#1234_0000#) System'To_Address (16#1234_0000#); @end smallexample *************** thus when used as an address clause valu *** 8537,8549 **** Additionally, GNAT treats as static an address clause that is an unchecked_conversion of a static integer value. This simplifies the porting of legacy code, and provides a portable equivalent to the GNAT attribute ! To_Address. @findex Export An address clause cannot be given for an exported object. More understandably the real restriction is that objects with an address clause cannot be exported. This is because such variables are not ! defined by the Ada program, so there is no external object so export. @findex Import It is permissible to give an address clause and a pragma Import for the --- 9576,9602 ---- Additionally, GNAT treats as static an address clause that is an unchecked_conversion of a static integer value. This simplifies the porting of legacy code, and provides a portable equivalent to the GNAT attribute ! @code{To_Address}. ! ! Another issue with address clauses is the interaction with alignment ! requirements. When an address clause is given for an object, the address ! value must be consistent with the alignment of the object (which is usually ! the same as the alignment of the type of the object). If an address clause ! is given that specifies an inappropriately aligned address value, then the ! program execution is erroneous. ! ! Since this source of erroneous behavior can have unfortunate effects, GNAT ! checks (at compile time if possible, generating a warning, or at execution ! time with a run-time check) that the alignment is appropriate. If the ! run-time check fails, then @code{Program_Error} is raised. This run-time ! check is suppressed if range checks are suppressed, or if ! @code{pragma Restrictions (No_Elaboration_Code)} is in effect. @findex Export An address clause cannot be given for an exported object. More understandably the real restriction is that objects with an address clause cannot be exported. This is because such variables are not ! defined by the Ada program, so there is no external object to export. @findex Import It is permissible to give an address clause and a pragma Import for the *************** programmer wants, so GNAT will output a *** 8565,8571 **** type R is record M : Integer := 0; end record; ! Ext : R; for Ext'Address use System'To_Address (16#1234_1234#); | --- 9618,9624 ---- type R is record M : Integer := 0; end record; ! Ext : R; for Ext'Address use System'To_Address (16#1234_1234#); | *************** programmer wants, so GNAT will output a *** 8573,8579 **** modify overlaid storage >>> warning: use pragma Import for "Ext" to suppress initialization (RM B(24)) ! end G; @end smallexample --- 9626,9632 ---- modify overlaid storage >>> warning: use pragma Import for "Ext" to suppress initialization (RM B(24)) ! end G; @end smallexample *************** Import to suppress this initialization. *** 8583,8601 **** object is declared and initialized elsewhere. The following package compiles without warnings (and the initialization is suppressed): ! @smallexample with System; package G is type R is record M : Integer := 0; end record; ! Ext : R; for Ext'Address use System'To_Address (16#1234_1234#); pragma Import (Ada, Ext); end G; @end smallexample @node Effect of Convention on Representation @section Effect of Convention on Representation @cindex Convention, effect on representation --- 9636,9699 ---- object is declared and initialized elsewhere. The following package compiles without warnings (and the initialization is suppressed): ! @smallexample @c ada with System; package G is type R is record M : Integer := 0; end record; ! Ext : R; for Ext'Address use System'To_Address (16#1234_1234#); pragma Import (Ada, Ext); end G; @end smallexample + @noindent + A final issue with address clauses involves their use for overlaying + variables, as in the following example: + @cindex Overlaying of objects + + @smallexample @c ada + A : Integer; + B : Integer; + for B'Address use A'Address; + @end smallexample + + @noindent + or alternatively, using the form recommended by the RM: + + @smallexample @c ada + A : Integer; + Addr : constant Address := A'Address; + B : Integer; + for B'Address use Addr; + @end smallexample + + @noindent + In both of these cases, @code{A} + and @code{B} become aliased to one another via the + address clause. This use of address clauses to overlay + variables, achieving an effect similar to unchecked + conversion was erroneous in Ada 83, but in Ada 95 + the effect is implementation defined. Furthermore, the + Ada 95 RM specifically recommends that in a situation + like this, @code{B} should be subject to the following + implementation advice (RM 13.3(19)): + + @quotation + 19 If the Address of an object is specified, or it is imported + or exported, then the implementation should not perform + optimizations based on assumptions of no aliases. + @end quotation + + @noindent + GNAT follows this recommendation, and goes further by also applying + this recommendation to the overlaid variable (@code{A} + in the above example) in this case. This means that the overlay + works "as expected", in that a modification to one of the variables + will affect the value of the other. + @node Effect of Convention on Representation @section Effect of Convention on Representation @cindex Convention, effect on representation *************** GNAT normally stores enumeration types i *** 8623,8629 **** to accommodate all values of the type. For example, for the enumeration type declared by: ! @smallexample type Color is (Red, Green, Blue); @end smallexample --- 9721,9727 ---- to accommodate all values of the type. For example, for the enumeration type declared by: ! @smallexample @c ada type Color is (Red, Green, Blue); @end smallexample *************** value represents true). *** 8647,8653 **** To accommodate the Fortran and C conventions, if a pragma Convention specifies C or Fortran convention for a derived Boolean, as in the following example: ! @smallexample type C_Switch is new Boolean; pragma Convention (C, C_Switch); @end smallexample --- 9745,9751 ---- To accommodate the Fortran and C conventions, if a pragma Convention specifies C or Fortran convention for a derived Boolean, as in the following example: ! @smallexample @c ada type C_Switch is new Boolean; pragma Convention (C, C_Switch); @end smallexample *************** often easier to simply experiment to see *** 8670,8690 **** effect is on the layout of types and objects. As required by the Ada RM, if a representation clause is not accepted, then ! it must be rejected as illegal by the compiler. However, when a representation ! clause or pragma is accepted, there can still be questions of what the ! compiler actually does. For example, if a partial record representation ! clause specifies the location of some components and not others, then where ! are the non-specified components placed? Or if pragma @code{Pack} is used on a ! record, then exactly where are the resulting fields placed? The section ! on pragma @code{Pack} in this chapter can be used to answer the second question, ! but it is often easier to just see what the compiler does. For this purpose, GNAT provides the option @code{-gnatR}. If you compile with this option, then the compiler will output information on the actual representations chosen, in a format similar to source representation clauses. For example, if we compile the package: ! @smallexample package q is type r (x : boolean) is tagged record case x is --- 9768,9789 ---- effect is on the layout of types and objects. As required by the Ada RM, if a representation clause is not accepted, then ! it must be rejected as illegal by the compiler. However, when a ! representation clause or pragma is accepted, there can still be questions ! of what the compiler actually does. For example, if a partial record ! representation clause specifies the location of some components and not ! others, then where are the non-specified components placed? Or if pragma ! @code{Pack} is used on a record, then exactly where are the resulting ! fields placed? The section on pragma @code{Pack} in this chapter can be ! used to answer the second question, but it is often easier to just see ! what the compiler does. For this purpose, GNAT provides the option @code{-gnatR}. If you compile with this option, then the compiler will output information on the actual representations chosen, in a format similar to source representation clauses. For example, if we compile the package: ! @smallexample @c ada package q is type r (x : boolean) is tagged record case x is *************** support these extended characters. *** 8861,8868 **** @item Ada.Command_Line (A.15) This package provides access to the command line parameters and the name ! of the current program (analogous to the use of @code{argc} and @code{argv} in C), and ! also allows the exit status for the program to be set in a system-independent manner. @item Ada.Decimal (F.2) --- 9960,9967 ---- @item Ada.Command_Line (A.15) This package provides access to the command line parameters and the name ! of the current program (analogous to the use of @code{argc} and @code{argv} ! in C), and also allows the exit status for the program to be set in a system-independent manner. @item Ada.Decimal (F.2) *************** requires the use of dynamic allocation a *** 9041,9047 **** @itemx Ada.Strings.Wide_Maps (A.4.7) @itemx Ada.Strings.Wide_Maps.Constants (A.4.7) @itemx Ada.Strings.Wide_Unbounded (A.4.7) ! These package provide analogous capabilities to the corresponding packages without @samp{Wide_} in the name, but operate with the types @code{Wide_String} and @code{Wide_Character} instead of @code{String} and @code{Character}. --- 10140,10146 ---- @itemx Ada.Strings.Wide_Maps (A.4.7) @itemx Ada.Strings.Wide_Maps.Constants (A.4.7) @itemx Ada.Strings.Wide_Unbounded (A.4.7) ! These packages provide analogous capabilities to the corresponding packages without @samp{Wide_} in the name, but operate with the types @code{Wide_String} and @code{Wide_Character} instead of @code{String} and @code{Character}. *************** package are listed next. *** 9066,9072 **** @item Ada.Text_IO.Decimal_IO Provides input-output facilities for decimal fixed-point types ! @item Ada.Text_IO.Enumeration_IO Provides input-output facilities for enumeration types. @item Ada.Text_IO.Fixed_IO --- 10165,10171 ---- @item Ada.Text_IO.Decimal_IO Provides input-output facilities for decimal fixed-point types ! @item Ada.Text_IO.Enumeration_IO Provides input-output facilities for enumeration types. @item Ada.Text_IO.Fixed_IO *************** This package is similar to @code{Ada.Tex *** 9235,9240 **** --- 10334,10340 ---- types are @code{Wide_Character} and @code{Wide_String} instead of @code{Character} and @code{String}. @end table + @node The Implementation of Standard I/O @chapter The Implementation of Standard I/O *************** of additional child library packages, th *** 9268,9284 **** these additional facilities are also described in this chapter. @menu ! * Standard I/O Packages:: ! * FORM Strings:: ! * Direct_IO:: ! * Sequential_IO:: ! * Text_IO:: ! * Wide_Text_IO:: ! * Stream_IO:: ! * Shared Files:: ! * Open Modes:: ! * Operations on C Streams:: ! * Interfacing to C Streams:: @end menu @node Standard I/O Packages --- 10368,10384 ---- these additional facilities are also described in this chapter. @menu ! * Standard I/O Packages:: ! * FORM Strings:: ! * Direct_IO:: ! * Sequential_IO:: ! * Text_IO:: ! * Wide_Text_IO:: ! * Stream_IO:: ! * Shared Files:: ! * Open Modes:: ! * Operations on C Streams:: ! * Interfacing to C Streams:: @end menu @node Standard I/O Packages *************** All files are opened using @code{fopen}. *** 9319,9324 **** --- 10419,10425 ---- All input/output operations use @code{fread}/@code{fwrite}. @end itemize + @noindent There is no internal buffering of any kind at the Ada library level. The only buffering is that provided at the system level in the implementation of the C library routines that support streams. This *************** SHARED=[YES|NO] *** 9344,9349 **** --- 10445,10451 ---- WCEM=[n|h|u|s\e] @end smallexample + @noindent The use of these parameters is described later in this section. @node Direct_IO *************** The records of a Direct_IO file are simp *** 9359,9365 **** sequence, with the first record starting at offset zero, and subsequent records following. There is no control information of any kind. For example, if 32-bit integers are being written, each record takes ! 4-bytes, so the record at index @var{K} starts at offset (@var{K}@minus{}1)*4. There is no limit on the size of Direct_IO files, they are expanded as --- 10461,10467 ---- sequence, with the first record starting at offset zero, and subsequent records following. There is no control information of any kind. For example, if 32-bit integers are being written, each record takes ! 4-bytes, so the record at index @var{K} starts at offset (@var{K}@minus{}1)*4. There is no limit on the size of Direct_IO files, they are expanded as *************** Note that it is not possible to use Sequ *** 9391,9397 **** length array items, and then read the data back into different length arrays. For example, the following will raise @code{Data_Error}: ! @smallexample package IO is new Sequential_IO (String); F : IO.File_Type; S : String (1..4); --- 10493,10499 ---- length array items, and then read the data back into different length arrays. For example, the following will raise @code{Data_Error}: ! @smallexample @c ada package IO is new Sequential_IO (String); F : IO.File_Type; S : String (1..4); *************** arrays. For example, the following will *** 9404,9412 **** @end smallexample ! On some Ada implementations, this will print @samp{hell}, but the program is clearly incorrect, since there is only one element in the file, and that ! element is the string @samp{hello!}. In Ada 95, this kind of behavior can be legitimately achieved using Stream_IO, and this is the preferred mechanism. In particular, the above --- 10506,10515 ---- @end smallexample ! @noindent ! On some Ada implementations, this will print @code{hell}, but the program is clearly incorrect, since there is only one element in the file, and that ! element is the string @code{hello!}. In Ada 95, this kind of behavior can be legitimately achieved using Stream_IO, and this is the preferred mechanism. In particular, the above *************** LF (line feed, 16#0A#) Line Mark *** 9424,9429 **** --- 10527,10533 ---- FF (form feed, 16#0C#) Page Mark @end smallexample + @noindent A canonical Text_IO file is defined as one in which the following conditions are met: *************** The file ends with either @code{LF} (lin *** 9443,9448 **** --- 10547,10553 ---- assumed to be present. @end itemize + @noindent A file written using Text_IO will be in canonical form provided that no explicit @code{LF} or @code{FF} characters are written using @code{Put} or @code{Put_Line}. There will be no @code{FF} character at the end of *************** The file ends in a character other than *** 9472,9477 **** --- 10577,10583 ---- i.e.@: there is no explicit line mark or page mark at the end of the file. @end itemize + @noindent Text_IO can be used to read such non-standard text files but subprograms to do with line or page numbers do not have defined meanings. In particular, a @code{FF} character that does not follow a @code{LF} *************** to end a line, and there is an implied @ *** 9481,9495 **** the file. @menu ! * Text_IO Stream Pointer Positioning:: ! * Text_IO Reading and Writing Non-Regular Files:: ! * Get_Immediate:: * Treating Text_IO Files as Streams:: * Text_IO Extensions:: * Text_IO Facilities for Unbounded Strings:: @end menu - @node Text_IO Stream Pointer Positioning @subsection Stream Pointer Positioning @noindent --- 10587,10601 ---- the file. @menu ! * Text_IO Stream Pointer Positioning:: ! * Text_IO Reading and Writing Non-Regular Files:: ! * Get_Immediate:: * Treating Text_IO Files as Streams:: * Text_IO Extensions:: * Text_IO Facilities for Unbounded Strings:: @end menu + @node Text_IO Stream Pointer Positioning @subsection Stream Pointer Positioning @noindent *************** maintains internal flags so that subsequ *** 9516,9521 **** --- 10622,10628 ---- handle the logical position. @end itemize + @noindent These discrepancies have no effect on the observable behavior of Text_IO, but if a single Ada stream is shared between a C program and Ada program, or shared (using @samp{shared=yes} in the form string) *************** entered from the pipe to complete one of *** 9555,9560 **** --- 10662,10668 ---- the end of the file. @end itemize + @noindent Output to non-regular files is the same as for regular files. Page marks may be written to non-regular files using @code{New_Page}, but as noted above they will not be treated as page marks on input if the output is *************** Another important discrepancy when readi *** 9564,9570 **** of file indication is not ``sticky''. If an end of file is entered, e.g.@: by pressing the @key{EOT} key, then end of file ! is signalled once (i.e.@: the test @code{End_Of_File} will yield @code{True}, or a read will raise @code{End_Error}), but then reading can resume to read data past that end of --- 10672,10678 ---- of file indication is not ``sticky''. If an end of file is entered, e.g.@: by pressing the @key{EOT} key, then end of file ! is signaled once (i.e.@: the test @code{End_Of_File} will yield @code{True}, or a read will raise @code{End_Error}), but then reading can resume to read data past that end of *************** to the standard @code{Text_IO} package: *** 9610,9617 **** @itemize @bullet @item function File_Exists (Name : String) return Boolean; ! Determines if a file of the given name exists and can be successfully ! opened (without actually performing the open operation). @item function Get_Line return String; Reads a string from the standard input file. The value returned is exactly --- 10718,10724 ---- @itemize @bullet @item function File_Exists (Name : String) return Boolean; ! Determines if a file of the given name exists. @item function Get_Line return String; Reads a string from the standard input file. The value returned is exactly *************** and is optional. If the parameter is om *** 9657,9664 **** output file is referenced as appropriate. The package @code{Ada.Strings.Wide_Unbounded.Wide_Text_IO} in library ! files @file{a-swuwti.ads} and @file{a-swuwti.adb} provides similar extended @code{Wide_Text_IO} ! functionality for unbounded wide strings. @node Wide_Text_IO @section Wide_Text_IO --- 10764,10771 ---- output file is referenced as appropriate. The package @code{Ada.Strings.Wide_Unbounded.Wide_Text_IO} in library ! files @file{a-swuwti.ads} and @file{a-swuwti.adb} provides similar extended ! @code{Wide_Text_IO} functionality for unbounded wide strings. @node Wide_Text_IO @section Wide_Text_IO *************** UTF-8 encoding *** 9692,9697 **** --- 10799,10805 ---- Brackets encoding @end table + @noindent The encoding methods match those that can be used in a source program, but there is no requirement that the encoding method used for *************** sequence: *** 9712,9717 **** --- 10820,10826 ---- ESC a b c d @end smallexample + @noindent where @var{a}, @var{b}, @var{c}, @var{d} are the four hexadecimal characters (using upper case letters) of the wide character code. For example, ESC A345 is used to represent the wide character with code *************** The wide character with encoding 16#abcd *** 9723,9729 **** (i.e.@: a is in the range 8-F) is represented as two bytes 16#ab# and 16#cd#. The second byte may never be a format control character, but is not required to be in the upper half. This method can be also used for ! shift-JIS or EUC where the internal coding matches the external coding. @item Shift JIS Coding A wide character is represented by a two character sequence 16#ab# and --- 10832,10838 ---- (i.e.@: a is in the range 8-F) is represented as two bytes 16#ab# and 16#cd#. The second byte may never be a format control character, but is not required to be in the upper half. This method can be also used for ! shift-JIS or EUC where the internal coding matches the external coding. @item Shift JIS Coding A wide character is represented by a two character sequence 16#ab# and *************** is a one, two, or three byte sequence: *** 9752,9757 **** --- 10861,10867 ---- 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# @end smallexample + @noindent where the xxx bits correspond to the left-padded bits of the 16-bit character value. Note that all lower half ASCII characters are represented as ASCII bytes and all upper half characters and *************** character sequence: *** 9769,9775 **** [ " a b c d " ] @end smallexample ! Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal characters (using uppercase letters) of the wide character code. For example, @code{["A345"]} is used to represent the wide character with code @code{16#A345#}. --- 10879,10886 ---- [ " a b c d " ] @end smallexample ! @noindent ! where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal characters (using uppercase letters) of the wide character code. For example, @code{["A345"]} is used to represent the wide character with code @code{16#A345#}. *************** is only used for wide characters with a *** 9780,9785 **** --- 10891,10897 ---- @end table + @noindent For the coding schemes other than Hex and Brackets encoding, not all wide character values can be represented. An attempt to output a character that cannot *************** Constraint_Error to be raised. An inval *** 9788,9795 **** input also causes Constraint_Error to be raised. @menu ! * Wide_Text_IO Stream Pointer Positioning:: ! * Wide_Text_IO Reading and Writing Non-Regular Files:: @end menu @node Wide_Text_IO Stream Pointer Positioning --- 10900,10907 ---- input also causes Constraint_Error to be raised. @menu ! * Wide_Text_IO Stream Pointer Positioning:: ! * Wide_Text_IO Reading and Writing Non-Regular Files:: @end menu @node Wide_Text_IO Stream Pointer Positioning *************** case: *** 9803,9809 **** If @code{Ada.Wide_Text_IO.Look_Ahead} reads a character outside the normal lower ASCII set (i.e.@: a character in the range: ! @smallexample Wide_Character'Val (16#0080#) .. Wide_Character'Val (16#FFFF#) @end smallexample --- 10915,10921 ---- If @code{Ada.Wide_Text_IO.Look_Ahead} reads a character outside the normal lower ASCII set (i.e.@: a character in the range: ! @smallexample @c ada Wide_Character'Val (16#0080#) .. Wide_Character'Val (16#FFFF#) @end smallexample *************** stream is shared between these files, an *** 9879,9884 **** --- 10991,10997 ---- in Ada 95 Reference Manual, Section A.14. @end itemize + @noindent When a program that opens multiple files with the same name is ported from another Ada compiler to GNAT, the effect will be that @code{Use_Error} is raised. *************** for this purpose (using the stream attri *** 9910,9919 **** @noindent @code{Open} and @code{Create} calls result in a call to @code{fopen} ! using the mode shown in Table 6.1 @sp 2 ! @center Table 6-1 @code{Open} and @code{Create} Call Modes @smallexample @b{OPEN } @b{CREATE} Append_File "r+" "w+" --- 11023,11032 ---- @noindent @code{Open} and @code{Create} calls result in a call to @code{fopen} ! using the mode shown in the following table: @sp 2 ! @center @code{Open} and @code{Create} Call Modes @smallexample @b{OPEN } @b{CREATE} Append_File "r+" "w+" *************** Out_File (all other cases) "w" *** 9923,9928 **** --- 11036,11042 ---- Inout_File "r+" "w+" @end smallexample + @noindent If text file translation is required, then either @samp{b} or @samp{t} is added to the mode, depending on the setting of Text. Text file translation refers to the mapping of CR/LF sequences in an external file *************** then the file is reopened in @samp{r+} m *** 9940,9946 **** The package @code{Interfaces.C_Streams} provides an Ada program with direct access to the C library functions for operations on C streams: ! @smallexample package Interfaces.C_Streams is -- Note: the reason we do not use the types that are in -- Interfaces.C is that we want to avoid dragging in the --- 11054,11060 ---- The package @code{Interfaces.C_Streams} provides an Ada program with direct access to the C library functions for operations on C streams: ! @smallexample @c adanocomment package Interfaces.C_Streams is -- Note: the reason we do not use the types that are in -- Interfaces.C is that we want to avoid dragging in the *************** package Interfaces.C_Streams is *** 9969,9975 **** -- Constants Defined in stdio.h -- ---------------------------------- EOF : constant int; ! -- Used by a number of routines to indicate error or -- end of file IOFBF : constant int; IOLBF : constant int; --- 11083,11089 ---- -- Constants Defined in stdio.h -- ---------------------------------- EOF : constant int; ! -- Used by a number of routines to indicate error or -- end of file IOFBF : constant int; IOLBF : constant int; *************** package Interfaces.C_Streams is *** 9990,10017 **** -- available in DOS, OS/2, UNIX and Xenix (but not -- necessarily in ANSI C). These are very thin interfaces -- which copy exactly the C headers. For more ! -- documentation on these functions, see the Microsoft C -- "Run-Time Library Reference" (Microsoft Press, 1990, -- ISBN 1-55615-225-6), which includes useful information -- on system compatibility. procedure clearerr (stream : FILEs); function fclose (stream : FILEs) return int; ! function fdopen (handle : int; mode : chars) return FILEs; ! function feof (stream : FILEs) return int; ! function ferror (stream : FILEs) return int; ! function fflush (stream : FILEs) return int; ! function fgetc (stream : FILEs) return int; ! function fgets (strng : chars; n : int; stream : FILEs) ! return chars; ! function fileno (stream : FILEs) return int; ! function fopen (filename : chars; Mode : chars) return FILEs; -- Note: to maintain target independence, use -- text_translation_required, a boolean variable defined in -- a-sysdep.c to deal with the target dependent text ! -- translation requirement. If this variable is set, -- then b/t should be appended to the standard mode ! -- argument to set the text translation mode off or on -- as required. function fputc (C : int; stream : FILEs) return int; function fputs (Strng : chars; Stream : FILEs) return int; --- 11104,11131 ---- -- available in DOS, OS/2, UNIX and Xenix (but not -- necessarily in ANSI C). These are very thin interfaces -- which copy exactly the C headers. For more ! -- documentation on these functions, see the Microsoft C -- "Run-Time Library Reference" (Microsoft Press, 1990, -- ISBN 1-55615-225-6), which includes useful information -- on system compatibility. procedure clearerr (stream : FILEs); function fclose (stream : FILEs) return int; ! function fdopen (handle : int; mode : chars) return FILEs; ! function feof (stream : FILEs) return int; ! function ferror (stream : FILEs) return int; ! function fflush (stream : FILEs) return int; ! function fgetc (stream : FILEs) return int; ! function fgets (strng : chars; n : int; stream : FILEs) ! return chars; ! function fileno (stream : FILEs) return int; ! function fopen (filename : chars; Mode : chars) return FILEs; -- Note: to maintain target independence, use -- text_translation_required, a boolean variable defined in -- a-sysdep.c to deal with the target dependent text ! -- translation requirement. If this variable is set, -- then b/t should be appended to the standard mode ! -- argument to set the text translation mode off or on -- as required. function fputc (C : int; stream : FILEs) return int; function fputs (Strng : chars; Stream : FILEs) return int; *************** package Interfaces.C_Streams is *** 10037,10043 **** size : size_t; count : size_t; stream : FILEs) ! return size_t; function isatty (handle : int) return int; procedure mktemp (template : chars); -- The return value (which is just a pointer to template) --- 11151,11157 ---- size : size_t; count : size_t; stream : FILEs) ! return size_t; function isatty (handle : int) return int; procedure mktemp (template : chars); -- The return value (which is just a pointer to template) *************** package Interfaces.C_Streams is *** 10058,10064 **** -- Extra functions -- --------------------- -- These functions supply slightly thicker bindings than ! -- those above. They are derived from functions in the -- C Run-Time Library, but may do a bit more work than -- just directly calling one of the Library functions. function is_regular_file (handle : int) return int; --- 11172,11178 ---- -- Extra functions -- --------------------- -- These functions supply slightly thicker bindings than ! -- those above. They are derived from functions in the -- C Run-Time Library, but may do a bit more work than -- just directly calling one of the Library functions. function is_regular_file (handle : int) return int; *************** package Interfaces.C_Streams is *** 10080,10088 **** procedure full_name (nam : chars; buffer : chars); -- Given a NUL terminated string representing a file -- name, returns in buffer a NUL terminated string ! -- representing the full path name for the file name. -- On systems where it is relevant the drive is also ! -- part of the full path name. It is the responsibility -- of the caller to pass an actual parameter for buffer -- that is big enough for any full path name. Use -- max_path_len given below as the size of buffer. --- 11194,11202 ---- procedure full_name (nam : chars; buffer : chars); -- Given a NUL terminated string representing a file -- name, returns in buffer a NUL terminated string ! -- representing the full path name for the file name. -- On systems where it is relevant the drive is also ! -- part of the full path name. It is the responsibility -- of the caller to pass an actual parameter for buffer -- that is big enough for any full path name. Use -- max_path_len given below as the size of buffer. *************** end Interfaces.C_Streams; *** 10099,10108 **** The packages in this section permit interfacing Ada files to C Stream operations. ! @smallexample with Interfaces.C_Streams; package Ada.Sequential_IO.C_Streams is ! function C_Stream (F : File_Type) return Interfaces.C_Streams.FILEs; procedure Open (File : in out File_Type; --- 11213,11222 ---- The packages in this section permit interfacing Ada files to C Stream operations. ! @smallexample @c ada with Interfaces.C_Streams; package Ada.Sequential_IO.C_Streams is ! function C_Stream (F : File_Type) return Interfaces.C_Streams.FILEs; procedure Open (File : in out File_Type; *************** operations. *** 10113,10119 **** with Interfaces.C_Streams; package Ada.Direct_IO.C_Streams is ! function C_Stream (F : File_Type) return Interfaces.C_Streams.FILEs; procedure Open (File : in out File_Type; --- 11227,11233 ---- with Interfaces.C_Streams; package Ada.Direct_IO.C_Streams is ! function C_Stream (F : File_Type) return Interfaces.C_Streams.FILEs; procedure Open (File : in out File_Type; *************** operations. *** 10135,10141 **** with Interfaces.C_Streams; package Ada.Wide_Text_IO.C_Streams is ! function C_Stream (F : File_Type) return Interfaces.C_Streams.FILEs; procedure Open (File : in out File_Type; --- 11249,11255 ---- with Interfaces.C_Streams; package Ada.Wide_Text_IO.C_Streams is ! function C_Stream (F : File_Type) return Interfaces.C_Streams.FILEs; procedure Open (File : in out File_Type; *************** operations. *** 10156,10161 **** --- 11270,11276 ---- end Ada.Stream_IO.C_Streams; @end smallexample + @noindent In each of these five packages, the @code{C_Stream} function obtains the @code{FILE} pointer from a currently opened Ada file. It is then possible to use the @code{Interfaces.C_Streams} package to operate on *************** The chapter here simply gives a brief su *** 10188,10194 **** The full documentation is found in the spec file for the package. The full sources of these library packages, including both spec and body, are provided with all GNAT releases. For example, to find out the full specifications of ! the SPITBOL pattern matching capability, including a full tutorial and extensive examples, look in the @file{g-spipat.ads} file in the library. For each entry here, the package name (as it would appear in a @code{with} --- 11303,11309 ---- The full documentation is found in the spec file for the package. The full sources of these library packages, including both spec and body, are provided with all GNAT releases. For example, to find out the full specifications of ! the SPITBOL pattern matching capability, including a full tutorial and extensive examples, look in the @file{g-spipat.ads} file in the library. For each entry here, the package name (as it would appear in a @code{with} *************** of GNAT, and will generate a warning mes *** 10211,10225 **** --- 11326,11346 ---- * Ada.Characters.Wide_Latin_1 (a-cwila1.ads):: * Ada.Characters.Wide_Latin_9 (a-cwila9.ads):: * Ada.Command_Line.Remove (a-colire.ads):: + * Ada.Command_Line.Environment (a-colien.ads):: * Ada.Direct_IO.C_Streams (a-diocst.ads):: * Ada.Exceptions.Is_Null_Occurrence (a-einuoc.ads):: + * Ada.Exceptions.Traceback (a-exctra.ads):: * Ada.Sequential_IO.C_Streams (a-siocst.ads):: * Ada.Streams.Stream_IO.C_Streams (a-ssicst.ads):: * Ada.Strings.Unbounded.Text_IO (a-suteio.ads):: * Ada.Strings.Wide_Unbounded.Wide_Text_IO (a-swuwti.ads):: * Ada.Text_IO.C_Streams (a-tiocst.ads):: * Ada.Wide_Text_IO.C_Streams (a-wtcstr.ads):: + * GNAT.Array_Split (g-arrspl.ads):: * GNAT.AWK (g-awk.ads):: + * GNAT.Bounded_Buffers (g-boubuf.ads):: + * GNAT.Bounded_Mailboxes (g-boumai.ads):: + * GNAT.Bubble_Sort (g-bubsor.ads):: * GNAT.Bubble_Sort_A (g-busora.ads):: * GNAT.Bubble_Sort_G (g-busorg.ads):: * GNAT.Calendar (g-calend.ads):: *************** of GNAT, and will generate a warning mes *** 10230,10243 **** --- 11351,11370 ---- * GNAT.CGI.Cookie (g-cgicoo.ads):: * GNAT.CGI.Debug (g-cgideb.ads):: * GNAT.Command_Line (g-comlin.ads):: + * GNAT.Compiler_Version (g-comver.ads):: + * GNAT.Ctrl_C (g-ctrl_c.ads):: * GNAT.Current_Exception (g-curexc.ads):: * GNAT.Debug_Pools (g-debpoo.ads):: * GNAT.Debug_Utilities (g-debuti.ads):: * GNAT.Directory_Operations (g-dirope.ads):: + * GNAT.Dynamic_HTables (g-dynhta.ads):: * GNAT.Dynamic_Tables (g-dyntab.ads):: + * GNAT.Exception_Actions (g-excact.ads):: * GNAT.Exception_Traces (g-exctra.ads):: + * GNAT.Exceptions (g-except.ads):: * GNAT.Expect (g-expect.ads):: * GNAT.Float_Control (g-flocon.ads):: + * GNAT.Heap_Sort (g-heasor.ads):: * GNAT.Heap_Sort_A (g-hesora.ads):: * GNAT.Heap_Sort_G (g-hesorg.ads):: * GNAT.HTable (g-htable.ads):: *************** of GNAT, and will generate a warning mes *** 10245,10255 **** --- 11372,11387 ---- * GNAT.IO_Aux (g-io_aux.ads):: * GNAT.Lock_Files (g-locfil.ads):: * GNAT.MD5 (g-md5.ads):: + * GNAT.Memory_Dump (g-memdum.ads):: * GNAT.Most_Recent_Exception (g-moreex.ads):: * GNAT.OS_Lib (g-os_lib.ads):: + * GNAT.Perfect_Hash.Generators (g-pehage.ads):: * GNAT.Regexp (g-regexp.ads):: * GNAT.Registry (g-regist.ads):: * GNAT.Regpat (g-regpat.ads):: + * GNAT.Secondary_Stack_Info (g-sestin.ads):: + * GNAT.Semaphores (g-semaph.ads):: + * GNAT.Signals (g-signal.ads):: * GNAT.Sockets (g-socket.ads):: * GNAT.Source_Info (g-souinf.ads):: * GNAT.Spell_Checker (g-speche.ads):: *************** of GNAT, and will generate a warning mes *** 10258,10268 **** --- 11390,11403 ---- * GNAT.Spitbol.Table_Boolean (g-sptabo.ads):: * GNAT.Spitbol.Table_Integer (g-sptain.ads):: * GNAT.Spitbol.Table_VString (g-sptavs.ads):: + * GNAT.Strings (g-string.ads):: + * GNAT.String_Split (g-strspl.ads):: * GNAT.Table (g-table.ads):: * GNAT.Task_Lock (g-tasloc.ads):: * GNAT.Threads (g-thread.ads):: * GNAT.Traceback (g-traceb.ads):: * GNAT.Traceback.Symbolic (g-trasym.ads):: + * GNAT.Wide_String_Split (g-wistsp.ads):: * Interfaces.C.Extensions (i-cexten.ads):: * Interfaces.C.Streams (i-cstrea.ads):: * Interfaces.CPP (i-cpp.ads):: *************** of GNAT, and will generate a warning mes *** 10275,10280 **** --- 11410,11416 ---- * Interfaces.VxWorks.IO (i-vxwoio.ads):: * System.Address_Image (s-addima.ads):: * System.Assertions (s-assert.ads):: + * System.Memory (s-memory.ads):: * System.Partition_Interface (s-parint.ads):: * System.Task_Info (s-tasinf.ads):: * System.Wch_Cnv (s-wchcnv.ads):: *************** arguments from the argument list. Once *** 10336,10348 **** to further calls on the subprograms in @code{Ada.Command_Line} will not see the removed argument. @node Ada.Direct_IO.C_Streams (a-diocst.ads) @section @code{Ada.Direct_IO.C_Streams} (@file{a-diocst.ads}) @cindex @code{Ada.Direct_IO.C_Streams} (@file{a-diocst.ads}) @cindex C Streams, Interfacing with Direct_IO @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Direct_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. --- 11472,11494 ---- to further calls on the subprograms in @code{Ada.Command_Line} will not see the removed argument. + @node Ada.Command_Line.Environment (a-colien.ads) + @section @code{Ada.Command_Line.Environment} (@file{a-colien.ads}) + @cindex @code{Ada.Command_Line.Environment} (@file{a-colien.ads}) + @cindex Environment entries + + @noindent + This child of @code{Ada.Command_Line} + provides a mechanism for obtaining environment values on systems + where this concept makes sense. + @node Ada.Direct_IO.C_Streams (a-diocst.ads) @section @code{Ada.Direct_IO.C_Streams} (@file{a-diocst.ads}) @cindex @code{Ada.Direct_IO.C_Streams} (@file{a-diocst.ads}) @cindex C Streams, Interfacing with Direct_IO @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Direct_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. *************** can be constructed from a stream opened *** 10353,10369 **** @cindex Null_Occurrence, testing for @noindent ! This child subprogram provides a way of testing for the null exception occurrence (@code{Null_Occurrence}) without raising an exception. @node Ada.Sequential_IO.C_Streams (a-siocst.ads) @section @code{Ada.Sequential_IO.C_Streams} (@file{a-siocst.ads}) @cindex @code{Ada.Sequential_IO.C_Streams} (@file{a-siocst.ads}) @cindex C Streams, Interfacing with Sequential_IO @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Sequential_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. --- 11499,11525 ---- @cindex Null_Occurrence, testing for @noindent ! This child subprogram provides a way of testing for the null exception occurrence (@code{Null_Occurrence}) without raising an exception. + @node Ada.Exceptions.Traceback (a-exctra.ads) + @section @code{Ada.Exceptions.Traceback} (@file{a-exctra.ads}) + @cindex @code{Ada.Exceptions.Traceback} (@file{a-exctra.ads}) + @cindex Traceback for Exception Occurrence + + @noindent + This child package provides the subprogram (@code{Tracebacks}) to + give a traceback array of addresses based on an exception + occurrence. + @node Ada.Sequential_IO.C_Streams (a-siocst.ads) @section @code{Ada.Sequential_IO.C_Streams} (@file{a-siocst.ads}) @cindex @code{Ada.Sequential_IO.C_Streams} (@file{a-siocst.ads}) @cindex C Streams, Interfacing with Sequential_IO @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Sequential_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. *************** can be constructed from a stream opened *** 10374,10380 **** @cindex C Streams, Interfacing with Stream_IO @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Stream_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. --- 11530,11536 ---- @cindex C Streams, Interfacing with Stream_IO @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Stream_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. *************** with ordinary wide strings. *** 10407,10413 **** @cindex C Streams, Interfacing with @code{Text_IO} @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Text_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. --- 11563,11569 ---- @cindex C Streams, Interfacing with @code{Text_IO} @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Text_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. *************** can be constructed from a stream opened *** 10418,10428 **** @cindex C Streams, Interfacing with @code{Wide_Text_IO} @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Wide_Text_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. @node GNAT.AWK (g-awk.ads) @section @code{GNAT.AWK} (@file{g-awk.ads}) @cindex @code{GNAT.AWK} (@file{g-awk.ads}) --- 11574,11594 ---- @cindex C Streams, Interfacing with @code{Wide_Text_IO} @noindent ! This package provides subprograms that allow interfacing between C streams and @code{Wide_Text_IO}. The stream identifier can be extracted from a file opened on the Ada side, and an Ada file can be constructed from a stream opened on the C side. + @node GNAT.Array_Split (g-arrspl.ads) + @section @code{GNAT.Array_Split} (@file{g-arrspl.ads}) + @cindex @code{GNAT.Array_Split} (@file{g-arrspl.ads}) + @cindex Array splitter + + @noindent + Useful array-manipulation routines: given a set of separators, split + an array wherever the separators appear, and provide direct access + to the resulting slices. + @node GNAT.AWK (g-awk.ads) @section @code{GNAT.AWK} (@file{g-awk.ads}) @cindex @code{GNAT.AWK} (@file{g-awk.ads}) *************** Provides AWK-like parsing functions, wit *** 10434,10439 **** --- 11600,11636 ---- or more files containing formatted data. The file is viewed as a database where each record is a line and a field is a data element in this line. + @node GNAT.Bounded_Buffers (g-boubuf.ads) + @section @code{GNAT.Bounded_Buffers} (@file{g-boubuf.ads}) + @cindex @code{GNAT.Bounded_Buffers} (@file{g-boubuf.ads}) + @cindex Parsing + @cindex Bounded Buffers + + @noindent + Provides a concurrent generic bounded buffer abstraction. Instances are + useful directly or as parts of the implementations of other abstractions, + such as mailboxes. + + @node GNAT.Bounded_Mailboxes (g-boumai.ads) + @section @code{GNAT.Bounded_Mailboxes} (@file{g-boumai.ads}) + @cindex @code{GNAT.Bounded_Mailboxes} (@file{g-boumai.ads}) + @cindex Parsing + @cindex Mailboxes + + @noindent + Provides a thread-safe asynchronous intertask mailbox communication facility. + + @node GNAT.Bubble_Sort (g-bubsor.ads) + @section @code{GNAT.Bubble_Sort} (@file{g-bubsor.ads}) + @cindex @code{GNAT.Bubble_Sort} (@file{g-bubsor.ads}) + @cindex Sorting + @cindex Bubble sort + + @noindent + Provides a general implementation of bubble sort usable for sorting arbitrary + data items. Exchange and comparison procedures are provided by passing + access-to-procedure values. + @node GNAT.Bubble_Sort_A (g-busora.ads) @section @code{GNAT.Bubble_Sort_A} (@file{g-busora.ads}) @cindex @code{GNAT.Bubble_Sort_A} (@file{g-busora.ads}) *************** where each record is a line and a field *** 10443,10449 **** @noindent Provides a general implementation of bubble sort usable for sorting arbitrary data items. Move and comparison procedures are provided by passing ! access-to-procedure values. @node GNAT.Bubble_Sort_G (g-busorg.ads) @section @code{GNAT.Bubble_Sort_G} (@file{g-busorg.ads}) --- 11640,11647 ---- @noindent Provides a general implementation of bubble sort usable for sorting arbitrary data items. Move and comparison procedures are provided by passing ! access-to-procedure values. This is an older version, retained for ! compatibility. Usually @code{GNAT.Bubble_Sort} will be preferable. @node GNAT.Bubble_Sort_G (g-busorg.ads) @section @code{GNAT.Bubble_Sort_G} (@file{g-busorg.ads}) *************** C @code{timeval} format. *** 10482,10490 **** @noindent This package implements the CRC-32 algorithm. For a full description ! of this algorithm you should have a look at: ! ``Computation of Cyclic Redundancy Checks via Table Look-Up'', @cite{Communications ! of the ACM}, Vol.@: 31 No.@: 8, pp.@: 1008-1013, Aug.@: 1988. Sarwate, D.V@. @noindent Provides an extended capability for formatted output of time values with --- 11680,11689 ---- @noindent This package implements the CRC-32 algorithm. For a full description ! of this algorithm see ! ``Computation of Cyclic Redundancy Checks via Table Look-Up'', ! @cite{Communications of the ACM}, Vol.@: 31 No.@: 8, pp.@: 1008-1013, ! Aug.@: 1988. Sarwate, D.V@. @noindent Provides an extended capability for formatted output of time values with *************** Provides a high level interface to @code *** 10543,10548 **** --- 11742,11768 ---- including the ability to scan for named switches with optional parameters and expand file names using wild card notations. + @node GNAT.Compiler_Version (g-comver.ads) + @section @code{GNAT.Compiler_Version} (@file{g-comver.ads}) + @cindex @code{GNAT.Compiler_Version} (@file{g-comver.ads}) + @cindex Compiler Version + @cindex Version, of compiler + + @noindent + Provides a routine for obtaining the version of the compiler used to + compile the program. More accurately this is the version of the binder + used to bind the program (this will normally be the same as the version + of the compiler if a consistent tool set is used to compile all units + of a partition). + + @node GNAT.Ctrl_C (g-ctrl_c.ads) + @section @code{GNAT.Ctrl_C} (@file{g-ctrl_c.ads}) + @cindex @code{GNAT.Ctrl_C} (@file{g-ctrl_c.ads}) + @cindex Interrupt + + @noindent + Provides a simple interface to handle Ctrl-C keyboard events. + @node GNAT.Current_Exception (g-curexc.ads) @section @code{GNAT.Current_Exception} (@file{g-curexc.ads}) @cindex @code{GNAT.Current_Exception} (@file{g-curexc.ads}) *************** the @cite{GNAT User's Guide}. *** 10574,10580 **** @noindent Provides a few useful utilities for debugging purposes, including conversion ! to and from string images of address values. @node GNAT.Directory_Operations (g-dirope.ads) @section @code{GNAT.Directory_Operations} (g-dirope.ads) --- 11794,11801 ---- @noindent Provides a few useful utilities for debugging purposes, including conversion ! to and from string images of address values. Supports both C and Ada formats ! for hexadecimal literals. @node GNAT.Directory_Operations (g-dirope.ads) @section @code{GNAT.Directory_Operations} (g-dirope.ads) *************** Provides a set of routines for manipulat *** 10586,10591 **** --- 11807,11828 ---- the current directory, making new directories, and scanning the files in a directory. + @node GNAT.Dynamic_HTables (g-dynhta.ads) + @section @code{GNAT.Dynamic_HTables} (@file{g-dynhta.ads}) + @cindex @code{GNAT.Dynamic_HTables} (@file{g-dynhta.ads}) + @cindex Hash tables + + @noindent + A generic implementation of hash tables that can be used to hash arbitrary + data. Provided in two forms, a simple form with built in hash functions, + and a more complex form in which the hash function is supplied. + + @noindent + This package provides a facility similar to that of @code{GNAT.HTable}, + except that this package declares a type that can be used to define + dynamic instances of the hash table, while an instantiation of + @code{GNAT.HTable} creates a single instance of the hash table. + @node GNAT.Dynamic_Tables (g-dyntab.ads) @section @code{GNAT.Dynamic_Tables} (@file{g-dyntab.ads}) @cindex @code{GNAT.Dynamic_Tables} (@file{g-dyntab.ads}) *************** A generic package providing a single dim *** 10597,10606 **** length of the array can be dynamically modified. @noindent ! This package provides a facility similar to that of GNAT.Table, except ! that this package declares a type that can be used to define dynamic ! instances of the table, while an instantiation of GNAT.Table creates a ! single instance of the table type. @node GNAT.Exception_Traces (g-exctra.ads) @section @code{GNAT.Exception_Traces} (@file{g-exctra.ads}) --- 11834,11853 ---- length of the array can be dynamically modified. @noindent ! This package provides a facility similar to that of @code{GNAT.Table}, ! except that this package declares a type that can be used to define ! dynamic instances of the table, while an instantiation of ! @code{GNAT.Table} creates a single instance of the table type. ! ! @node GNAT.Exception_Actions (g-excact.ads) ! @section @code{GNAT.Exception_Actions} (@file{g-excact.ads}) ! @cindex @code{GNAT.Exception_Actions} (@file{g-excact.ads}) ! @cindex Exception actions ! ! @noindent ! Provides callbacks when an exception is raised. Callbacks can be registered ! for specific exceptions, or when any exception is raised. This ! can be used for instance to force a core dump to ease debugging. @node GNAT.Exception_Traces (g-exctra.ads) @section @code{GNAT.Exception_Traces} (@file{g-exctra.ads}) *************** single instance of the table type. *** 10612,10617 **** --- 11859,11879 ---- Provides an interface allowing to control automatic output upon exception occurrences. + @node GNAT.Exceptions (g-except.ads) + @section @code{GNAT.Exceptions} (@file{g-expect.ads}) + @cindex @code{GNAT.Exceptions} (@file{g-expect.ads}) + @cindex Exceptions, Pure + @cindex Pure packages, exceptions + + @noindent + Normally it is not possible to raise an exception with + a message from a subprogram in a pure package, since the + necessary types and subprograms are in @code{Ada.Exceptions} + which is not a pure unit. @code{GNAT.Exceptions} provides a + facility for getting around this limitation for a few + predefined exceptions, and for example allow raising + @code{Constraint_Error} with a message from a pure subprogram. + @node GNAT.Expect (g-expect.ads) @section @code{GNAT.Expect} (@file{g-expect.ads}) @cindex @code{GNAT.Expect} (@file{g-expect.ads}) *************** Provides a set of subprograms similar to *** 10621,10629 **** with the standard Tcl Expect tool. It allows you to easily spawn and communicate with an external process. You can send commands or inputs to the process, and compare the output ! with some expected regular expression. ! Currently GNAT.Expect is implemented on all native GNAT ports except for ! OpenVMS@. It is not implemented for cross ports, and in particular is not implemented for VxWorks or LynxOS@. @node GNAT.Float_Control (g-flocon.ads) --- 11883,11891 ---- with the standard Tcl Expect tool. It allows you to easily spawn and communicate with an external process. You can send commands or inputs to the process, and compare the output ! with some expected regular expression. Currently @code{GNAT.Expect} ! is implemented on all native GNAT ports except for OpenVMS@. ! It is not implemented for cross ports, and in particular is not implemented for VxWorks or LynxOS@. @node GNAT.Float_Control (g-flocon.ads) *************** mode required for correct semantic opera *** 10637,10642 **** --- 11899,11915 ---- library calls may cause this mode to be modified, and the Reset procedure in this package can be used to reestablish the required mode. + @node GNAT.Heap_Sort (g-heasor.ads) + @section @code{GNAT.Heap_Sort} (@file{g-heasor.ads}) + @cindex @code{GNAT.Heap_Sort} (@file{g-heasor.ads}) + @cindex Sorting + + @noindent + Provides a general implementation of heap sort usable for sorting arbitrary + data items. Exchange and comparison procedures are provided by passing + access-to-procedure values. The algorithm used is a modified heap sort + that performs approximately N*log(N) comparisons in the worst case. + @node GNAT.Heap_Sort_A (g-hesora.ads) @section @code{GNAT.Heap_Sort_A} (@file{g-hesora.ads}) @cindex @code{GNAT.Heap_Sort_A} (@file{g-hesora.ads}) *************** in this package can be used to reestabli *** 10644,10652 **** @noindent Provides a general implementation of heap sort usable for sorting arbitrary ! data items. Move and comparison procedures are provided by passing access-to-procedure values. The algorithm used is a modified heap sort that performs approximately N*log(N) comparisons in the worst case. @node GNAT.Heap_Sort_G (g-hesorg.ads) @section @code{GNAT.Heap_Sort_G} (@file{g-hesorg.ads}) --- 11917,11927 ---- @noindent Provides a general implementation of heap sort usable for sorting arbitrary ! data items. Move and comparison procedures are provided by passing access-to-procedure values. The algorithm used is a modified heap sort that performs approximately N*log(N) comparisons in the worst case. + This differs from @code{GNAT.Heap_Sort} in having a less convenient + interface, but may be slightly more efficient. @node GNAT.Heap_Sort_G (g-hesorg.ads) @section @code{GNAT.Heap_Sort_G} (@file{g-hesorg.ads}) *************** allowing arbitrary dynamic hash tables. *** 10676,10682 **** @cindex Input/Output facilities @noindent ! A simple preealborable input-output package that provides a subset of simple Text_IO functions for reading characters and strings from Standard_Input, and writing characters, strings and integers to either Standard_Output or Standard_Error. --- 11951,11957 ---- @cindex Input/Output facilities @noindent ! A simple preelaborable input-output package that provides a subset of simple Text_IO functions for reading characters and strings from Standard_Input, and writing characters, strings and integers to either Standard_Output or Standard_Error. *************** for whether a file exists, and functions *** 10698,10704 **** @noindent Provides a general interface for using files as locks. Can be used for ! providing program level synchronization. @node GNAT.MD5 (g-md5.ads) @section @code{GNAT.MD5} (@file{g-md5.ads}) --- 11973,11979 ---- @noindent Provides a general interface for using files as locks. Can be used for ! providing program level synchronization. @node GNAT.MD5 (g-md5.ads) @section @code{GNAT.MD5} (@file{g-md5.ads}) *************** providing program level synchronization. *** 10706,10712 **** @cindex Message Digest MD5 @noindent ! Implements the MD5 Message-Digest Algorithm as described in RFC 1321. @node GNAT.Most_Recent_Exception (g-moreex.ads) @section @code{GNAT.Most_Recent_Exception} (@file{g-moreex.ads}) --- 11981,11997 ---- @cindex Message Digest MD5 @noindent ! Implements the MD5 Message-Digest Algorithm as described in RFC 1321. ! ! @node GNAT.Memory_Dump (g-memdum.ads) ! @section @code{GNAT.Memory_Dump} (@file{g-memdum.ads}) ! @cindex @code{GNAT.Memory_Dump} (@file{g-memdum.ads}) ! @cindex Dump Memory ! ! @noindent ! Provides a convenient routine for dumping raw memory to either the ! standard output or standard error files. Uses GNAT.IO for actual ! output. @node GNAT.Most_Recent_Exception (g-moreex.ads) @section @code{GNAT.Most_Recent_Exception} (@file{g-moreex.ads}) *************** including time/date management, file ope *** 10730,10735 **** --- 12015,12035 ---- including a portable spawn procedure, and access to environment variables and error return codes. + @node GNAT.Perfect_Hash.Generators (g-pehage.ads) + @section @code{GNAT.Perfect_Hash.Generators} (@file{g-pehage.ads}) + @cindex @code{GNAT.Perfect_Hash.Generators} (@file{g-pehage.ads}) + @cindex Hash functions + + @noindent + Provides a generator of static minimal perfect hash functions. No + collisions occur and each item can be retrieved from the table in one + probe (perfect property). The hash table size corresponds to the exact + size of the key set and no larger (minimal property). The key set has to + be know in advance (static property). The hash functions are also order + preservering. If w2 is inserted after w1 in the generator, their + hashcode are in the same order. These hashing functions are very + convenient for use with realtime applications. + @node GNAT.Regexp (g-regexp.ads) @section @code{GNAT.Regexp} (@file{g-regexp.ads}) @cindex @code{GNAT.Regexp} (@file{g-regexp.ads}) *************** A complete implementation of Unix-style *** 10764,10769 **** --- 12064,12095 ---- from the original V7 style regular expression library written in C by Henry Spencer (and binary compatible with this C library). + @node GNAT.Secondary_Stack_Info (g-sestin.ads) + @section @code{GNAT.Secondary_Stack_Info} (@file{g-sestin.ads}) + @cindex @code{GNAT.Secondary_Stack_Info} (@file{g-sestin.ads}) + @cindex Secondary Stack Info + + @noindent + Provide the capability to query the high water mark of the current task's + secondary stack. + + @node GNAT.Semaphores (g-semaph.ads) + @section @code{GNAT.Semaphores} (@file{g-semaph.ads}) + @cindex @code{GNAT.Semaphores} (@file{g-semaph.ads}) + @cindex Semaphores + + @noindent + Provides classic counting and binary semaphores using protected types. + + @node GNAT.Signals (g-signal.ads) + @section @code{GNAT.Signals} (@file{g-signal.ads}) + @cindex @code{GNAT.Signals} (@file{g-signal.ads}) + @cindex Signals + + @noindent + Provides the ability to manipulate the blocked status of signals on supported + targets. + @node GNAT.Sockets (g-socket.ads) @section @code{GNAT.Sockets} (@file{g-socket.ads}) @cindex @code{GNAT.Sockets} (@file{g-socket.ads}) *************** Henry Spencer (and binary compatible wit *** 10771,10779 **** @noindent A high level and portable interface to develop sockets based applications. ! This package is based on the sockets thin binding found in GNAT.Sockets.Thin. ! Currently GNAT.Sockets is implemented on all native GNAT ports except for ! OpenVMS@. It is not implemented for the LynxOS@ cross port. @node GNAT.Source_Info (g-souinf.ads) @section @code{GNAT.Source_Info} (@file{g-souinf.ads}) --- 12097,12106 ---- @noindent A high level and portable interface to develop sockets based applications. ! This package is based on the sockets thin binding found in ! @code{GNAT.Sockets.Thin}. Currently @code{GNAT.Sockets} is implemented ! on all native GNAT ports except for OpenVMS@. It is not implemented ! for the LynxOS@ cross port. @node GNAT.Source_Info (g-souinf.ads) @section @code{GNAT.Source_Info} (@file{g-souinf.ads}) *************** from string to integer values. *** 10848,10857 **** @cindex SPITBOL Tables @noindent ! A library level of instantiation of GNAT.Spitbol.Patterns.Table for a variable length string type, giving an implementation of general maps from strings to strings. @node GNAT.Table (g-table.ads) @section @code{GNAT.Table} (@file{g-table.ads}) @cindex @code{GNAT.Table} (@file{g-table.ads}) --- 12175,12203 ---- @cindex SPITBOL Tables @noindent ! A library level of instantiation of @code{GNAT.Spitbol.Patterns.Table} for a variable length string type, giving an implementation of general maps from strings to strings. + @node GNAT.Strings (g-string.ads) + @section @code{GNAT.Strings} (@file{g-string.ads}) + @cindex @code{GNAT.Strings} (@file{g-string.ads}) + + @noindent + Common String access types and related subprograms. Basically it + defines a string access and an array of string access types. + + @node GNAT.String_Split (g-strspl.ads) + @section @code{GNAT.String_Split} (@file{g-strspl.ads}) + @cindex @code{GNAT.String_Split} (@file{g-strspl.ads}) + @cindex String splitter + + @noindent + Useful string-manipulation routines: given a set of separators, split + a string wherever the separators appear, and provide direct access + to the resulting slices. This package is instantiated from + @code{GNAT.Array_Split}. + @node GNAT.Table (g-table.ads) @section @code{GNAT.Table} (@file{g-table.ads}) @cindex @code{GNAT.Table} (@file{g-table.ads}) *************** A generic package providing a single dim *** 10863,10871 **** length of the array can be dynamically modified. @noindent ! This package provides a facility similar to that of GNAT.Dynamic_Tables, except that this package declares a single instance of the table type, ! while an instantiation of GNAT.Dynamic_Tables creates a type that can be used to define dynamic instances of the table. @node GNAT.Task_Lock (g-tasloc.ads) --- 12209,12217 ---- length of the array can be dynamically modified. @noindent ! This package provides a facility similar to that of @code{GNAT.Dynamic_Tables}, except that this package declares a single instance of the table type, ! while an instantiation of @code{GNAT.Dynamic_Tables} creates a type that can be used to define dynamic instances of the table. @node GNAT.Task_Lock (g-tasloc.ads) *************** in various debugging situations. *** 10911,10916 **** --- 12257,12273 ---- Provides symbolic traceback information that includes the subprogram name and line number information. + @node GNAT.Wide_String_Split (g-wistsp.ads) + @section @code{GNAT.Wide_String_Split} (@file{g-wistsp.ads}) + @cindex @code{GNAT.Wide_String_Split} (@file{g-wistsp.ads}) + @cindex Wide_String splitter + + @noindent + Useful wide_string-manipulation routines: given a set of separators, split + a wide_string wherever the separators appear, and provide direct access + to the resulting slices. This package is instantiated from + @code{GNAT.Array_Split}. + @node Interfaces.C.Extensions (i-cexten.ads) @section @code{Interfaces.C.Extensions} (@file{i-cexten.ads}) @cindex @code{Interfaces.C.Extensions} (@file{i-cexten.ads}) *************** VxWorks hardware interrupt facilities. *** 11011,11021 **** @cindex Interfacing to VxWorks' I/O @cindex VxWorks, I/O interfacing @cindex VxWorks, Get_Immediate @noindent ! This package provides a limited binding to the VxWorks' I/O API. ! In particular, it provides procedures that enable the use of ! Get_Immediate under VxWorks. @node System.Address_Image (s-addima.ads) @section @code{System.Address_Image} (@file{s-addima.ads}) --- 12368,12380 ---- @cindex Interfacing to VxWorks' I/O @cindex VxWorks, I/O interfacing @cindex VxWorks, Get_Immediate + @cindex Get_Immediate, VxWorks @noindent ! This package provides a binding to the ioctl (IO/Control) ! function of VxWorks, defining a set of option values and ! function codes. A particular use of this package is ! to enable the use of Get_Immediate under VxWorks. @node System.Address_Image (s-addima.ads) @section @code{System.Address_Image} (@file{s-addima.ads}) *************** This package provides the declaration of *** 11039,11044 **** --- 12398,12418 ---- by an run-time assertion failure, as well as the routine that is used internally to raise this assertion. + @node System.Memory (s-memory.ads) + @section @code{System.Memory} (@file{s-memory.ads}) + @cindex @code{System.Memory} (@file{s-memory.ads}) + @cindex Memory allocation + + @noindent + This package provides the interface to the low level routines used + by the generated code for allocation and freeing storage for the + default storage pool (analogous to the C routines malloc and free. + It also provides a reallocation interface analogous to the C routine + realloc. The body of this unit may be modified to provide alternative + allocation mechanisms for the default pool, and in addition, direct + calls to this unit may be made for low level allocation uses (for + example see the body of @code{GNAT.Tables}). + @node System.Partition_Interface (s-parint.ads) @section @code{System.Partition_Interface} (@file{s-parint.ads}) @cindex @code{System.Partition_Interface} (@file{s-parint.ads}) *************** implemented in GNAT, and in addition, a *** 11090,11099 **** provided. @menu ! * Interfacing to C:: ! * Interfacing to C++:: ! * Interfacing to COBOL:: ! * Interfacing to Fortran:: * Interfacing to non-GNAT Ada code:: @end menu --- 12464,12473 ---- provided. @menu ! * Interfacing to C:: ! * Interfacing to C++:: ! * Interfacing to COBOL:: ! * Interfacing to Fortran:: * Interfacing to non-GNAT Ada code:: @end menu *************** provided. *** 11103,11119 **** @noindent Interfacing to C with GNAT can use one of two approaches: ! @enumerate @item The types in the package @code{Interfaces.C} may be used. @item Standard Ada types may be used directly. This may be less portable to other compilers, but will work on all GNAT compilers, which guarantee correspondence between the C and Ada types. ! @end enumerate @noindent ! Pragma @code{Convention C} maybe applied to Ada types, but mostly has no effect, since this is the default. The following table shows the correspondence between Ada scalar types and the corresponding C types. --- 12477,12493 ---- @noindent Interfacing to C with GNAT can use one of two approaches: ! @itemize @bullet @item The types in the package @code{Interfaces.C} may be used. @item Standard Ada types may be used directly. This may be less portable to other compilers, but will work on all GNAT compilers, which guarantee correspondence between the C and Ada types. ! @end itemize @noindent ! Pragma @code{Convention C} may be applied to Ada types, but mostly has no effect, since this is the default. The following table shows the correspondence between Ada scalar types and the corresponding C types. *************** correspondence between Ada scalar types *** 11138,11151 **** This is the longest floating-point type supported by the hardware. @end table @itemize @bullet @item Ada enumeration types map to C enumeration types directly if pragma @code{Convention C} is specified, which causes them to have int length. Without pragma @code{Convention C}, Ada enumeration types map to ! 8, 16, or 32 bits (i.e.@: C types @code{signed char}, @code{short}, @code{int}, respectively) ! depending on the number of values passed. This is the only case in which ! pragma @code{Convention C} affects the representation of an Ada type. @item Ada access types map to C pointers, except for the case of pointers to --- 12512,12529 ---- This is the longest floating-point type supported by the hardware. @end table + @noindent + Additionally, there are the following general correspondences between Ada + and C types: @itemize @bullet @item Ada enumeration types map to C enumeration types directly if pragma @code{Convention C} is specified, which causes them to have int length. Without pragma @code{Convention C}, Ada enumeration types map to ! 8, 16, or 32 bits (i.e.@: C types @code{signed char}, @code{short}, ! @code{int}, respectively) depending on the number of values passed. ! This is the only case in which pragma @code{Convention C} affects the ! representation of an Ada type. @item Ada access types map to C pointers, except for the case of pointers to *************** primarily intended to be constructed aut *** 11171,11179 **** tool, although it is possible to construct them by hand. No suitable binding generator tool is supplied with GNAT though. Using these pragmas it is possible to achieve complete inter-operability between Ada tagged types and C class definitions. ! See @ref{Implementation Defined Pragmas} for more details. @table @code @item pragma CPP_Class ([Entity =>] @var{local_name}) --- 12549,12558 ---- tool, although it is possible to construct them by hand. No suitable binding generator tool is supplied with GNAT though. + Using these pragmas it is possible to achieve complete inter-operability between Ada tagged types and C class definitions. ! See @ref{Implementation Defined Pragmas}, for more details. @table @code @item pragma CPP_Class ([Entity =>] @var{local_name}) *************** order as required for convenient interfa *** 11211,11225 **** @node Interfacing to non-GNAT Ada code @section Interfacing to non-GNAT Ada code ! It is possible to specify the convention @code{Ada} in a pragma @code{Import} or ! pragma @code{Export}. However this refers to the calling conventions used ! by GNAT, which may or may not be similar enough to those used by ! some other Ada 83 or Ada 95 compiler to allow interoperation. If arguments types are kept simple, and if the foreign compiler generally follows system calling conventions, then it may be possible to integrate files compiled by other Ada compilers, provided that the elaboration ! issues are adequately addressed (for example by eliminating the need for any load time elaboration). In particular, GNAT running on VMS is designed to --- 12590,12605 ---- @node Interfacing to non-GNAT Ada code @section Interfacing to non-GNAT Ada code ! It is possible to specify the convention @code{Ada} in a pragma ! @code{Import} or pragma @code{Export}. However this refers to ! the calling conventions used by GNAT, which may or may not be ! similar enough to those used by some other Ada 83 or Ada 95 ! compiler to allow interoperation. If arguments types are kept simple, and if the foreign compiler generally follows system calling conventions, then it may be possible to integrate files compiled by other Ada compilers, provided that the elaboration ! issues are adequately addressed (for example by eliminating the need for any load time elaboration). In particular, GNAT running on VMS is designed to *************** provided that the data items passed are *** 11229,11236 **** values or simple record types without variants, or simple array types with fixed bounds. @node Machine Code Insertions ! @chapter Machine Code Insertions @noindent Package @code{Machine_Code} provides machine code support as described --- 12609,12664 ---- values or simple record types without variants, or simple array types with fixed bounds. + + @node Specialized Needs Annexes + @chapter Specialized Needs Annexes + + @noindent + Ada 95 defines a number of specialized needs annexes, which are not + required in all implementations. However, as described in this chapter, + GNAT implements all of these special needs annexes: + + @table @asis + @item Systems Programming (Annex C) + The Systems Programming Annex is fully implemented. + + @item Real-Time Systems (Annex D) + The Real-Time Systems Annex is fully implemented. + + @item Distributed Systems (Annex E) + Stub generation is fully implemented in the GNAT compiler. In addition, + a complete compatible PCS is available as part of the GLADE system, + a separate product. When the two + products are used in conjunction, this annex is fully implemented. + + @item Information Systems (Annex F) + The Information Systems annex is fully implemented. + + @item Numerics (Annex G) + The Numerics Annex is fully implemented. + + @item Safety and Security (Annex H) + The Safety and Security annex is fully implemented. + @end table + + + @node Implementation of Specific Ada Features + @chapter Implementation of Specific Ada Features + + @noindent + This chapter describes the GNAT implementation of several Ada language + facilities. + + @menu + * Machine Code Insertions:: + * GNAT Implementation of Tasking:: + * GNAT Implementation of Shared Passive Packages:: + * Code Generation for Array Aggregates:: + @end menu + + @node Machine Code Insertions ! @section Machine Code Insertions @noindent Package @code{Machine_Code} provides machine code support as described *************** An intrinsic callable procedure, providi *** 11244,11253 **** including machine instructions in a subprogram. @end itemize The two features are similar, and both closely related to the mechanism provided by the asm instruction in the GNU C compiler. Full understanding and use of the facilities in this package requires understanding the asm ! instruction as described in @cite{Using and Porting the GNU Compiler Collection (GCC)} by Richard Stallman. Calls to the function @code{Asm} and the procedure @code{Asm} have identical semantic restrictions and effects as described below. --- 12672,12682 ---- including machine instructions in a subprogram. @end itemize + @noindent The two features are similar, and both closely related to the mechanism provided by the asm instruction in the GNU C compiler. Full understanding and use of the facilities in this package requires understanding the asm ! instruction as described in @cite{Using and Porting the GNU Compiler Collection (GCC)} by Richard Stallman. Calls to the function @code{Asm} and the procedure @code{Asm} have identical semantic restrictions and effects as described below. *************** instruction: *** 11263,11274 **** @noindent The equivalent can be written for GNAT as: ! @smallexample Asm ("fsinx %1 %0", My_Float'Asm_Output ("=f", result), My_Float'Asm_Input ("f", angle)); @end smallexample The first argument to @code{Asm} is the assembler template, and is identical to what is used in GNU C@. This string must be a static expression. The second argument is the output operand list. It is --- 12692,12704 ---- @noindent The equivalent can be written for GNAT as: ! @smallexample @c ada Asm ("fsinx %1 %0", My_Float'Asm_Output ("=f", result), My_Float'Asm_Input ("f", angle)); @end smallexample + @noindent The first argument to @code{Asm} is the assembler template, and is identical to what is used in GNU C@. This string must be a static expression. The second argument is the output operand list. It is *************** private type @code{Asm_Insn}, can be use *** 11331,11341 **** this is the only context where such calls are allowed. Code statements appear as aggregates of the form: ! @smallexample Asm_Insn'(Asm (@dots{})); Asm_Insn'(Asm_Volatile (@dots{})); @end smallexample In accordance with RM rules, such code statements are allowed only within subprograms whose entire body consists of such statements. It is not permissible to intermix such statements with other Ada statements. --- 12761,12772 ---- this is the only context where such calls are allowed. Code statements appear as aggregates of the form: ! @smallexample @c ada Asm_Insn'(Asm (@dots{})); Asm_Insn'(Asm_Volatile (@dots{})); @end smallexample + @noindent In accordance with RM rules, such code statements are allowed only within subprograms whose entire body consists of such statements. It is not permissible to intermix such statements with other Ada statements. *************** not permissible to intermix such stateme *** 11343,11350 **** Typically the form using intrinsic procedure calls is more convenient and more flexible. The code statement form is provided to meet the RM suggestion that such a facility should be made available. The following ! is the exact syntax of the call to @code{Asm} (of course if named notation is ! used, the arguments may be given in arbitrary order, following the normal rules for use of positional and named arguments) @smallexample --- 12774,12781 ---- Typically the form using intrinsic procedure calls is more convenient and more flexible. The code statement form is provided to meet the RM suggestion that such a facility should be made available. The following ! is the exact syntax of the call to @code{Asm}. As usual, if named notation ! is used, the arguments may be given in arbitrary order, following the normal rules for use of positional and named arguments) @smallexample *************** ASM_CALL ::= Asm ( *** 11354,11390 **** [,[Inputs =>] INPUT_OPERAND_LIST ] [,[Clobber =>] static_string_EXPRESSION ] [,[Volatile =>] static_boolean_EXPRESSION] ) OUTPUT_OPERAND_LIST ::= ! No_Output_Operands | OUTPUT_OPERAND_ATTRIBUTE | (OUTPUT_OPERAND_ATTRIBUTE @{,OUTPUT_OPERAND_ATTRIBUTE@}) OUTPUT_OPERAND_ATTRIBUTE ::= SUBTYPE_MARK'Asm_Output (static_string_EXPRESSION, NAME) INPUT_OPERAND_LIST ::= ! No_Input_Operands | INPUT_OPERAND_ATTRIBUTE | (INPUT_OPERAND_ATTRIBUTE @{,INPUT_OPERAND_ATTRIBUTE@}) INPUT_OPERAND_ATTRIBUTE ::= SUBTYPE_MARK'Asm_Input (static_string_EXPRESSION, EXPRESSION) @end smallexample @node GNAT Implementation of Tasking ! @chapter GNAT Implementation of Tasking @menu * Mapping Ada Tasks onto the Underlying Kernel Threads:: * Ensuring Compliance with the Real-Time Annex:: @end menu @node Mapping Ada Tasks onto the Underlying Kernel Threads ! @section Mapping Ada Tasks onto the Underlying Kernel Threads ! GNAT run-time system comprises two layers: @itemize @bullet ! @item GNARL (GNAT Run-time Layer) @item GNULL (GNAT Low-level Library) @end itemize In GNAT, Ada's tasking services rely on a platform and OS independent layer known as GNARL@. This code is responsible for implementing the correct semantics of Ada's task creation, rendezvous, protected --- 12785,12840 ---- [,[Inputs =>] INPUT_OPERAND_LIST ] [,[Clobber =>] static_string_EXPRESSION ] [,[Volatile =>] static_boolean_EXPRESSION] ) + OUTPUT_OPERAND_LIST ::= ! [PREFIX.]No_Output_Operands | OUTPUT_OPERAND_ATTRIBUTE | (OUTPUT_OPERAND_ATTRIBUTE @{,OUTPUT_OPERAND_ATTRIBUTE@}) + OUTPUT_OPERAND_ATTRIBUTE ::= SUBTYPE_MARK'Asm_Output (static_string_EXPRESSION, NAME) + INPUT_OPERAND_LIST ::= ! [PREFIX.]No_Input_Operands | INPUT_OPERAND_ATTRIBUTE | (INPUT_OPERAND_ATTRIBUTE @{,INPUT_OPERAND_ATTRIBUTE@}) + INPUT_OPERAND_ATTRIBUTE ::= SUBTYPE_MARK'Asm_Input (static_string_EXPRESSION, EXPRESSION) @end smallexample + @noindent + The identifiers @code{No_Input_Operands} and @code{No_Output_Operands} + are declared in the package @code{Machine_Code} and must be referenced + according to normal visibility rules. In particular if there is no + @code{use} clause for this package, then appropriate package name + qualification is required. + @node GNAT Implementation of Tasking ! @section GNAT Implementation of Tasking ! ! @noindent ! This chapter outlines the basic GNAT approach to tasking (in particular, ! a multi-layered library for portability) and discusses issues related ! to compliance with the Real-Time Systems Annex. ! @menu * Mapping Ada Tasks onto the Underlying Kernel Threads:: * Ensuring Compliance with the Real-Time Annex:: @end menu @node Mapping Ada Tasks onto the Underlying Kernel Threads ! @subsection Mapping Ada Tasks onto the Underlying Kernel Threads ! @noindent ! GNAT's run-time support comprises two layers: @itemize @bullet ! @item GNARL (GNAT Run-time Layer) @item GNULL (GNAT Low-level Library) @end itemize + @noindent In GNAT, Ada's tasking services rely on a platform and OS independent layer known as GNARL@. This code is responsible for implementing the correct semantics of Ada's task creation, rendezvous, protected *************** the services offered by the underlying k *** 11403,11420 **** by GNARL@. Whatever the underlying OS (VxWorks, UNIX, OS/2, Windows NT, etc.) the ! key point is that each Ada task is mapped on a thread in the underlying kernel. For example, in the case of VxWorks, one Ada task = one VxWorks task. In addition Ada task priorities map onto the underlying thread priorities. Mapping Ada tasks onto the underlying kernel threads has several advantages: ! @enumerate ! @item The underlying scheduler is used to schedule the Ada tasks. This makes Ada tasks as efficient as kernel threads from a scheduling ! standpoint. @item Interaction with code written in C containing threads is eased --- 12853,12869 ---- by GNARL@. Whatever the underlying OS (VxWorks, UNIX, OS/2, Windows NT, etc.) the ! key point is that each Ada task is mapped on a thread in the underlying kernel. For example, in the case of VxWorks, one Ada task = one VxWorks task. In addition Ada task priorities map onto the underlying thread priorities. Mapping Ada tasks onto the underlying kernel threads has several advantages: ! @itemize @bullet @item The underlying scheduler is used to schedule the Ada tasks. This makes Ada tasks as efficient as kernel threads from a scheduling ! standpoint. @item Interaction with code written in C containing threads is eased *************** When an Ada task is blocked during I/O t *** 11426,11455 **** able to proceed. @item ! On multi-processor systems Ada Tasks can execute in parallel. ! @end enumerate @node Ensuring Compliance with the Real-Time Annex ! @section Ensuring Compliance with the Real-Time Annex ! The reader will be quick to notice that while mapping Ada tasks onto the underlying threads has significant advantages, it does create some complications when it comes to respecting the scheduling semantics specified in the real-time annex (Annex D). ! For instance Annex D requires that for the FIFO_Within_Priorities ! scheduling policy we have: ! @smallexample ! When the active priority of a ready task that is not running changes, or the setting of its base priority takes effect, the task is removed from the ready queue for its old active priority and is added at the tail of the ready queue for its new active priority, except in the case where the active priority is lowered due to the loss of inherited priority, in which case the task is ! added at the head of the ready queue for its new active priority. ! @end smallexample While most kernels do put tasks at the end of the priority queue when a task changes its priority, (which respects the main FIFO_Within_Priorities requirement), almost none keep a thread at the --- 12875,12915 ---- able to proceed. @item ! On multiprocessor systems Ada tasks can execute in parallel. ! @end itemize ! ! @noindent ! Some threads libraries offer a mechanism to fork a new process, with the ! child process duplicating the threads from the parent. ! GNAT does not ! support this functionality when the parent contains more than one task. ! @cindex Forking a new process ! @node Ensuring Compliance with the Real-Time Annex ! @subsection Ensuring Compliance with the Real-Time Annex ! @cindex Real-Time Systems Annex compliance ! @noindent ! Although mapping Ada tasks onto the underlying threads has significant advantages, it does create some complications when it comes to respecting the scheduling semantics specified in the real-time annex (Annex D). ! For instance the Annex D requirement for the @code{FIFO_Within_Priorities} ! scheduling policy states: ! @quotation ! @emph{When the active priority of a ready task that is not running changes, or the setting of its base priority takes effect, the task is removed from the ready queue for its old active priority and is added at the tail of the ready queue for its new active priority, except in the case where the active priority is lowered due to the loss of inherited priority, in which case the task is ! added at the head of the ready queue for its new active priority.} ! @end quotation + @noindent While most kernels do put tasks at the end of the priority queue when a task changes its priority, (which respects the main FIFO_Within_Priorities requirement), almost none keep a thread at the *************** running, it checks whether some other Ad *** 11467,11489 **** priority as T has been suspended due to the loss of priority inheritance. If this is the case, T yields and is placed at the end of its priority queue. When R arrives at the front of the queue it ! executes. Note that this simple scheme preserves the relative order of the tasks that were ready to execute in the priority queue where R has been placed at the end. ! @node Code generation for array aggregates ! @chapter Code generation for array aggregates @menu * Static constant aggregates with static bounds:: * Constant aggregates with an unconstrained nominal types:: * Aggregates with static bounds:: * Aggregates with non-static bounds:: ! * Aggregates in assignments statements:: @end menu ! Aggregate have a rich syntax and allow the user to specify the values of complex data structures by means of a single construct. As a result, the code generated for aggregates can be quite complex and involve loops, case --- 12927,13044 ---- priority as T has been suspended due to the loss of priority inheritance. If this is the case, T yields and is placed at the end of its priority queue. When R arrives at the front of the queue it ! executes. Note that this simple scheme preserves the relative order of the tasks that were ready to execute in the priority queue where R has been placed at the end. ! @node GNAT Implementation of Shared Passive Packages ! @section GNAT Implementation of Shared Passive Packages ! @cindex Shared passive packages ! ! @noindent ! GNAT fully implements the pragma @code{Shared_Passive} for ! @cindex pragma @code{Shared_Passive} ! the purpose of designating shared passive packages. ! This allows the use of passive partitions in the ! context described in the Ada Reference Manual; i.e. for communication ! between separate partitions of a distributed application using the ! features in Annex E. ! @cindex Annex E ! @cindex Distribution Systems Annex ! ! However, the implementation approach used by GNAT provides for more ! extensive usage as follows: ! ! @table @emph ! @item Communication between separate programs ! ! This allows separate programs to access the data in passive ! partitions, using protected objects for synchronization where ! needed. The only requirement is that the two programs have a ! common shared file system. It is even possible for programs ! running on different machines with different architectures ! (e.g. different endianness) to communicate via the data in ! a passive partition. ! ! @item Persistence between program runs ! ! The data in a passive package can persist from one run of a ! program to another, so that a later program sees the final ! values stored by a previous run of the same program. ! ! @end table ! ! @noindent ! The implementation approach used is to store the data in files. A ! separate stream file is created for each object in the package, and ! an access to an object causes the corresponding file to be read or ! written. ! ! The environment variable @code{SHARED_MEMORY_DIRECTORY} should be ! @cindex @code{SHARED_MEMORY_DIRECTORY} environment variable ! set to the directory to be used for these files. ! The files in this directory ! have names that correspond to their fully qualified names. For ! example, if we have the package ! ! @smallexample @c ada ! package X is ! pragma Shared_Passive (X); ! Y : Integer; ! Z : Float; ! end X; ! @end smallexample ! ! @noindent ! and the environment variable is set to @code{/stemp/}, then the files created ! will have the names: ! ! @smallexample ! /stemp/x.y ! /stemp/x.z ! @end smallexample ! ! @noindent ! These files are created when a value is initially written to the object, and ! the files are retained until manually deleted. This provides the persistence ! semantics. If no file exists, it means that no partition has assigned a value ! to the variable; in this case the initial value declared in the package ! will be used. This model ensures that there are no issues in synchronizing ! the elaboration process, since elaboration of passive packages elaborates the ! initial values, but does not create the files. ! ! The files are written using normal @code{Stream_IO} access. ! If you want to be able ! to communicate between programs or partitions running on different ! architectures, then you should use the XDR versions of the stream attribute ! routines, since these are architecture independent. ! ! If active synchronization is required for access to the variables in the ! shared passive package, then as described in the Ada Reference Manual, the ! package may contain protected objects used for this purpose. In this case ! a lock file (whose name is @file{___lock} (three underscores) ! is created in the shared memory directory. ! @cindex @file{___lock} file (for shared passive packages) ! This is used to provide the required locking ! semantics for proper protected object synchronization. ! ! As of January 2003, GNAT supports shared passive packages on all platforms ! except for OpenVMS. ! ! @node Code Generation for Array Aggregates ! @section Code Generation for Array Aggregates @menu * Static constant aggregates with static bounds:: * Constant aggregates with an unconstrained nominal types:: * Aggregates with static bounds:: * Aggregates with non-static bounds:: ! * Aggregates in assignment statements:: @end menu ! ! @noindent Aggregate have a rich syntax and allow the user to specify the values of complex data structures by means of a single construct. As a result, the code generated for aggregates can be quite complex and involve loops, case *************** The code generated for aggregates depend *** 11500,11967 **** and the type. In the context of an object declaration the code generated is generally simpler than in the case of an assignment. As a general rule, static component values and static subtypes also lead to simpler code. ! @node Static constant aggregates with static bounds ! @section Static constant aggregates with static bounds ! ! For the declarations: ! @smallexample type One_Dim is array (1..10) of integer; ar0 : constant One_Dim := ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 0); ! @end smallexample GNAT generates no executable code: the constant ar0 is placed in static memory. The same is true for constant aggregates with named associations: ! ! @smallexample Cr1 : constant One_Dim := (4 => 16, 2 => 4, 3 => 9, 1=> 1); Cr3 : constant One_Dim := (others => 7777); ! @end smallexample ! ! The same is true for multidimensional constant arrays such as: ! ! @smallexample type two_dim is array (1..3, 1..3) of integer; Unit : constant two_dim := ( (1,0,0), (0,1,0), (0,0,1)); ! @end smallexample ! The same is true for arrays of one-dimensional arrays: the following are static: ! ! @smallexample ! type ar1b is array (1..3) of boolean; type ar_ar is array (1..3) of ar1b; ! None : constant ar1b := (others => false); -- fully static None2 : constant ar_ar := (1..3 => None); -- fully static ! @end smallexample ! However, for multidimensional aggregates with named associations, GNAT will generate assignments and loops, even if all associations are static. The following two declarations generate a loop for the first dimension, and individual component assignments for the second dimension: ! ! @smallexample Zero1: constant two_dim := (1..3 => (1..3 => 0)); ! Zero2: constant two_dim := (others => (others => 0)); ! @end smallexample ! @node Constant aggregates with an unconstrained nominal types ! @section Constant aggregates with an unconstrained nominal types ! ! In such cases the aggregate itself establishes the subtype, so that associations ! with @code{others} cannot be used. GNAT determines the bounds for the actual ! subtype of the aggregate, and allocates the aggregate statically as well. No ! code is generated for the following: ! ! @smallexample type One_Unc is array (natural range <>) of integer; Cr_Unc : constant One_Unc := (12,24,36); ! @end smallexample ! @node Aggregates with static bounds ! @section Aggregates with static bounds ! In all previous examples the aggregate was the initial (and immutable) value of a constant. If the aggregate initializes a variable, then code is generated for it as a combination of individual assignments and loops over the target object. The declarations ! ! @smallexample Cr_Var1 : One_Dim := (2, 5, 7, 11); Cr_Var2 : One_Dim := (others > -1); ! @end smallexample ! generate the equivalent of ! ! @smallexample Cr_Var1 (1) := 2; Cr_Var1 (2) := 3; Cr_Var1 (3) := 5; Cr_Var1 (4) := 11; ! for I in Cr_Var2'range loop Cr_Var2 (I) := =-1; end loop; ! @end smallexample ! @node Aggregates with non-static bounds ! @section Aggregates with non-static bounds ! If the bounds of the aggregate are not statically compatible with the bounds of the nominal subtype of the target, then constraint checks have to be generated on the bounds. For a multidimensional array, constraint checks may have to be applied to sub-arrays individually, if they do not have statically compatible subtypes. ! ! @node Aggregates in assignments statements ! @section Aggregates in assignments statements ! In general, aggregate assignment requires the construction of a temporary, and a copy from the temporary to the target of the assignment. This is because ! it is not always possible to convert the assignment into a series of individual component assignments. For example, consider the simple case: ! ! @smallexample ! @end smallexample A := (A(2), A(1)); ! This cannot be converted into: ! ! @smallexample A(1) := A(2); A(2) := A(1); ! @end smallexample ! So the aggregate has to be built first in a separate location, and then copied into the target. GNAT recognizes simple cases where this intermediate step is not required, and the assignments can be performed in place, directly into the target. The following sufficient criteria are applied: ! @enumerate ! @item The bounds of the aggregate are static, and the associations are static. ! @item The components of the aggregate are static constants, names of ! simple variables that are not renamings, or expressions not involving ! indexed components whose operands obey these rules. ! @end enumerate ! If any of these conditions are violated, the aggregate will be built in a temporary (created either by the front-end or the code generator) and then that temporary will be copied onto the target. ! ! ! @node Specialized Needs Annexes ! @chapter Specialized Needs Annexes @noindent ! Ada 95 defines a number of specialized needs annexes, which are not ! required in all implementations. However, as described in this chapter, ! GNAT implements all of these special needs annexes: ! @table @asis ! @item Systems Programming (Annex C) ! The Systems Programming Annex is fully implemented. ! @item Real-Time Systems (Annex D) ! The Real-Time Systems Annex is fully implemented. ! @item Distributed Systems (Annex E) ! Stub generation is fully implemented in the GNAT compiler. In addition, ! a complete compatible PCS is available as part of the GLADE system, ! a separate product. When the two ! products are used in conjunction, this annex is fully implemented. ! @item Information Systems (Annex F) ! The Information Systems annex is fully implemented. ! @item Numerics (Annex G) ! The Numerics Annex is fully implemented. ! @item Safety and Security (Annex H) ! The Safety and Security annex is fully implemented. ! @end table ! @node Compatibility Guide ! @chapter Compatibility Guide @noindent ! This chapter contains sections that describe compatibility issues between ! GNAT and other Ada 83 and Ada 95 compilation systems, to aid in porting ! applications developed in other Ada environments. ! @menu ! * Compatibility with Ada 83:: ! * Compatibility with DEC Ada 83:: ! * Compatibility with Other Ada 95 Systems:: ! * Representation Clauses:: ! @end menu ! @node Compatibility with Ada 83 ! @section Compatibility with Ada 83 ! @cindex Compatibility (between Ada 83 and Ada 95) @noindent ! Ada 95 is designed to be highly upwards compatible with Ada 83. In ! particular, the design intention is that the difficulties associated ! with moving from Ada 83 to Ada 95 should be no greater than those ! that occur when moving from one Ada 83 system to another. ! However, there are a number of points at which there are minor ! incompatibilities. The Ada 95 Annotated Reference Manual contains ! full details of these issues, ! and should be consulted for a complete treatment. ! In practice the ! following are the most likely issues to be encountered. ! @table @asis ! @item Character range ! The range of @code{Standard.Character} is now the full 256 characters of Latin-1, ! whereas in most Ada 83 implementations it was restricted to 128 characters. ! This may show up as compile time or runtime errors. The desirable fix is to ! adapt the program to accommodate the full character set, but in some cases ! it may be convenient to define a subtype or derived type of Character that ! covers only the restricted range. ! @cindex Latin-1 ! @item New reserved words ! The identifiers @code{abstract}, @code{aliased}, @code{protected}, ! @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95. ! Existing Ada 83 code using any of these identifiers must be edited to ! use some alternative name. ! @item Freezing rules ! The rules in Ada 95 are slightly different with regard to the point at ! which entities are frozen, and representation pragmas and clauses are ! not permitted past the freeze point. This shows up most typically in ! the form of an error message complaining that a representation item ! appears too late, and the appropriate corrective action is to move ! the item nearer to the declaration of the entity to which it refers. ! A particular case is that representation pragmas (including the ! extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure}), cannot ! be applied to a subprogram body. If necessary, a separate subprogram ! declaration must be introduced to which the pragma can be applied. ! @item Optional bodies for library packages ! In Ada 83, a package that did not require a package body was nevertheless ! allowed to have one. This lead to certain surprises in compiling large ! systems (situations in which the body could be unexpectedly ignored). In ! Ada 95, if a package does not require a body then it is not permitted to ! have a body. To fix this problem, simply remove a redundant body if it ! is empty, or, if it is non-empty, introduce a dummy declaration into the ! spec that makes the body required. One approach is to add a private part ! to the package declaration (if necessary), and define a parameterless ! procedure called Requires_Body, which must then be given a dummy ! procedure body in the package body, which then becomes required. ! @item @code{Numeric_Error} is now the same as @code{Constraint_Error} ! In Ada 95, the exception @code{Numeric_Error} is a renaming of @code{Constraint_Error}. ! This means that it is illegal to have separate exception handlers for ! the two exceptions. The fix is simply to remove the handler for the ! @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise ! @code{Constraint_Error} in place of @code{Numeric_Error} in all cases). ! @item Indefinite subtypes in generics ! In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String}) as ! the actual for a generic formal private type, but then the instantiation ! would be illegal if there were any instances of declarations of variables ! of this type in the generic body. In Ada 95, to avoid this clear violation ! of the contract model, the generic declaration clearly indicates whether ! or not such instantiations are permitted. If a generic formal parameter ! has explicit unknown discriminants, indicated by using @code{(<>)} after the ! type name, then it can be instantiated with indefinite types, but no ! variables can be declared of this type. Any attempt to declare a variable ! will result in an illegality at the time the generic is declared. If the ! @code{(<>)} notation is not used, then it is illegal to instantiate the generic ! with an indefinite type. This will show up as a compile time error, and ! the fix is usually simply to add the @code{(<>)} to the generic declaration. ! @end table ! All implementations of GNAT provide a switch that causes GNAT to operate ! in Ada 83 mode. In this mode, some but not all compatibility problems ! of the type described above are handled automatically. For example, the ! new Ada 95 protected keywords are not recognized in this mode. However, ! in practice, it is usually advisable to make the necessary modifications ! to the program to remove the need for using this switch. ! @node Compatibility with Other Ada 95 Systems ! @section Compatibility with Other Ada 95 Systems @noindent ! Providing that programs avoid the use of implementation dependent and ! implementation defined features of Ada 95, as documented in the Ada 95 ! reference manual, there should be a high degree of portability between ! GNAT and other Ada 95 systems. The following are specific items which ! have proved troublesome in moving GNAT programs to other Ada 95 ! compilers, but do not affect porting code to GNAT@. ! @table @asis ! @item Ada 83 Pragmas and Attributes ! Ada 95 compilers are allowed, but not required, to implement the missing ! Ada 83 pragmas and attributes that are no longer defined in Ada 95. ! GNAT implements all such pragmas and attributes, eliminating this as ! a compatibility concern, but some other Ada 95 compilers reject these ! pragmas and attributes. ! @item Special-needs Annexes ! GNAT implements the full set of special needs annexes. At the ! current time, it is the only Ada 95 compiler to do so. This means that ! programs making use of these features may not be portable to other Ada ! 95 compilation systems. ! @item Representation Clauses ! Some other Ada 95 compilers implement only the minimal set of ! representation clauses required by the Ada 95 reference manual. GNAT goes ! far beyond this minimal set, as described in the next section. ! @end table ! @node Representation Clauses ! @section Representation Clauses @noindent ! The Ada 83 reference manual was quite vague in describing both the minimal ! required implementation of representation clauses, and also their precise ! effects. The Ada 95 reference manual is much more explicit, but the minimal ! set of capabilities required in Ada 95 is quite limited. ! GNAT implements the full required set of capabilities described in the ! Ada 95 reference manual, but also goes much beyond this, and in particular ! an effort has been made to be compatible with existing Ada 83 usage to the ! greatest extent possible. ! A few cases exist in which Ada 83 compiler behavior is incompatible with ! requirements in the Ada 95 reference manual. These are instances of ! intentional or accidental dependence on specific implementation dependent ! characteristics of these Ada 83 compilers. The following is a list of ! the cases most likely to arise in existing legacy Ada 83 code. ! @table @asis ! @item Implicit Packing ! Some Ada 83 compilers allowed a Size specification to cause implicit ! packing of an array or record. This could cause expensive implicit ! conversions for change of representation in the presence of derived ! types, and the Ada design intends to avoid this possibility. ! Subsequent AI's were issued to make it clear that such implicit ! change of representation in response to a Size clause is inadvisable, ! and this recommendation is represented explicitly in the Ada 95 RM ! as implementation advice that is followed by GNAT@. ! The problem will show up as an error ! message rejecting the size clause. The fix is simply to provide ! the explicit pragma @code{Pack}, or for more fine tuned control, provide ! a Component_Size clause. ! @item Meaning of Size Attribute ! The Size attribute in Ada 95 for discrete types is defined as being the ! minimal number of bits required to hold values of the type. For example, ! on a 32-bit machine, the size of Natural will typically be 31 and not ! 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and ! some 32 in this situation. This problem will usually show up as a compile ! time error, but not always. It is a good idea to check all uses of the ! 'Size attribute when porting Ada 83 code. The GNAT specific attribute ! Object_Size can provide a useful way of duplicating the behavior of ! some Ada 83 compiler systems. ! @item Size of Access Types ! A common assumption in Ada 83 code is that an access type is in fact a pointer, ! and that therefore it will be the same size as a System.Address value. This ! assumption is true for GNAT in most cases with one exception. For the case of ! a pointer to an unconstrained array type (where the bounds may vary from one ! value of the access type to another), the default is to use a ``fat pointer'', ! which is represented as two separate pointers, one to the bounds, and one to ! the array. This representation has a number of advantages, including improved ! efficiency. However, it may cause some difficulties in porting existing Ada 83 ! code which makes the assumption that, for example, pointers fit in 32 bits on ! a machine with 32-bit addressing. ! To get around this problem, GNAT also permits the use of ``thin pointers'' for ! access types in this case (where the designated type is an unconstrained array ! type). These thin pointers are indeed the same size as a System.Address value. ! To specify a thin pointer, use a size clause for the type, for example: @smallexample ! type X is access all String; ! for X'Size use Standard'Address_Size; @end smallexample @noindent ! which will cause the type X to be represented using a single pointer. When using ! this representation, the bounds are right behind the array. This representation ! is slightly less efficient, and does not allow quite such flexibility in the ! use of foreign pointers or in using the Unrestricted_Access attribute to create ! pointers to non-aliased objects. But for any standard portable use of the access ! type it will work in a functionally correct manner and allow porting of existing ! code. Note that another way of forcing a thin pointer representation is to use ! a component size clause for the element size in an array, or a record ! representation clause for an access field in a record. @end table ! @node Compatibility with DEC Ada 83 ! @section Compatibility with DEC Ada 83 @noindent ! The VMS version of GNAT fully implements all the pragmas and attributes ! provided by DEC Ada 83, as well as providing the standard DEC Ada 83 ! libraries, including Starlet. In addition, data layouts and parameter ! passing conventions are highly compatible. This means that porting ! existing DEC Ada 83 code to GNAT in VMS systems should be easier than ! most other porting efforts. The following are some of the most ! significant differences between GNAT and DEC Ada 83. ! @table @asis ! @item Default floating-point representation ! In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83, ! it is VMS format. GNAT does implement the necessary pragmas ! (Long_Float, Float_Representation) for changing this default. ! @item System ! The package System in GNAT exactly corresponds to the definition in the ! Ada 95 reference manual, which means that it excludes many of the ! DEC Ada 83 extensions. However, a separate package Aux_DEC is provided ! that contains the additional definitions, and a special pragma, ! Extend_System allows this package to be treated transparently as an ! extension of package System. ! @item To_Address ! The definitions provided by Aux_DEC are exactly compatible with those ! in the DEC Ada 83 version of System, with one exception. DEC Ada provides ! the following declarations: @smallexample ! TO_ADDRESS(INTEGER) ! TO_ADDRESS(UNSIGNED_LONGWORD) ! TO_ADDRESS(universal_integer) @end smallexample @noindent ! The version of TO_ADDRESS taking a universal integer argument is in fact ! an extension to Ada 83 not strictly compatible with the reference manual. ! In GNAT, we are constrained to be exactly compatible with the standard, ! and this means we cannot provide this capability. In DEC Ada 83, the ! point of this definition is to deal with a call like: @smallexample ! TO_ADDRESS (16#12777#); @end smallexample @noindent ! Normally, according to the Ada 83 standard, one would expect this to be ! ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms ! of TO_ADDRESS@. However, in DEC Ada 83, there is no ambiguity, since the ! definition using universal_integer takes precedence. ! In GNAT, since the version with universal_integer cannot be supplied, it is ! not possible to be 100% compatible. Since there are many programs using ! numeric constants for the argument to TO_ADDRESS, the decision in GNAT was ! to change the name of the function in the UNSIGNED_LONGWORD case, so the ! declarations provided in the GNAT version of AUX_Dec are: @smallexample ! function To_Address (X : Integer) return Address; ! pragma Pure_Function (To_Address); ! function To_Address_Long (X : Unsigned_Longword) ! return Address; ! pragma Pure_Function (To_Address_Long); @end smallexample @noindent ! This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must ! change the name to TO_ADDRESS_LONG@. ! @item Task_Id values ! The Task_Id values assigned will be different in the two systems, and GNAT ! does not provide a specified value for the Task_Id of the environment task, ! which in GNAT is treated like any other declared task. @end table ! For full details on these and other less significant compatibility issues, ! see appendix E of the Digital publication entitled @cite{DEC Ada, Technical ! Overview and Comparison on DIGITAL Platforms}. ! For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and ! attributes are recognized, although only a subset of them can sensibly ! be implemented. The description of pragmas in this reference manual ! indicates whether or not they are applicable to non-VMS systems. @include fdl.texi @c GNU Free Documentation License --- 13055,14072 ---- and the type. In the context of an object declaration the code generated is generally simpler than in the case of an assignment. As a general rule, static component values and static subtypes also lead to simpler code. ! @node Static constant aggregates with static bounds ! @subsection Static constant aggregates with static bounds ! ! @noindent ! For the declarations: ! @smallexample @c ada type One_Dim is array (1..10) of integer; ar0 : constant One_Dim := ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 0); ! @end smallexample + @noindent GNAT generates no executable code: the constant ar0 is placed in static memory. The same is true for constant aggregates with named associations: ! ! @smallexample @c ada Cr1 : constant One_Dim := (4 => 16, 2 => 4, 3 => 9, 1=> 1); Cr3 : constant One_Dim := (others => 7777); ! @end smallexample ! ! @noindent ! The same is true for multidimensional constant arrays such as: ! ! @smallexample @c ada type two_dim is array (1..3, 1..3) of integer; Unit : constant two_dim := ( (1,0,0), (0,1,0), (0,0,1)); ! @end smallexample ! ! @noindent The same is true for arrays of one-dimensional arrays: the following are static: ! ! @smallexample @c ada ! type ar1b is array (1..3) of boolean; type ar_ar is array (1..3) of ar1b; ! None : constant ar1b := (others => false); -- fully static None2 : constant ar_ar := (1..3 => None); -- fully static ! @end smallexample ! ! @noindent However, for multidimensional aggregates with named associations, GNAT will generate assignments and loops, even if all associations are static. The following two declarations generate a loop for the first dimension, and individual component assignments for the second dimension: ! ! @smallexample @c ada Zero1: constant two_dim := (1..3 => (1..3 => 0)); ! Zero2: constant two_dim := (others => (others => 0)); ! @end smallexample ! @node Constant aggregates with an unconstrained nominal types ! @subsection Constant aggregates with an unconstrained nominal types ! ! @noindent ! In such cases the aggregate itself establishes the subtype, so that ! associations with @code{others} cannot be used. GNAT determines the ! bounds for the actual subtype of the aggregate, and allocates the ! aggregate statically as well. No code is generated for the following: ! ! @smallexample @c ada type One_Unc is array (natural range <>) of integer; Cr_Unc : constant One_Unc := (12,24,36); ! @end smallexample ! @node Aggregates with static bounds ! @subsection Aggregates with static bounds ! ! @noindent In all previous examples the aggregate was the initial (and immutable) value of a constant. If the aggregate initializes a variable, then code is generated for it as a combination of individual assignments and loops over the target object. The declarations ! ! @smallexample @c ada Cr_Var1 : One_Dim := (2, 5, 7, 11); Cr_Var2 : One_Dim := (others > -1); ! @end smallexample ! ! @noindent generate the equivalent of ! ! @smallexample @c ada Cr_Var1 (1) := 2; Cr_Var1 (2) := 3; Cr_Var1 (3) := 5; Cr_Var1 (4) := 11; ! for I in Cr_Var2'range loop Cr_Var2 (I) := =-1; end loop; ! @end smallexample ! @node Aggregates with non-static bounds ! @subsection Aggregates with non-static bounds ! ! @noindent If the bounds of the aggregate are not statically compatible with the bounds of the nominal subtype of the target, then constraint checks have to be generated on the bounds. For a multidimensional array, constraint checks may have to be applied to sub-arrays individually, if they do not have statically compatible subtypes. ! ! @node Aggregates in assignment statements ! @subsection Aggregates in assignment statements ! ! @noindent In general, aggregate assignment requires the construction of a temporary, and a copy from the temporary to the target of the assignment. This is because ! it is not always possible to convert the assignment into a series of individual component assignments. For example, consider the simple case: ! ! @smallexample @c ada A := (A(2), A(1)); ! @end smallexample ! ! @noindent This cannot be converted into: ! ! @smallexample @c ada A(1) := A(2); A(2) := A(1); ! @end smallexample ! ! @noindent So the aggregate has to be built first in a separate location, and then copied into the target. GNAT recognizes simple cases where this intermediate step is not required, and the assignments can be performed in place, directly into the target. The following sufficient criteria are applied: ! @itemize @bullet ! @item ! The bounds of the aggregate are static, and the associations are static. ! @item ! The components of the aggregate are static constants, names of ! simple variables that are not renamings, or expressions not involving ! indexed components whose operands obey these rules. ! @end itemize ! ! @noindent If any of these conditions are violated, the aggregate will be built in a temporary (created either by the front-end or the code generator) and then that temporary will be copied onto the target. ! ! ! @node Project File Reference ! @chapter Project File Reference @noindent ! This chapter describes the syntax and semantics of project files. ! Project files specify the options to be used when building a system. ! Project files can specify global settings for all tools, ! as well as tool-specific settings. ! See the chapter on project files in the GNAT Users guide for examples of use. ! @menu ! * Reserved Words:: ! * Lexical Elements:: ! * Declarations:: ! * Typed string declarations:: ! * Variables:: ! * Expressions:: ! * Attributes:: ! * Project Attributes:: ! * Attribute References:: ! * External Values:: ! * Case Construction:: ! * Packages:: ! * Package Renamings:: ! * Projects:: ! * Project Extensions:: ! * Project File Elaboration:: ! @end menu ! @node Reserved Words ! @section Reserved Words ! @noindent ! All Ada95 reserved words are reserved in project files, and cannot be used ! as variable names or project names. In addition, the following are ! also reserved in project files: ! @itemize ! @item @code{extends} ! @item @code{external} ! @item @code{project} ! @end itemize ! @node Lexical Elements ! @section Lexical Elements @noindent ! Rules for identifiers are the same as in Ada95. Identifiers ! are case-insensitive. Strings are case sensitive, except where noted. ! Comments have the same form as in Ada95. ! @noindent ! Syntax: ! @smallexample ! simple_name ::= ! identifier ! ! name ::= ! simple_name @{. simple_name@} ! @end smallexample ! ! @node Declarations ! @section Declarations @noindent ! Declarations introduce new entities that denote types, variables, attributes, ! and packages. Some declarations can only appear immediately within a project ! declaration. Others can appear within a project or within a package. ! Syntax: ! @smallexample ! declarative_item ::= ! simple_declarative_item | ! typed_string_declaration | ! package_declaration ! simple_declarative_item ::= ! variable_declaration | ! typed_variable_declaration | ! attribute_declaration | ! case_construction ! @end smallexample ! @node Typed string declarations ! @section Typed string declarations ! @noindent ! Typed strings are sequences of string literals. Typed strings are the only ! named types in project files. They are used in case constructions, where they ! provide support for conditional attribute definitions. ! Syntax: ! @smallexample ! typed_string_declaration ::= ! @b{type} _simple_name @b{is} ! ( string_literal @{, string_literal@} ); ! @end smallexample ! @noindent ! A typed string declaration can only appear immediately within a project ! declaration. ! All the string literals in a typed string declaration must be distinct. ! @node Variables ! @section Variables ! @noindent ! Variables denote values, and appear as constituents of expressions. ! @smallexample ! typed_variable_declaration ::= ! simple_name : name := string_expression ; ! ! variable_declaration ::= ! simple_name := expression; ! @end smallexample @noindent ! The elaboration of a variable declaration introduces the variable and ! assigns to it the value of the expression. The name of the variable is ! available after the assignment symbol. ! @noindent ! A typed_variable can only be declare once. ! @noindent ! a non typed variable can be declared multiple times. ! @noindent ! Before the completion of its first declaration, the value of variable ! is the null string. ! @node Expressions ! @section Expressions @noindent ! An expression is a formula that defines a computation or retrieval of a value. ! In a project file the value of an expression is either a string or a list ! of strings. A string value in an expression is either a literal, the current ! value of a variable, an external value, an attribute reference, or a ! concatenation operation. ! Syntax: ! @smallexample ! expression ::= ! term @{& term@} ! term ::= ! string_literal | ! string_list | ! name | ! external_value | ! attribute_reference ! string_literal ::= ! (same as Ada) ! string_list ::= ! ( expression @{ , expression @} ) ! @end smallexample ! @subsection Concatenation ! @noindent ! The following concatenation functions are defined: ! ! @smallexample @c ada ! function "&" (X : String; Y : String) return String; ! function "&" (X : String_List; Y : String) return String_List; ! function "&" (X : String_List; Y : String_List) return String_List; ! @end smallexample + @node Attributes + @section Attributes + + @noindent + An attribute declaration defines a property of a project or package. This + property can later be queried by means of an attribute reference. + Attribute values are strings or string lists. + + Some attributes are associative arrays. These attributes are mappings whose + domain is a set of strings. These attributes are declared one association + at a time, by specifying a point in the domain and the corresponding image + of the attribute. They may also be declared as a full associative array, + getting the same associations as the corresponding attribute in an imported + or extended project. + + Attributes that are not associative arrays are called simple attributes. + + Syntax: @smallexample ! attribute_declaration ::= ! full_associative_array_declaration | ! @b{for} attribute_designator @b{use} expression ; ! ! full_associative_array_declaration ::= ! @b{for} simple_name @b{use} ! simple_name [ . simple_Name ] ' simple_name ; ! ! attribute_designator ::= ! simple_name | ! simple_name ( string_literal ) @end smallexample @noindent ! Some attributes are project-specific, and can only appear immediately within ! a project declaration. Others are package-specific, and can only appear within ! the proper package. ! ! The expression in an attribute definition must be a string or a string_list. ! The string literal appearing in the attribute_designator of an associative ! array attribute is case-insensitive. ! ! @node Project Attributes ! @section Project Attributes ! ! @noindent ! The following attributes apply to a project. All of them are simple ! attributes. ! ! @table @code ! @item Object_Dir ! Expression must be a path name. The attribute defines the ! directory in which the object files created by the build are to be placed. If ! not specified, object files are placed in the project directory. ! ! @item Exec_Dir ! Expression must be a path name. The attribute defines the ! directory in which the executables created by the build are to be placed. ! If not specified, executables are placed in the object directory. ! ! @item Source_Dirs ! Expression must be a list of path names. The attribute ! defines the directories in which the source files for the project are to be ! found. If not specified, source files are found in the project directory. ! ! @item Source_Files ! Expression must be a list of file names. The attribute ! defines the individual files, in the project directory, which are to be used ! as sources for the project. File names are path_names that contain no directory ! information. If the project has no sources the attribute must be declared ! explicitly with an empty list. ! ! @item Source_List_File ! Expression must a single path name. The attribute ! defines a text file that contains a list of source file names to be used ! as sources for the project ! ! @item Library_Dir ! Expression must be a path name. The attribute defines the ! directory in which a library is to be built. The directory must exist, must ! be distinct from the project's object directory, and must be writable. ! ! @item Library_Name ! Expression must be a string that is a legal file name, ! without extension. The attribute defines a string that is used to generate ! the name of the library to be built by the project. ! ! @item Library_Kind ! Argument must be a string value that must be one of the ! following @code{"static"}, @code{"dynamic"} or @code{"relocatable"}. This ! string is case-insensitive. If this attribute is not specified, the library is ! a static library. Otherwise, the library may be dynamic or relocatable. This ! distinction is operating-system dependent. ! ! @item Library_Version ! Expression must be a string value whose interpretation ! is platform dependent. On UNIX, it is used only for dynamic/relocatable ! libraries as the internal name of the library (the @code{"soname"}). If the ! library file name (built from the @code{Library_Name}) is different from the ! @code{Library_Version}, then the library file will be a symbolic link to the ! actual file whose name will be @code{Library_Version}. ! ! @item Library_Interface ! Expression must be a string list. Each element of the string list ! must designate a unit of the project. ! If this attribute is present in a Library Project File, then the project ! file is a Stand-alone Library_Project_File. ! ! @item Library_Auto_Init ! Expression must be a single string "true" or "false", case-insensitive. ! If this attribute is present in a Stand-alone Library Project File, ! it indicates if initialization is automatic when the dynamic library ! is loaded. ! ! @item Library_Options ! Expression must be a string list. Indicates additional switches that ! are to be used when building a shared library. ! ! @item Library_GCC ! Expression must be a single string. Designates an alternative to "gcc" ! for building shared libraries. ! ! @item Library_Src_Dir ! Expression must be a path name. The attribute defines the ! directory in which the sources of the interfaces of a Stand-alone Library will ! be copied. The directory must exist, must be distinct from the project's ! object directory and source directories, and must be writable. ! ! @item Main ! Expression must be a list of strings that are legal file names. ! These file names designate existing compilation units in the source directory ! that are legal main subprograms. ! ! When a project file is elaborated, as part of the execution of a gnatmake ! command, one or several executables are built and placed in the Exec_Dir. ! If the gnatmake command does not include explicit file names, the executables ! that are built correspond to the files specified by this attribute. ! ! @item Main_Language ! This is a simple attribute. Its value is a string that specifies the ! language of the main program. ! ! @item Languages ! Expression must be a string list. Each string designates ! a programming language that is known to GNAT. The strings are case-insensitive. ! ! @item Locally_Removed_Files ! This attribute is legal only in a project file that extends another. ! Expression must be a list of strings that are legal file names. ! Each file name must designate a source that would normally be inherited ! by the current project file. It cannot designate an immediate source that is ! not inherited. Each of the source files in the list are not considered to ! be sources of the project file: they are not inherited. @end table ! @node Attribute References ! @section Attribute References @noindent ! Attribute references are used to retrieve the value of previously defined ! attribute for a package or project. ! Syntax: ! @smallexample ! attribute_reference ::= ! attribute_prefix ' simple_name [ ( string_literal ) ] ! attribute_prefix ::= ! @b{project} | ! simple_name . package_identifier ! @end smallexample ! @noindent ! If an attribute has not been specified for a given package or project, its ! value is the null string or the empty list. ! @node External Values ! @section External Values + @noindent + An external value is an expression whose value is obtained from the command + that invoked the processing of the current project file (typically a + gnatmake command). + + Syntax: @smallexample ! external_value ::= ! @b{external} ( string_literal [, string_literal] ) @end smallexample @noindent ! The first string_literal is the string to be used on the command line or ! in the environment to specify the external value. The second string_literal, ! if present, is the default to use if there is no specification for this ! external value either on the command line or in the environment. ! ! @node Case Construction ! @section Case Construction ! ! @noindent ! A case construction supports attribute declarations that depend on the value of ! a previously declared variable. + Syntax: @smallexample ! case_construction ::= ! @b{case} name @b{is} ! @{case_item@} ! @b{end case} ; ! ! case_item ::= ! @b{when} discrete_choice_list => ! @{case_construction | attribute_declaration@} ! ! discrete_choice_list ::= ! string_literal @{| string_literal@} | ! @b{others} @end smallexample @noindent ! All choices in a choice list must be distinct. The choice lists of two ! distinct alternatives must be disjoint. Unlike Ada, the choice lists of all ! alternatives do not need to include all values of the type. An @code{others} ! choice must appear last in the list of alternatives. ! @node Packages ! @section Packages ! ! @noindent ! A package provides a grouping of variable declarations and attribute ! declarations to be used when invoking various GNAT tools. The name of ! the package indicates the tool(s) to which it applies. ! Syntax: @smallexample ! package_declaration ::= ! package_specification | package_renaming ! package_specification ::= ! @b{package} package_identifier @b{is} ! @{simple_declarative_item@} ! @b{end} package_identifier ; ! ! package_identifier ::= ! @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} | ! @code{Linker} | @code{Finder} | @code{Cross_Reference} | ! @code{gnatls} | @code{IDE} | @code{Pretty_Printer} @end smallexample + @subsection Package Naming + @noindent ! The attributes of a @code{Naming} package specifies the naming conventions ! that apply to the source files in a project. When invoking other GNAT tools, ! they will use the sources in the source directories that satisfy these ! naming conventions. ! The following attributes apply to a @code{Naming} package: ! ! @table @code ! @item Casing ! This is a simple attribute whose value is a string. Legal values of this ! string are @code{"lowercase"}, @code{"uppercase"} or @code{"mixedcase"}. ! These strings are themselves case insensitive. ! ! @noindent ! If @code{Casing} is not specified, then the default is @code{"lowercase"}. ! ! @item Dot_Replacement ! This is a simple attribute whose string value satisfies the following ! requirements: ! ! @itemize @bullet ! @item It must not be empty ! @item It cannot start or end with an alphanumeric character ! @item It cannot be a single underscore ! @item It cannot start with an underscore followed by an alphanumeric ! @item It cannot contain a dot @code{'.'} if longer than one character ! @end itemize ! ! @noindent ! If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. ! ! @item Spec_Suffix ! This is an associative array attribute, defined on language names, ! whose image is a string that must satisfy the following ! conditions: ! ! @itemize @bullet ! @item It must not be empty ! @item It cannot start with an alphanumeric character ! @item It cannot start with an underscore followed by an alphanumeric character ! @end itemize ! ! @noindent ! For Ada, the attribute denotes the suffix used in file names that contain ! library unit declarations, that is to say units that are package and ! subprogram declarations. If @code{Spec_Suffix ("Ada")} is not ! specified, then the default is @code{".ads"}. ! ! For C and C++, the attribute denotes the suffix used in file names that ! contain prototypes. ! ! @item Body_Suffix ! This is an associative array attribute defined on language names, ! whose image is a string that must satisfy the following ! conditions: ! ! @itemize @bullet ! @item It must not be empty ! @item It cannot start with an alphanumeric character ! @item It cannot start with an underscore followed by an alphanumeric character ! @item It cannot be a suffix of @code{Spec_Suffix} ! @end itemize ! ! @noindent ! For Ada, the attribute denotes the suffix used in file names that contain ! library bodies, that is to say units that are package and subprogram bodies. ! If @code{Body_Suffix ("Ada")} is not specified, then the default is ! @code{".adb"}. ! ! For C and C++, the attribute denotes the suffix used in file names that contain ! source code. ! ! @item Separate_Suffix ! This is a simple attribute whose value satisfies the same conditions as ! @code{Body_Suffix}. ! ! This attribute is specific to Ada. It denotes the suffix used in file names ! that contain separate bodies. If it is not specified, then it defaults to same ! value as @code{Body_Suffix ("Ada")}. ! ! @item Spec ! This is an associative array attribute, specific to Ada, defined over ! compilation unit names. The image is a string that is the name of the file ! that contains that library unit. The file name is case sensitive if the ! conventions of the host operating system require it. ! ! @item Body ! This is an associative array attribute, specific to Ada, defined over ! compilation unit names. The image is a string that is the name of the file ! that contains the library unit body for the named unit. The file name is case ! sensitive if the conventions of the host operating system require it. ! ! @item Specification_Exceptions ! This is an associative array attribute defined on language names, ! whose value is a list of strings. ! ! This attribute is not significant for Ada. ! ! For C and C++, each string in the list denotes the name of a file that ! contains prototypes, but whose suffix is not necessarily the ! @code{Spec_Suffix} for the language. ! ! @item Implementation_Exceptions ! This is an associative array attribute defined on language names, ! whose value is a list of strings. ! ! This attribute is not significant for Ada. ! ! For C and C++, each string in the list denotes the name of a file that ! contains source code, but whose suffix is not necessarily the ! @code{Body_Suffix} for the language. @end table ! The following attributes of package @code{Naming} are obsolescent. They are ! kept as synonyms of other attributes for compatibility with previous versions ! of the Project Manager. ! @table @code ! @item Specification_Suffix ! This is a synonym of @code{Spec_Suffix}. ! ! @item Implementation_Suffix ! This is a synonym of @code{Body_Suffix}. ! ! @item Specification ! This is a synonym of @code{Spec}. ! ! @item Implementation ! This is a synonym of @code{Body}. ! @end table ! ! @subsection package Compiler ! ! @noindent ! The attributes of the @code{Compiler} package specify the compilation options ! to be used by the underlying compiler. ! ! @table @code ! @item Default_Switches ! This is an associative array attribute. Its ! domain is a set of language names. Its range is a string list that ! specifies the compilation options to be used when compiling a component ! written in that language, for which no file-specific switches have been ! specified.. ! ! @item Switches ! This is an associative array attribute. Its domain is ! a set of file names. Its range is a string list that specifies the ! compilation options to be used when compiling the named file. If a file ! is not specified in the Switches attribute, it is compiled with the ! settings specified by Default_Switches. ! ! @item Local_Configuration_Pragmas. ! This is a simple attribute, whose ! value is a path name that designates a file containing configuration pragmas ! to be used for all invocations of the compiler for immediate sources of the ! project. ! ! @item Executable ! This is an associative array attribute. Its domain is ! a set of main source file names. Its range is a simple string that specifies ! the executable file name to be used when linking the specified main source. ! If a main source is not specified in the Executable attribute, the executable ! file name is deducted from the main source file name. ! @end table ! ! @subsection package Builder ! ! @noindent ! The attributes of package @code{Builder} specify the compilation, binding, and ! linking options to be used when building an executable for a project. The ! following attributes apply to package @code{Builder}: ! ! @table @code ! @item Default_Switches ! As above. ! ! @item Switches ! As above. ! ! @item Global_Configuration_Pragmas ! This is a simple attribute, whose ! value is a path name that designates a file that contains configuration pragmas ! to be used in every build of an executable. If both local and global ! configuration pragmas are specified, a compilation makes use of both sets. ! ! @item Executable ! This is an associative array attribute, defined over ! compilation unit names. The image is a string that is the name of the ! executable file corresponding to the main source file index. ! This attribute has no effect if its value is the empty string. ! ! @item Executable_Suffix ! This is a simple attribute whose value is a suffix to be added to ! the executables that don't have an attribute Executable specified. ! @end table ! ! @subsection package Gnatls ! ! @noindent ! The attributes of package @code{Gnatls} specify the tool options to be used ! when invoking the library browser @command{gnatls}. ! The following attributes apply to package @code{Gnatls}: ! ! @table @code ! @item Switches ! As above. ! @end table ! ! @subsection package Binder ! ! @noindent ! The attributes of package @code{Binder} specify the options to be used ! when invoking the binder in the construction of an executable. ! The following attributes apply to package @code{Binder}: ! ! @table @code ! @item Default_Switches ! As above. ! @item Switches ! As above. ! @end table ! ! @subsection package Linker ! ! @noindent ! The attributes of package @code{Linker} specify the options to be used when ! invoking the linker in the construction of an executable. ! The following attributes apply to package @code{Linker}: ! ! @table @code ! @item Default_Switches ! As above ! @item Switches ! As above. ! @end table ! ! @subsection package Cross_Reference ! ! @noindent ! The attributes of package @code{Cross_Reference} specify the tool options ! to be used ! when invoking the library tool @command{gnatxref}. ! The following attributes apply to package @code{Cross_Reference}: ! ! @table @code ! @item Default_Switches ! As above. ! @item Switches ! As above. ! @end table ! ! @subsection package Finder ! ! @noindent ! The attributes of package @code{Finder} specify the tool options to be used ! when invoking the search tool @command{gnatfind}. ! The following attributes apply to package @code{Finder}: ! ! @table @code ! @item Default_Switches ! As above. ! @item Switches ! As above. ! @end table ! ! @subsection package Pretty_Printer ! ! @noindent ! The attributes of package @code{Pretty_Printer} ! specify the tool options to be used ! when invoking the formatting tool @command{gnatpp}. ! The following attributes apply to package @code{Pretty_Printer}: ! ! @table @code ! @item Default_switches ! As above. ! @item Switches ! As above. ! @end table ! ! @subsection package IDE ! ! @noindent ! The attributes of package @code{IDE} specify the options to be used when using ! an Integrated Development Environment such as @command{GPS}. ! ! @table @code ! @item Remote_Host ! This is a simple attribute. Its value is a string that designates the remote ! host in a cross-compilation environment, to be used for remote compilation and ! debugging. This field should not be specified when running on the local ! machine. ! ! @item Program_Host ! This is a simple attribute. Its value is a string that specifies the ! name of IP address of the embedded target in a cross-compilation environment, ! on which the program should execute. ! ! @item Communication_Protocol ! This is a simple string attribute. Its value is the name of the protocol ! to use to communicate with the target in a cross-compilation environment, ! e.g. @code{"wtx"} or @code{"vxworks"}. ! ! @item Compiler_Command ! This is an associative array attribute, whose domain is a language name. Its ! value is string that denotes the command to be used to invoke the compiler. ! The value of @code{Compiler_Command ("Ada")} is expected to be compatible with ! gnatmake, in particular in the handling of switches. ! ! @item Debugger_Command ! This is simple attribute, Its value is a string that specifies the name of ! the debugger to be used, such as gdb, powerpc-wrs-vxworks-gdb or gdb-4. ! ! @item Default_Switches ! This is an associative array attribute. Its indexes are the name of the ! external tools that the GNAT Programming System (GPS) is supporting. Its ! value is a list of switches to use when invoking that tool. ! ! @item Gnatlist ! This is a simple attribute. Its value is a string that specifies the name ! of the @command{gnatls} utility to be used to retrieve information about the ! predefined path; e.g., @code{"gnatls"}, @code{"powerpc-wrs-vxworks-gnatls"}. ! ! @item VCS_Kind ! This is a simple atribute. Is value is a string used to specify the ! Version Control System (VCS) to be used for this project, e.g CVS, RCS ! ClearCase or Perforce. ! ! @item VCS_File_Check ! This is a simple attribute. Its value is a string that specifies the ! command used by the VCS to check the validity of a file, either ! when the user explicitly asks for a check, or as a sanity check before ! doing the check-in. ! ! @item VCS_Log_Check ! This is a simple attribute. Its value is a string that specifies ! the command used by the VCS to check the validity of a log file. ! ! @end table ! ! @node Package Renamings ! @section Package Renamings ! ! @noindent ! A package can be defined by a renaming declaration. The new package renames ! a package declared in a different project file, and has the same attributes ! as the package it renames. ! Syntax: ! @smallexample ! package_renaming ::== ! @b{package} package_identifier @b{renames} ! simple_name.package_identifier ; ! @end smallexample ! ! @noindent ! The package_identifier of the renamed package must be the same as the ! package_identifier. The project whose name is the prefix of the renamed ! package must contain a package declaration with this name. This project ! must appear in the context_clause of the enclosing project declaration, ! or be the parent project of the enclosing child project. ! ! @node Projects ! @section Projects ! ! @noindent ! A project file specifies a set of rules for constructing a software system. ! A project file can be self-contained, or depend on other project files. ! Dependencies are expressed through a context clause that names other projects. ! ! Syntax: ! ! @smallexample ! project ::= ! context_clause project_declaration ! ! project_declaration ::= ! simple_project_declaration | project_extension ! ! simple_project_declaration ::= ! @b{project} simple_name @b{is} ! @{declarative_item@} ! @b{end} simple_name; ! ! context_clause ::= ! @{with_clause@} ! ! with_clause ::= ! [@b{limited}] @b{with} path_name @{ , path_name @} ; ! ! path_name ::= ! string_literal ! @end smallexample ! ! @noindent ! A path name denotes a project file. A path name can be absolute or relative. ! An absolute path name includes a sequence of directories, in the syntax of ! the host operating system, that identifies uniquely the project file in the ! file system. A relative path name identifies the directory that contains the ! project file, relative to the directory that contains the current project. ! Path names are case sensitive if file names in the host operating system ! are case sensitive. ! ! A given project name can appear only once in a context_clause. ! ! It is illegal for a project imported by a context clause to refer, directly ! or indirectly, to the project in which this context clause appears (the ! dependency graph cannot contain cycles), except when one of the with_clause ! in the cycle is a @code{limited with}. ! ! @node Project Extensions ! @section Project Extensions ! ! @noindent ! A project extension introduces a new project, which inherits the declarations ! of another project. ! Syntax: ! @smallexample ! ! project_extension ::= ! @b{project} simple_name @b{extends} path_name @b{is} ! @{declarative_item@} ! @b{end} simple_name; ! @end smallexample ! ! @noindent ! The project extension declares a child project. The child project inherits ! all the declarations and all the files of the parent project, These inherited ! declaration can be overridden in the child project, by means of suitable ! declarations. ! ! @node Project File Elaboration ! @section Project File Elaboration ! ! @noindent ! A project file is processed as part of the invocation of a gnat tool that ! uses the project option. Elaboration of the process file consists in the ! sequential elaboration of all its declarations. The computed values of ! attributes and variables in the project are then used to establish the ! environment in which the gnat tool will execute. @include fdl.texi @c GNU Free Documentation License diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat-style.texi gcc-3.4.1/gcc/ada/gnat-style.texi *** gcc-3.4.0/gcc/ada/gnat-style.texi 2003-04-24 17:54:04.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat-style.texi 2004-06-09 09:20:43.000000000 +0000 *************** *** 7,14 **** @c o @c G N A T C O D I N G S T Y L E o @c o ! @c o ! @c Copyright (C) 1992-2001 Ada Core Technologies, Inc. o @c o @c GNAT is free software; you can redistribute it and/or modify it under o @c terms of the GNU General Public License as published by the Free Soft- o --- 7,13 ---- @c o @c G N A T C O D I N G S T Y L E o @c o ! @c Copyright (C) 1992-2004 Ada Core Technologies, Inc. o @c o @c GNAT is free software; you can redistribute it and/or modify it under o @c terms of the GNU General Public License as published by the Free Soft- o *************** *** 24,30 **** --- 23,33 ---- @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo @setfilename gnat-style.info + @settitle GNAT Coding Style + @setchapternewpage odd + + @dircategory Programming @direntry * gnat-style: (gnat-style). GNAT Coding Style *************** *** 35,58 **** @end macro @c %**end of header - @ifinfo - @center GNAT Coding Style - - @center A guide for GNAT developers - Copyright (C) 1992-2001 Ada Core Technologies, Inc. - @end ifinfo - @titlepage @sp 10 @title GNAT Coding Style ! @subtitle A guide for GNAT developers @author Ada Core Technologies, Inc. @end titlepage @raisesections @node Top, General, , (dir) @comment node-name, next, previous, up @menu * General:: * Lexical Elements:: --- 38,96 ---- @end macro @c %**end of header @titlepage @sp 10 @title GNAT Coding Style ! @flushright ! @titlefont{A Guide for GNAT Developers} ! @end flushright ! @sp 2 ! @subtitle GNAT, The GNU Ada 95 Compiler ! @author Ada Core Technologies, Inc. + + @page + @vskip 0pt plus 1filll + + Copyright @copyright{} 1995-2003, Free Software Foundation + + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.1 + or any later version published by the Free Software Foundation; + with the Invariant Sections being ``GNU Free Documentation License'', with the + Front-Cover Texts being + ``GNAT Coding Style'' and ``A Guide for GNAT Developers'', + and with no Back-Cover Texts. + A copy of the license is included in the section entitled + ``GNU Free Documentation License''. @end titlepage + @raisesections @node Top, General, , (dir) @comment node-name, next, previous, up + @ifnottex + @noindent + GNAT Coding Style@* + A Guide for GNAT Developers + @sp 2 + @noindent + GNAT, The GNU Ada 95 Compiler@* + + @noindent + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.1 + or any later version published by the Free Software Foundation; + with the Invariant Sections being ``GNU Free Documentation License'', with the + Front-Cover Texts being + ``GNAT Coding Style'' and ``A Guide for GNAT Developers'' + and with no Back-Cover Texts. + A copy of the license is included in the section entitled + ``GNU Free Documentation License''. + @end ifnottex + + @menu * General:: * Lexical Elements:: *************** *** 62,67 **** --- 100,107 ---- * Subprograms:: * Packages:: * Program Structure:: + * GNU Free Documentation License:: + * Index:: @end menu @c ------------------------------------------------------------------------- *************** readability of the code. This document *** 75,105 **** maintain this consistent style, while having a large group of developers work on the compiler. - @noindent For the coding style in the C parts of the compiler and run time, see the GNU Coding Guidelines. ! @noindent ! This document is structured after the Ada Reference manual. Those familiar with that document should be able to quickly lookup style rules for particular constructs. @c ------------------------------------------------------------------------- @node Lexical Elements, Declarations and Types, General, Top @section Lexical Elements @c ------------------------------------------------------------------------- @subsection Character Set and Separators @c ------------------------------------------------------------------------- @itemize @bullet @item The character set used should be plain 7-bit ASCII@. The only separators allowed are space and the end-of-line sequence. ! No other control character or format effector (such as HT, VT, FF) should be used. ! The normal end-of-line sequence is used, which may be LF, CR/LF or CR, ! depending on the host system. An optional SUB (16#1A#) may be present as the last character in the file on hosts using that character as file terminator. @item --- 115,154 ---- maintain this consistent style, while having a large group of developers work on the compiler. For the coding style in the C parts of the compiler and run time, see the GNU Coding Guidelines. ! This document is structured after the @cite{Ada Reference Manual}. Those familiar with that document should be able to quickly lookup style rules for particular constructs. + @c ------------------------------------------------------------------------- @node Lexical Elements, Declarations and Types, General, Top @section Lexical Elements @c ------------------------------------------------------------------------- + @cindex Lexical elements @subsection Character Set and Separators @c ------------------------------------------------------------------------- + @cindex Character set + @cindex ASCII + @cindex Separators + @cindex End-of-line + @cindex Line length + @cindex Indentation @itemize @bullet @item The character set used should be plain 7-bit ASCII@. The only separators allowed are space and the end-of-line sequence. ! No other control character or format effector (such as @code{HT}, ! @code{VT}, @code{FF}) should be used. ! The normal end-of-line sequence is used, which may be ! @code{LF}, @code{CR/LF} or @code{CR}, ! depending on the host system. An optional @code{SUB} ! (@code{16#1A#}) may be present as the last character in the file on hosts using that character as file terminator. @item *************** separator. *** 113,136 **** Lines must not have trailing blanks. @item ! Indentation is 3 characters per level for if statements, loops, case ! statements. For exact information on required spacing between lexical elements, see file @file{style.adb}. ! @end itemize @subsection Identifiers @c ------------------------------------------------------------------------- @itemize @bullet @item Identifiers will start with an upper case letter, and each letter following ! an underscore will be upper case. Short acronyms may be all upper case. All other letters are lower case. An exception is for identifiers matching a foreign language. In particular, we use all lower case where appropriate for C@. @item Use underscores to separate words in an identifier. @item Try to limit your use of abbreviations in identifiers. It is ok to make a few abbreviations, explain what they mean, and then --- 162,192 ---- Lines must not have trailing blanks. @item ! Indentation is 3 characters per level for @code{if} statements, loops, and ! @code{case} statements. ! For exact information on required spacing between lexical elements, see file @file{style.adb}. ! @cindex @file{style.adb} file @end itemize + @subsection Identifiers @c ------------------------------------------------------------------------- @itemize @bullet + @cindex Identifiers + @item Identifiers will start with an upper case letter, and each letter following ! an underscore will be upper case. ! @cindex Casing (for identifiers) ! Short acronyms may be all upper case. All other letters are lower case. An exception is for identifiers matching a foreign language. In particular, we use all lower case where appropriate for C@. @item Use underscores to separate words in an identifier. + @cindex Underscores @item Try to limit your use of abbreviations in identifiers. It is ok to make a few abbreviations, explain what they mean, and then *************** example is the @code{ALI} word which sta *** 139,160 **** Information and is by convention always written in upper-case when used in entity names. ! @smallexample procedure Find_ALI_Files; @end smallexample @item ! Don't use the variable @samp{I}, use @samp{J} instead, @samp{I} is too ! easily mixed up with @samp{1} in some fonts. Similarly don't use the ! variable @samp{O}, which is too easily mixed up with the number @samp{0}. @end itemize @subsection Numeric Literals @c ------------------------------------------------------------------------- @itemize @bullet @item Numeric literals should include underscores where helpful for readability. @smallexample 1_000_000 --- 195,219 ---- Information and is by convention always written in upper-case when used in entity names. ! @smallexample @c adanocomment procedure Find_ALI_Files; @end smallexample @item ! Don't use the variable name @code{I}, use @code{J} instead; @code{I} is too ! easily confused with @code{1} in some fonts. Similarly don't use the ! variable @code{O}, which is too easily mistaken for the number @code{0}. @end itemize @subsection Numeric Literals @c ------------------------------------------------------------------------- + @cindex Numeric literals + @itemize @bullet @item Numeric literals should include underscores where helpful for readability. + @cindex Underscores @smallexample 1_000_000 *************** readability. *** 165,241 **** @subsection Reserved Words @c ------------------------------------------------------------------------- @itemize @bullet @item Reserved words use all lower case. ! @smallexample return else @end smallexample @item ! The words @samp{Access}, @samp{Delta} and @samp{Digits} are capitalized when used as @syntax{attribute_designator}. @end itemize @subsection Comments @c ------------------------------------------------------------------------- @itemize @bullet @item ! Comment start with @samp{-- } (i.e.@: @samp{--} followed by two spaces). The only exception to this rule (i.e.@: one space is tolerated) is when the ! comment ends with @samp{ --}. ! It also accepted to have only one space between @samp{--} and the start of the comment when the comment is at the end of a line, after some Ada code. @item Every sentence in a comment should start with an upper-case letter (including the first letter of the comment). @item When declarations are commented with ``hanging'' comments, i.e.@: comments after the declaration, there is no blank line before the comment, and if it is absolutely necessary to have blank lines within ! the comments these blank lines @emph{do} have a @samp{--} (unlike the normal rule, which is to use entirely blank lines for separating ! comment paragraphs). The comment start at same level of indentation ! as code they are commenting. ! @smallexample z : Integer; ! -- @r{Integer value for storing value of} z -- ! -- @r{The previous line was a blank line.} @end smallexample @item ! Comments that are dubious or incomplete or comment on possibly ! wrong or incomplete code should be preceded or followed by @samp{???}@. @item ! Comments in a subprogram body must generally be surrounded by blank lines, ! except after a @samp{begin}: ! @smallexample begin ! -- @r{Comment for the next statement} A := 5; ! -- @r{Comment for the B statement} B := 6; @end smallexample @item In sequences of statements, comments at the end of the lines should be aligned. ! @smallexample ! My_Identifier := 5; -- @r{First comment} ! Other_Id := 6; -- @r{Second comment} @end smallexample @item --- 224,312 ---- @subsection Reserved Words @c ------------------------------------------------------------------------- + @cindex Reserved words + @itemize @bullet @item Reserved words use all lower case. + @cindex Casing (for reserved words) ! @smallexample @c adanocomment return else @end smallexample @item ! The words @code{Access}, @code{Delta} and @code{Digits} are capitalized when used as @syntax{attribute_designator}. @end itemize @subsection Comments @c ------------------------------------------------------------------------- + @cindex Comments @itemize @bullet @item ! A comment starts with @code{--} followed by two spaces). The only exception to this rule (i.e.@: one space is tolerated) is when the ! comment ends with a single space followed by @code{--}. ! It is also acceptable to have only one space between @code{--} and the start of the comment when the comment is at the end of a line, after some Ada code. @item Every sentence in a comment should start with an upper-case letter (including the first letter of the comment). + @cindex Casing (in comments) @item When declarations are commented with ``hanging'' comments, i.e.@: comments after the declaration, there is no blank line before the comment, and if it is absolutely necessary to have blank lines within ! the comments these blank lines @emph{do} have a @code{--} (unlike the normal rule, which is to use entirely blank lines for separating ! comment paragraphs). The comment starts at same level of indentation ! as code it is commenting. ! @cindex Blank lines (in comments) ! @cindex Indentation ! @smallexample @c adanocomment z : Integer; ! -- Integer value for storing value of z -- ! -- The previous line was a blank line. @end smallexample @item ! Comments that are dubious or incomplete, or that comment on possibly ! wrong or incomplete code, should be preceded or followed by @code{???}@. @item ! Comments in a subprogram body must generally be surrounded by blank lines. ! An exception is a comment that follows a line containing a single keyword ! (@code{begin}, @code{else}, @code{loop}): ! @smallexample @c adanocomment ! @group begin ! -- Comment for the next statement A := 5; ! -- Comment for the B statement B := 6; + end; + @end group @end smallexample @item In sequences of statements, comments at the end of the lines should be aligned. + @cindex Alignment (in comments) ! @smallexample @c adanocomment ! My_Identifier := 5; -- First comment ! Other_Id := 6; -- Second comment @end smallexample @item *************** period. Comments taking more than a lin *** 244,250 **** manner. @item ! Comments should focus on why instead of what. Descriptions of what subprograms do go with the specification. @item --- 315,321 ---- manner. @item ! Comments should focus on @emph{why} instead of @emph{what}. Descriptions of what subprograms do go with the specification. @item *************** depend on the names of things. The name *** 254,273 **** sufficient, as comments. @item ! Do NOT put two spaces after periods in comments. @end itemize @c ------------------------------------------------------------------------- @node Declarations and Types, Expressions and Names, Lexical Elements,Top @section Declarations and Types @c ------------------------------------------------------------------------- @itemize @bullet @item In entity declarations, colons must be surrounded by spaces. Colons should be aligned. ! @smallexample Entity1 : Integer; My_Entity : Integer; @end smallexample --- 325,346 ---- sufficient, as comments. @item ! @emph{Do not} put two spaces after periods in comments. @end itemize @c ------------------------------------------------------------------------- @node Declarations and Types, Expressions and Names, Lexical Elements,Top @section Declarations and Types @c ------------------------------------------------------------------------- + @cindex Declarationa and Types @itemize @bullet @item In entity declarations, colons must be surrounded by spaces. Colons should be aligned. + @cindex Alignment (in declarations) ! @smallexample @c adanocomment Entity1 : Integer; My_Entity : Integer; @end smallexample *************** All local subprograms in a subprogram or *** 281,290 **** before the first local subprogram body. @item ! Don't declare local entities that hide global entities. @item ! Don't declare multiple variables in one declaration that spans lines. Start a new declaration on each line, instead. @item --- 354,364 ---- before the first local subprogram body. @item ! Do not declare local entities that hide global entities. ! @cindex Hiding of outer entities @item ! Do not declare multiple variables in one declaration that spans lines. Start a new declaration on each line, instead. @item *************** one context, where comments explain thei *** 303,326 **** @node Expressions and Names, Statements, Declarations and Types, Top @section Expressions and Names @c ------------------------------------------------------------------------- @itemize @bullet @item ! Every operator must be surrounded by spaces, except for the ! exponentiation operator. ! @smallexample E := A * B**2 + 3 * (C - D); @end smallexample @item - When folding a long line, fold before an operator, not after. - - @item Use parentheses where they clarify the intended association of operands with operators: ! @smallexample (A / B) * C @end smallexample @end itemize --- 377,403 ---- @node Expressions and Names, Statements, Declarations and Types, Top @section Expressions and Names @c ------------------------------------------------------------------------- + @cindex Expressions and names @itemize @bullet @item ! Every operator must be surrounded by spaces. An exception is that ! this rule does not apply to the exponentiation operator, for which ! there are no specific layout rules. The reason for this exception ! is that sometimes it makes clearer reading to leave out the spaces ! around exponentiation. ! @cindex Operators ! @smallexample @c adanocomment E := A * B**2 + 3 * (C - D); @end smallexample @item Use parentheses where they clarify the intended association of operands with operators: ! @cindex Parenthesization of expressions ! @smallexample @c adanocomment (A / B) * C @end smallexample @end itemize *************** with operators: *** 329,337 **** --- 406,417 ---- @node Statements, Subprograms, Expressions and Names, Top @section Statements @c ------------------------------------------------------------------------- + @cindex Statements @subsection Simple and Compound Statements @c ------------------------------------------------------------------------- + @cindex Simple and compound statements + @itemize @bullet @item Use only one statement or label per line. *************** groups or separated from surrounding cod *** 342,354 **** @subsection If Statements @c ------------------------------------------------------------------------- @itemize @bullet @item ! When the @samp{if}, @samp{elsif} or @samp{else} keywords fit on the ! same line with the condition and the @samp{then} keyword, then the statement is formatted as follows: ! @smallexample if @var{condition} then ... elsif @var{condition} then --- 422,438 ---- @subsection If Statements @c ------------------------------------------------------------------------- + @cindex @code{if} statement + @itemize @bullet @item ! When the @code{if}, @code{elsif} or @code{else} keywords fit on the ! same line with the condition and the @code{then} keyword, then the statement is formatted as follows: + @cindex Alignment (in an @code{if} statement) ! @smallexample @c adanocomment ! @group if @var{condition} then ... elsif @var{condition} then *************** statement is formatted as follows: *** 356,418 **** else ... end if; @end smallexample @noindent ! When the above layout is not possible, @samp{then} should be aligned ! with @samp{if}, and conditions should preferably be split before an ! @samp{and} or @samp{or} keyword a follows: ! @smallexample if @var{long_condition_that_has_to_be_split} and then @var{continued_on_the_next_line} then ... end if; @end smallexample @noindent ! The @samp{elsif}, @samp{else} and @samp{end if} always line up with ! the @samp{if} keyword. The preferred location for splitting the line ! is before @samp{and} or @samp{or}. The continuation of a condition is indented with two spaces or as many as needed to make nesting clear. ! As exception, if conditions are closely related either of the following is allowed: @smallexample if x = lakdsjfhlkashfdlkflkdsalkhfsalkdhflkjdsahf or else x = asldkjhalkdsjfhhfd or else x = asdfadsfadsf then if x = lakdsjfhlkashfdlkflkdsalkhfsalkdhflkjdsahf or else x = asldkjhalkdsjfhhfd or else x = asdfadsfadsf then @end smallexample @item ! Conditions should use short-circuit forms (@samp{and then}, ! @samp{or else}). @item ! Complex conditions in if statements are indented two characters: ! @smallexample if @var{this_complex_condition} and then @var{that_other_one} and then @var{one_last_one} then ... @end smallexample @item ! Every @samp{if} block is preceded and followed by a blank line, except where it begins or ends a @syntax{sequence_of_statements}. ! @smallexample A := 5; if A = 5 then --- 440,520 ---- else ... end if; + @end group @end smallexample @noindent ! When the above layout is not possible, @code{then} should be aligned ! with @code{if}, and conditions should preferably be split before an ! @code{and} or @code{or} keyword a follows: ! @smallexample @c adanocomment ! @group if @var{long_condition_that_has_to_be_split} and then @var{continued_on_the_next_line} then ... end if; + @end group @end smallexample @noindent ! The @code{elsif}, @code{else} and @code{end if} always line up with ! the @code{if} keyword. The preferred location for splitting the line ! is before @code{and} or @code{or}. The continuation of a condition is indented with two spaces or as many as needed to make nesting clear. ! As an exception, if conditions are closely related either of the following is allowed: @smallexample + @group if x = lakdsjfhlkashfdlkflkdsalkhfsalkdhflkjdsahf or else x = asldkjhalkdsjfhhfd or else x = asdfadsfadsf then + ... + end if; + @end group + @group if x = lakdsjfhlkashfdlkflkdsalkhfsalkdhflkjdsahf or else x = asldkjhalkdsjfhhfd or else x = asdfadsfadsf then + ... + end if; + @end group @end smallexample @item ! Conditions should use short-circuit forms (@code{and then}, ! @code{or else}). ! @cindex Short-circuit forms @item ! Complex conditions in @code{if} statements are indented two characters: ! @cindex Indentation (in @code{if} statements) ! @smallexample @c adanocomment ! @group if @var{this_complex_condition} and then @var{that_other_one} and then @var{one_last_one} then ... + end if; + @end group @end smallexample @item ! Every @code{if} block is preceded and followed by a blank line, except where it begins or ends a @syntax{sequence_of_statements}. + @cindex Blank lines (in an @code{if} statement) ! @smallexample @c adanocomment ! @group A := 5; if A = 5 then *************** where it begins or ends a @syntax{sequen *** 420,496 **** end if; A := 6; @end smallexample @end itemize @subsection Case Statements ! @itemize @bullet @item ! Layout is as below. For long case statements, the extra indentation ! can be saved by aligning the when clauses with the opening case. ! @smallexample case @var{expression} is when @var{condition} => ... when @var{condition} => ... end case; @end smallexample @end itemize @subsection Loop Statements ! @itemize @bullet @noindent ! When possible, have @samp{for} or @samp{while} on one line with the ! condition and the @samp{loop} keyword. ! @smallexample for J in S'Range loop ... end loop; @end smallexample @noindent If the condition is too long, split the condition (see ``If ! statements'' above) and align @samp{loop} with the @samp{for} or ! @samp{while} keyword. ! @smallexample while @var{long_condition_that_has_to_be_split} and then @var{continued_on_the_next_line} loop ... end loop; @end smallexample @noindent If the @syntax{loop_statement} has an identifier, it is laid out as follows: ! @smallexample Outer : while not @var{condition} loop ... end Outer; @end smallexample @end itemize @subsection Block Statements ! @itemize @bullet @item ! The @samp{declare} (optional), @samp{begin} and @samp{end} statements are aligned, except when the @syntax{block_statement} is named. There ! is a blank line before the @samp{begin} keyword: ! @smallexample Some_Block : declare ... begin ... end Some_Block; @end smallexample @end itemize --- 522,614 ---- end if; A := 6; + @end group @end smallexample @end itemize @subsection Case Statements ! @cindex @code{case} statements + @itemize @bullet @item ! Layout is as below. For long @code{case} statements, the extra indentation ! can be saved by aligning the @code{when} clauses with the opening @code{case}. ! @smallexample @c adanocomment ! @group case @var{expression} is when @var{condition} => ... when @var{condition} => ... end case; + @end group @end smallexample @end itemize @subsection Loop Statements ! @cindex Loop statements + @itemize @bullet @noindent ! When possible, have @code{for} or @code{while} on one line with the ! condition and the @code{loop} keyword. ! @smallexample @c adanocomment ! @group for J in S'Range loop ... end loop; + @end group @end smallexample @noindent If the condition is too long, split the condition (see ``If ! statements'' above) and align @code{loop} with the @code{for} or ! @code{while} keyword. ! @cindex Alignment (in a loop statement) ! @smallexample @c adanocomment ! @group while @var{long_condition_that_has_to_be_split} and then @var{continued_on_the_next_line} loop ... end loop; + @end group @end smallexample @noindent If the @syntax{loop_statement} has an identifier, it is laid out as follows: ! @smallexample @c adanocomment ! @group Outer : while not @var{condition} loop ... end Outer; + @end group @end smallexample @end itemize @subsection Block Statements ! @cindex Block statement + @itemize @bullet @item ! The @code{declare} (optional), @code{begin} and @code{end} words are aligned, except when the @syntax{block_statement} is named. There ! is a blank line before the @code{begin} keyword: ! @cindex Alignment (in a block statement) ! @smallexample @c adanocomment ! @group Some_Block : declare ... begin ... end Some_Block; + @end group @end smallexample @end itemize *************** is a blank line before the @samp{begin} *** 499,559 **** @node Subprograms, Packages, Statements, Top @section Subprograms @c ------------------------------------------------------------------------- ! @subsection Subprogram Declarations @c ------------------------------------------------------------------------- @itemize @bullet @item ! Do not write the @samp{in} for parameters, especially in functions: ! @smallexample function Length (S : String) return Integer; @end smallexample @item ! When the declaration line for a procedure or a function is too long, fold it. ! In this case, align the colons, and, for functions, the result type. ! @smallexample function Head (Source : String; Count : Natural; ! Pad : Character := Space) ! return String; @end smallexample ! @item ! The parameter list for a subprogram is preceded by a space: ! @smallexample ! procedure Func (A : Integer); @end smallexample @end itemize @subsection Subprogram Bodies @c ------------------------------------------------------------------------- ! @itemize @bullet @item ! The functions and procedures should always be sorted alphabetically in ! a compilation unit. @item All subprograms have a header giving the function name, with the following format: ! @smallexample ----------------- -- My_Function -- ----------------- procedure My_Function is begin @end smallexample Note that the name in the header is preceded by a single space, not two spaces as for other comments. --- 617,720 ---- @node Subprograms, Packages, Statements, Top @section Subprograms @c ------------------------------------------------------------------------- ! @cindex Subprograms @subsection Subprogram Declarations @c ------------------------------------------------------------------------- @itemize @bullet @item ! Do not write the @code{in} for parameters, especially in functions: ! @smallexample @c adanocomment function Length (S : String) return Integer; @end smallexample @item ! When the declaration line for a procedure or a function is too long to fit ! the entire declaration (including the keyword procedure or function) on a ! single line, then fold it, putting a single parameter on a line, aligning ! the colons, as in: ! @smallexample @c adanocomment ! @group ! procedure Set_Heading ! (Source : String; ! Count : Natural; ! Pad : Character := Space; ! Fill : Boolean := True); ! @end group ! @end smallexample ! ! @noindent ! In the case of a function, if the entire spec does not fit on one line, then ! the return may appear after the last parameter, as in: ! ! @smallexample @c adanocomment ! @group function Head (Source : String; Count : Natural; ! Pad : Character := Space) return String; ! @end group @end smallexample ! @noindent ! Or it may appear on its own as a separate line. This form is preferred when ! putting the return on the same line as the last parameter would result in ! an overlong line. The return type may optionally be aligned with the types ! of the parameters (usually we do this aligning if it results only in a small ! number of extra spaces, and otherwise we don't attempt to align). So two ! alternative forms for the above spec are: ! @smallexample @c adanocomment ! @group ! function Head ! (Source : String; ! Count : Natural; ! Pad : Character := Space) ! return String; ! ! function Head ! (Source : String; ! Count : Natural; ! Pad : Character := Space) ! return String; ! @end group @end smallexample @end itemize @subsection Subprogram Bodies @c ------------------------------------------------------------------------- ! @cindex Subprogram bodies + @itemize @bullet @item ! Function and procedure bodies should usually be sorted alphabetically. Do ! not attempt to sort them in some logical order by functionality. For a ! sequence of subrpgroams specs, a general alphabetical sorting is also ! usually appropriate, but occasionally it makes sense to group by major ! function, with appropriate headers. @item All subprograms have a header giving the function name, with the following format: ! @smallexample @c adanocomment ! @group ----------------- -- My_Function -- ----------------- procedure My_Function is begin + ... + end My_Function; + @end group @end smallexample + @noindent Note that the name in the header is preceded by a single space, not two spaces as for other comments. *************** not two spaces as for other comments. *** 561,578 **** Every subprogram body must have a preceding @syntax{subprogram_declaration}. @item ! If there any declarations in a subprogram, the @samp{begin} keyword is ! preceded by a blank line. @item If the declarations in a subprogram contain at least one nested ! subprogram body, then just before the @samp{begin} of the enclosing ! subprogram, there is a line: ! @smallexample ! -- @r{Start of processing for @var{Enclosing_Subprogram}} ! begin @end smallexample @end itemize --- 722,747 ---- Every subprogram body must have a preceding @syntax{subprogram_declaration}. @item ! @cindex Blank lines (in subprogram bodies) ! A sequence of declarations may optionally be separated from the following ! begin by a blank line. Just as we optionally allow blank lines in general ! between declarations, this blank line should be present only if it improves ! readability. Generally we avoid this blank line if the declarative part is ! small (one or two lines) and we include it if the declarative part is long. @item If the declarations in a subprogram contain at least one nested ! subprogram body, then just before the @code{begin} of the enclosing ! subprogram, there is a comment line and a blank line: ! @smallexample @c adanocomment ! @group ! -- Start of processing for @var{Enclosing_Subprogram} ! begin ! ... ! end @var{Enclosing_Subprogram}; ! @end group @end smallexample @end itemize *************** subprogram, there is a line: *** 581,616 **** @node Packages, Program Structure, Subprograms, Top @section Packages and Visibility Rules @c ------------------------------------------------------------------------- @itemize @bullet - @item All program units and subprograms have their name at the end: ! @smallexample package P is ... end P; @end smallexample @item ! We will use the style of @samp{use}-ing @samp{with}-ed packages, with the context clauses looking like: ! @smallexample with A; use A; with B; use B; @end smallexample @item Names declared in the visible part of packages should be ! unique, to prevent name clashes when the packages are @samp{use}d. ! @smallexample package Entity is type Entity_Kind is ...; ! ... end Entity; @end smallexample @item --- 750,793 ---- @node Packages, Program Structure, Subprograms, Top @section Packages and Visibility Rules @c ------------------------------------------------------------------------- + @cindex Packages @itemize @bullet @item All program units and subprograms have their name at the end: ! @smallexample @c adanocomment ! @group package P is ... end P; + @end group @end smallexample @item ! We will use the style of @code{use}-ing @code{with}-ed packages, with the context clauses looking like: + @cindex @code{use} clauses ! @smallexample @c adanocomment ! @group with A; use A; with B; use B; + @end group @end smallexample @item Names declared in the visible part of packages should be ! unique, to prevent name clashes when the packages are @code{use}d. ! @cindex Name clash avoidance ! @smallexample @c adanocomment ! @group package Entity is type Entity_Kind is ...; ! ... end Entity; + @end group @end smallexample @item *************** should be the first thing in a @syntax{p *** 619,646 **** @end itemize @c ------------------------------------------------------------------------- ! @node Program Structure,, Packages, Top @section Program Structure and Compilation Issues @c ------------------------------------------------------------------------- @itemize @bullet @item Every GNAT source file must be compiled with the @option{-gnatg} ! switch to check the coding style (Note that you should look at @file{style.adb} to see the lexical rules enforced by @option{-gnatg}). @item Each source file should contain only one compilation unit. @item ! Filenames should be 8 characters or less followed by the @samp{.adb} ! extension for a body or @samp{.ads} for a spec. @item ! Unit names should be distinct when krunched to 8 characters (see @file{krunch.ads}) and the filenames should match the unit name, except that they are all lower case. @end itemize @bye --- 796,844 ---- @end itemize @c ------------------------------------------------------------------------- ! @node Program Structure, GNU Free Documentation License, Packages, Top @section Program Structure and Compilation Issues @c ------------------------------------------------------------------------- + @cindex Program structure @itemize @bullet @item Every GNAT source file must be compiled with the @option{-gnatg} ! switch to check the coding style. ! (Note that you should look at @file{style.adb} to see the lexical rules enforced by @option{-gnatg}). + @cindex @option{-gnatg} option (to gcc) + @cindex @file{style.adb} file @item Each source file should contain only one compilation unit. @item ! Filenames should be 8 or fewer characters, followed by the @code{.adb} ! extension for a body or @code{.ads} for a spec. ! @cindex File name length @item ! Unit names should be distinct when ``krunch''ed to 8 characters (see @file{krunch.ads}) and the filenames should match the unit name, except that they are all lower case. + @cindex @file{krunch.ads} file @end itemize + + @c ********************************** + @c * GNU Free Documentation License * + @c ********************************** + @include fdl.texi + @c GNU Free Documentation License + @cindex GNU Free Documentation License + + @node Index,,GNU Free Documentation License, Top + @unnumberedsec Index + + @printindex cp + + @contents + @bye diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_ugn.texi gcc-3.4.1/gcc/ada/gnat_ugn.texi *** gcc-3.4.0/gcc/ada/gnat_ugn.texi 1970-01-01 00:00:00.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_ugn.texi 2004-06-09 09:20:48.000000000 +0000 *************** *** 0 **** --- 1,27170 ---- + \input texinfo @c -*-texinfo-*- + @c %**start of header + + @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo + @c o + @c GNAT DOCUMENTATION o + @c o + @c G N A T _ U G N o + @c o + @c Copyright (C) 1992-2004 Ada Core Technologies, Inc. o + @c o + @c GNAT is free software; you can redistribute it and/or modify it under o + @c terms of the GNU General Public License as published by the Free Soft- o + @c ware Foundation; either version 2, or (at your option) any later ver- o + @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o + @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o + @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o + @c for more details. You should have received a copy of the GNU General o + @c Public License distributed with GNAT; see file COPYING. If not, write o + @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o + @c MA 02111-1307, USA. o + @c o + @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo + + @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo + @c + @c GNAT_UGN Style Guide + @c + @c 1. Always put a @noindent on the line before the first paragraph + @c after any of these commands: + @c + @c @chapter + @c @section + @c @subsection + @c @subsubsection + @c @subsubsubsection + @c + @c @end smallexample + @c @end itemize + @c @end enumerate + @c + @c 2. DO NOT use @example. Use @smallexample instead. + @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample + @c context. These can interfere with the readability of the texi + @c source file. Instead, use one of the following annotated + @c @smallexample commands, and preprocess the texi file with the + @c ada2texi tool (which generates appropriate highlighting): + @c @smallexample @c ada + @c @smallexample @c adanocomment + @c @smallexample @c projectfile + @c b) The "@c ada" markup will result in boldface for reserved words + @c and italics for comments + @c c) The "@c adanocomment" markup will result only in boldface for + @c reserved words (comments are left alone) + @c d) The "@c projectfile" markup is like "@c ada" except that the set + @c of reserved words include the new reserved words for project files + @c + @c 3. Each @chapter, @section, @subsection, @subsubsection, etc. + @c command must be preceded by two empty lines + @c + @c 4. The @item command should be on a line of its own if it is in an + @c @itemize or @enumerate command. + @c + @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" + @c or "ali". + @c + @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will + @c cause the document build to fail. + @c + @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines. + @c This command inhibits page breaks, so long examples in a @cartouche can + @c lead to large, ugly patches of empty space on a page. + @c + @c NOTE: This file should be submitted to xgnatugn with either the vms flag + @c or the unw flag set. The unw flag covers topics for both Unix and + @c Windows. + @c + @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo + + @ifset vms + @setfilename gnat_ugn_vms.info + @end ifset + + @ifset unw + @setfilename gnat_ugn_unw.info + @end ifset + + @ifset vms + @settitle GNAT User's Guide for Native Platforms / OpenVMS Alpha + @dircategory GNU Ada tools + @direntry + * GNAT User's Guide (gnat_ugn_vms) for Native Platforms / OpenVMS Alpha + @end direntry + @end ifset + + @ifset unw + @settitle GNAT User's Guide for Native Platforms / Unix and Windows + @direntry + * GNAT User's Guide (gnat_ugn_unw) for Native Platforms / Unix and Windows + @end direntry + @end ifset + + @include gcc-common.texi + + @setchapternewpage odd + @syncodeindex fn cp + @c %**end of header + + @copying + Copyright @copyright{} 1995-2004, Free Software Foundation + + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU Free Documentation License, Version 1.2 + or any later version published by the Free Software Foundation; + with the Invariant Sections being ``GNU Free Documentation License'', with the + Front-Cover Texts being + @ifset vms + ``GNAT User's Guide for Native Platforms / OpenVMS Alpha'', + @end ifset + @ifset unw + ``GNAT User's Guide for Native Platforms / Unix and Windows'', + @end ifset + and with no Back-Cover Texts. + A copy of the license is included in the section entitled + ``GNU Free Documentation License''. + @end copying + + @titlepage + + @title GNAT User's Guide + @center @titlefont{for Native Platforms} + @sp 1 + + @flushright + @ifset unw + @titlefont{@i{Unix and Windows}} + @end ifset + @ifset vms + @titlefont{@i{OpenVMS Alpha}} + @end ifset + @end flushright + @sp 2 + + @subtitle GNAT, The GNU Ada 95 Compiler + @subtitle GCC version @value{version-GCC} + + @author Ada Core Technologies, Inc. + + @page + @vskip 0pt plus 1filll + + @insertcopying + + @end titlepage + + + @ifnottex + @node Top, About This Guide, (dir), (dir) + @top GNAT User's Guide + + @ifset vms + @noindent + GNAT User's Guide for Native Platforms / OpenVMS Alpha + @end ifset + + @ifset unw + @noindent + GNAT User's Guide for Native Platforms / Unix and Windows + @end ifset + + @noindent + GNAT, The GNU Ada 95 Compiler@* + GCC version @value{version-GCC}@* + + @noindent + Ada Core Technologies, Inc.@* + + @menu + * About This Guide:: + * Getting Started with GNAT:: + * The GNAT Compilation Model:: + * Compiling Using gcc:: + * Binding Using gnatbind:: + * Linking Using gnatlink:: + * The GNAT Make Program gnatmake:: + * Improving Performance:: + * Renaming Files Using gnatchop:: + * Configuration Pragmas:: + * Handling Arbitrary File Naming Conventions Using gnatname:: + * GNAT Project Manager:: + * The Cross-Referencing Tools gnatxref and gnatfind:: + * The GNAT Pretty-Printer gnatpp:: + * File Name Krunching Using gnatkr:: + * Preprocessing Using gnatprep:: + @ifset vms + * The GNAT Run-Time Library Builder gnatlbr:: + @end ifset + * The GNAT Library Browser gnatls:: + * Cleaning Up Using gnatclean:: + @ifclear vms + * GNAT and Libraries:: + * Using the GNU make Utility:: + @end ifclear + * Finding Memory Problems:: + * Creating Sample Bodies Using gnatstub:: + * Other Utility Programs:: + * Running and Debugging Ada Programs:: + @ifset vms + * Compatibility with DEC Ada:: + @end ifset + * Platform-Specific Information for the Run-Time Libraries:: + * Example of Binder Output File:: + * Elaboration Order Handling in GNAT:: + * Inline Assembler:: + * Compatibility and Porting Guide:: + @ifset unw + * Microsoft Windows Topics:: + @end ifset + * GNU Free Documentation License:: + * Index:: + + --- The Detailed Node Listing --- + + About This Guide + + * What This Guide Contains:: + * What You Should Know before Reading This Guide:: + * Related Information:: + * Conventions:: + + Getting Started with GNAT + + * Running GNAT:: + * Running a Simple Ada Program:: + * Running a Program with Multiple Units:: + * Using the gnatmake Utility:: + @ifset vms + * Editing with Emacs:: + @end ifset + @ifclear vms + * Introduction to GPS:: + * Introduction to Glide and GVD:: + @end ifclear + + The GNAT Compilation Model + + * Source Representation:: + * Foreign Language Representation:: + * File Naming Rules:: + * Using Other File Names:: + * Alternative File Naming Schemes:: + * Generating Object Files:: + * Source Dependencies:: + * The Ada Library Information Files:: + * Binding an Ada Program:: + * Mixed Language Programming:: + * Building Mixed Ada & C++ Programs:: + * Comparison between GNAT and C/C++ Compilation Models:: + * Comparison between GNAT and Conventional Ada Library Models:: + @ifset vms + * Placement of temporary files:: + @end ifset + + Foreign Language Representation + + * Latin-1:: + * Other 8-Bit Codes:: + * Wide Character Encodings:: + + Compiling Ada Programs With gcc + + * Compiling Programs:: + * Switches for gcc:: + * Search Paths and the Run-Time Library (RTL):: + * Order of Compilation Issues:: + * Examples:: + + Switches for gcc + + * Output and Error Message Control:: + * Warning Message Control:: + * Debugging and Assertion Control:: + * Run-Time Checks:: + * Stack Overflow Checking:: + * Validity Checking:: + * Style Checking:: + * Using gcc for Syntax Checking:: + * Using gcc for Semantic Checking:: + * Compiling Ada 83 Programs:: + * Character Set Control:: + * File Naming Control:: + * Subprogram Inlining Control:: + * Auxiliary Output Control:: + * Debugging Control:: + * Exception Handling Control:: + * Units to Sources Mapping Files:: + * Integrated Preprocessing:: + @ifset vms + * Return Codes:: + @end ifset + + Binding Ada Programs With gnatbind + + * Running gnatbind:: + * Switches for gnatbind:: + * Command-Line Access:: + * Search Paths for gnatbind:: + * Examples of gnatbind Usage:: + + Switches for gnatbind + + * Consistency-Checking Modes:: + * Binder Error Message Control:: + * Elaboration Control:: + * Output Control:: + * Binding with Non-Ada Main Programs:: + * Binding Programs with No Main Subprogram:: + + Linking Using gnatlink + + * Running gnatlink:: + * Switches for gnatlink:: + * Setting Stack Size from gnatlink:: + * Setting Heap Size from gnatlink:: + + The GNAT Make Program gnatmake + + * Running gnatmake:: + * Switches for gnatmake:: + * Mode Switches for gnatmake:: + * Notes on the Command Line:: + * How gnatmake Works:: + * Examples of gnatmake Usage:: + + + Improving Performance + * Performance Considerations:: + * Reducing the Size of Ada Executables with gnatelim:: + + Performance Considerations + * Controlling Run-Time Checks:: + * Use of Restrictions:: + * Optimization Levels:: + * Debugging Optimized Code:: + * Inlining of Subprograms:: + @ifset vms + * Coverage Analysis:: + @end ifset + + Reducing the Size of Ada Executables with gnatelim + * About gnatelim:: + * Running gnatelim:: + * Correcting the List of Eliminate Pragmas:: + * Making Your Executables Smaller:: + * Summary of the gnatelim Usage Cycle:: + + Renaming Files Using gnatchop + + * Handling Files with Multiple Units:: + * Operating gnatchop in Compilation Mode:: + * Command Line for gnatchop:: + * Switches for gnatchop:: + * Examples of gnatchop Usage:: + + Configuration Pragmas + + * Handling of Configuration Pragmas:: + * The Configuration Pragmas Files:: + + Handling Arbitrary File Naming Conventions Using gnatname + + * Arbitrary File Naming Conventions:: + * Running gnatname:: + * Switches for gnatname:: + * Examples of gnatname Usage:: + + GNAT Project Manager + + * Introduction:: + * Examples of Project Files:: + * Project File Syntax:: + * Objects and Sources in Project Files:: + * Importing Projects:: + * Project Extension:: + * External References in Project Files:: + * Packages in Project Files:: + * Variables from Imported Projects:: + * Naming Schemes:: + * Library Projects:: + * Using Third-Party Libraries through Projects:: + * Stand-alone Library Projects:: + * Switches Related to Project Files:: + * Tools Supporting Project Files:: + * An Extended Example:: + * Project File Complete Syntax:: + + + The Cross-Referencing Tools gnatxref and gnatfind + + * gnatxref Switches:: + * gnatfind Switches:: + * Project Files for gnatxref and gnatfind:: + * Regular Expressions in gnatfind and gnatxref:: + * Examples of gnatxref Usage:: + * Examples of gnatfind Usage:: + + + The GNAT Pretty-Printer gnatpp + + * Switches for gnatpp:: + * Formatting Rules:: + + + File Name Krunching Using gnatkr + + * About gnatkr:: + * Using gnatkr:: + * Krunching Method:: + * Examples of gnatkr Usage:: + + Preprocessing Using gnatprep + + * Using gnatprep:: + * Switches for gnatprep:: + * Form of Definitions File:: + * Form of Input Text for gnatprep:: + + @ifset vms + The GNAT Run-Time Library Builder gnatlbr + + * Running gnatlbr:: + * Switches for gnatlbr:: + * Examples of gnatlbr Usage:: + @end ifset + + The GNAT Library Browser gnatls + + * Running gnatls:: + * Switches for gnatls:: + * Examples of gnatls Usage:: + + Cleaning Up Using gnatclean + + * Running gnatclean:: + * Switches for gnatclean:: + * Examples of gnatclean Usage:: + + @ifclear vms + + GNAT and Libraries + + * Creating an Ada Library:: + * Installing an Ada Library:: + * Using an Ada Library:: + * Creating an Ada Library to be Used in a Non-Ada Context:: + * Rebuilding the GNAT Run-Time Library:: + + Using the GNU make Utility + + * Using gnatmake in a Makefile:: + * Automatically Creating a List of Directories:: + * Generating the Command Line Switches:: + * Overcoming Command Line Length Limits:: + @end ifclear + + Finding Memory Problems + + @ifclear vms + * The gnatmem Tool:: + @end ifclear + * The GNAT Debug Pool Facility:: + + @ifclear vms + The gnatmem Tool + + * Running gnatmem:: + * Switches for gnatmem:: + * Example of gnatmem Usage:: + @end ifclear + + The GNAT Debug Pool Facility + + Creating Sample Bodies Using gnatstub + + * Running gnatstub:: + * Switches for gnatstub:: + + Other Utility Programs + + * Using Other Utility Programs with GNAT:: + * The External Symbol Naming Scheme of GNAT:: + @ifclear vms + * Ada Mode for Glide:: + @end ifclear + * Converting Ada Files to html with gnathtml:: + + Running and Debugging Ada Programs + + * The GNAT Debugger GDB:: + * Running GDB:: + * Introduction to GDB Commands:: + * Using Ada Expressions:: + * Calling User-Defined Subprograms:: + * Using the Next Command in a Function:: + * Ada Exceptions:: + * Ada Tasks:: + * Debugging Generic Units:: + * GNAT Abnormal Termination or Failure to Terminate:: + * Naming Conventions for GNAT Source Files:: + * Getting Internal Debugging Information:: + * Stack Traceback:: + + @ifset vms + * LSE:: + @end ifset + + @ifset vms + Compatibility with DEC Ada + + * Ada 95 Compatibility:: + * Differences in the Definition of Package System:: + * Language-Related Features:: + * The Package STANDARD:: + * The Package SYSTEM:: + * Tasking and Task-Related Features:: + * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems:: + * Pragmas and Pragma-Related Features:: + * Library of Predefined Units:: + * Bindings:: + * Main Program Definition:: + * Implementation-Defined Attributes:: + * Compiler and Run-Time Interfacing:: + * Program Compilation and Library Management:: + * Input-Output:: + * Implementation Limits:: + * Tools:: + + Language-Related Features + + * Integer Types and Representations:: + * Floating-Point Types and Representations:: + * Pragmas Float_Representation and Long_Float:: + * Fixed-Point Types and Representations:: + * Record and Array Component Alignment:: + * Address Clauses:: + * Other Representation Clauses:: + + Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems + + * Assigning Task IDs:: + * Task IDs and Delays:: + * Task-Related Pragmas:: + * Scheduling and Task Priority:: + * The Task Stack:: + * External Interrupts:: + + Pragmas and Pragma-Related Features + + * Restrictions on the Pragma INLINE:: + * Restrictions on the Pragma INTERFACE:: + * Restrictions on the Pragma SYSTEM_NAME:: + + Library of Predefined Units + + * Changes to DECLIB:: + + Bindings + + * Shared Libraries and Options Files:: + * Interfaces to C:: + @end ifset + + Platform-Specific Information for the Run-Time Libraries + + * Summary of Run-Time Configurations:: + * Specifying a Run-Time Library:: + * Choosing between Native and FSU Threads Libraries:: + * Choosing the Scheduling Policy:: + * Solaris-Specific Considerations:: + * IRIX-Specific Considerations:: + * Linux-Specific Considerations:: + + Example of Binder Output File + + Elaboration Order Handling in GNAT + + * Elaboration Code in Ada 95:: + * Checking the Elaboration Order in Ada 95:: + * Controlling the Elaboration Order in Ada 95:: + * Controlling Elaboration in GNAT - Internal Calls:: + * Controlling Elaboration in GNAT - External Calls:: + * Default Behavior in GNAT - Ensuring Safety:: + * Treatment of Pragma Elaborate:: + * Elaboration Issues for Library Tasks:: + * Mixing Elaboration Models:: + * What to Do If the Default Elaboration Behavior Fails:: + * Elaboration for Access-to-Subprogram Values:: + * Summary of Procedures for Elaboration Control:: + * Other Elaboration Order Considerations:: + + Inline Assembler + + * Basic Assembler Syntax:: + * A Simple Example of Inline Assembler:: + * Output Variables in Inline Assembler:: + * Input Variables in Inline Assembler:: + * Inlining Inline Assembler Code:: + * Other Asm Functionality:: + * A Complete Example:: + + Compatibility and Porting Guide + + * Compatibility with Ada 83:: + * Implementation-dependent characteristics:: + * Compatibility with DEC Ada 83:: + * Compatibility with Other Ada 95 Systems:: + * Representation Clauses:: + + @ifset unw + Microsoft Windows Topics + + * Using GNAT on Windows:: + * CONSOLE and WINDOWS subsystems:: + * Temporary Files:: + * Mixed-Language Programming on Windows:: + * Windows Calling Conventions:: + * Introduction to Dynamic Link Libraries (DLLs):: + * Using DLLs with GNAT:: + * Building DLLs with GNAT:: + * GNAT and Windows Resources:: + * Debugging a DLL:: + * GNAT and COM/DCOM Objects:: + @end ifset + + + * Index:: + @end menu + @end ifnottex + + @node About This Guide + @unnumbered About This Guide + + @noindent + @ifset vms + This guide describes the use of of GNAT, a full language compiler for the Ada + 95 programming language, implemented on HP OpenVMS Alpha platforms. + @end ifset + @ifclear vms + This guide describes the use of GNAT, a compiler and software development + toolset for the full Ada 95 programming language. + @end ifclear + It describes the features of the compiler and tools, and details + how to use them to build Ada 95 applications. + + @menu + * What This Guide Contains:: + * What You Should Know before Reading This Guide:: + * Related Information:: + * Conventions:: + @end menu + + @node What This Guide Contains + @unnumberedsec What This Guide Contains + + @noindent + This guide contains the following chapters: + @itemize @bullet + + @item + @ref{Getting Started with GNAT}, describes how to get started compiling + and running Ada programs with the GNAT Ada programming environment. + @item + @ref{The GNAT Compilation Model}, describes the compilation model used + by GNAT. + + @item + @ref{Compiling Using gcc}, describes how to compile + Ada programs with @code{gcc}, the Ada compiler. + + @item + @ref{Binding Using gnatbind}, describes how to + perform binding of Ada programs with @code{gnatbind}, the GNAT binding + utility. + + @item + @ref{Linking Using gnatlink}, + describes @code{gnatlink}, a + program that provides for linking using the GNAT run-time library to + construct a program. @code{gnatlink} can also incorporate foreign language + object units into the executable. + + @item + @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a + utility that automatically determines the set of sources + needed by an Ada compilation unit, and executes the necessary compilations + binding and link. + + @item + @ref{Improving Performance}, shows various techniques for making your + Ada program run faster or take less space. + It discusses the effect of the compiler's optimization switch and + also describes the @command{gnatelim} tool. + + @item + @ref{Renaming Files Using gnatchop}, describes + @code{gnatchop}, a utility that allows you to preprocess a file that + contains Ada source code, and split it into one or more new files, one + for each compilation unit. + + @item + @ref{Configuration Pragmas}, describes the configuration pragmas + handled by GNAT. + + @item + @ref{Handling Arbitrary File Naming Conventions Using gnatname}, + shows how to override the default GNAT file naming conventions, + either for an individual unit or globally. + + @item + @ref{GNAT Project Manager}, describes how to use project files + to organize large projects. + + @item + @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses + @code{gnatxref} and @code{gnatfind}, two tools that provide an easy + way to navigate through sources. + + @item + @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted + version of an Ada source file with control over casing, indentation, + comment placement, and other elements of program presentation style. + + + @item + @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr} + file name krunching utility, used to handle shortened + file names on operating systems with a limit on the length of names. + + @item + @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a + preprocessor utility that allows a single source file to be used to + generate multiple or parameterized source files, by means of macro + substitution. + + @ifset vms + @item + @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr}, + a tool for rebuilding the GNAT run time with user-supplied + configuration pragmas. + @end ifset + + @item + @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a + utility that displays information about compiled units, including dependences + on the corresponding sources files, and consistency of compilations. + + @item + @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility + to delete files that are produced by the compiler, binder and linker. + + @ifclear vms + @item + @ref{GNAT and Libraries}, describes the process of creating and using + Libraries with GNAT. It also describes how to recompile the GNAT run-time + library. + + @item + @ref{Using the GNU make Utility}, describes some techniques for using + the GNAT toolset in Makefiles. + @end ifclear + + @item + @ref{Finding Memory Problems}, describes + @ifclear vms + @command{gnatmem}, a utility that monitors dynamic allocation and deallocation + and helps detect ``memory leaks'', and + @end ifclear + the GNAT Debug Pool facility, which helps detect incorrect memory references. + + @item + @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub}, + a utility that generates empty but compilable bodies for library units. + + @item + @ref{Other Utility Programs}, discusses several other GNAT utilities, + including @code{gnathtml}. + + @item + @ref{Running and Debugging Ada Programs}, describes how to run and debug + Ada programs. + + @ifset vms + @item + @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with + DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally + developed by Digital Equipment Corporation and currently supported by HP.} + for OpenVMS Alpha. + @end ifset + + @item + @ref{Platform-Specific Information for the Run-Time Libraries}, + describes the various run-time + libraries supported by GNAT on various platforms and explains how to + choose a particular library. + + @item + @ref{Example of Binder Output File}, shows the source code for the binder + output file for a sample program. + + @item + @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps + you deal with elaboration order issues. + + @item + @ref{Inline Assembler}, shows how to use the inline assembly facility + in an Ada program. + + @item + @ref{Compatibility and Porting Guide}, includes sections on compatibility + of GNAT with other Ada 83 and Ada 95 compilation systems, to assist + in porting code from other environments. + + @ifset unw + @item + @ref{Microsoft Windows Topics}, presents information relevant to the + Microsoft Windows platform. + @end ifset + @end itemize + + + @c ************************************************* + @node What You Should Know before Reading This Guide + @c ************************************************* + @unnumberedsec What You Should Know before Reading This Guide + + @cindex Ada 95 Language Reference Manual + @noindent + This user's guide assumes that you are familiar with Ada 95 language, as + described in the International Standard ANSI/ISO/IEC-8652:1995, January + 1995. + + @node Related Information + @unnumberedsec Related Information + + @noindent + For further information about related tools, refer to the following + documents: + + @itemize @bullet + @item + @cite{GNAT Reference Manual}, which contains all reference + material for the GNAT implementation of Ada 95. + + @ifset unw + @item + @cite{Using the GNAT Programming System}, which describes the GPS + integrated development environment. + + @item + @cite{GNAT Programming System Tutorial}, which introduces the + main GPS features through examples. + @end ifset + + @item + @cite{Ada 95 Language Reference Manual}, which contains all reference + material for the Ada 95 programming language. + + @item + @cite{Debugging with GDB} + @ifset vms + , located in the GNU:[DOCS] directory, + @end ifset + contains all details on the use of the GNU source-level debugger. + + @item + @cite{GNU Emacs Manual} + @ifset vms + , located in the GNU:[DOCS] directory if the EMACS kit is installed, + @end ifset + contains full information on the extensible editor and programming + environment Emacs. + + @end itemize + + @c ************** + @node Conventions + @unnumberedsec Conventions + @cindex Conventions + @cindex Typographical conventions + + @noindent + Following are examples of the typographical and graphic conventions used + in this guide: + + @itemize @bullet + @item + @code{Functions}, @code{utility program names}, @code{standard names}, + and @code{classes}. + + @item + @samp{Option flags} + + @item + @file{File Names}, @file{button names}, and @file{field names}. + + @item + @var{Variables}. + + @item + @emph{Emphasis}. + + @item + [optional information or parameters] + + @item + Examples are described by text + @smallexample + and then shown this way. + @end smallexample + @end itemize + + @noindent + Commands that are entered by the user are preceded in this manual by the + characters @w{``@code{$ }''} (dollar sign followed by space). If your system + uses this sequence as a prompt, then the commands will appear exactly as + you see them in the manual. If your system uses some other prompt, then + the command will appear with the @code{$} replaced by whatever prompt + character you are using. + + @ifset unw + Full file names are shown with the ``@code{/}'' character + as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}. + If you are using GNAT on a Windows platform, please note that + the ``@code{\}'' character should be used instead. + @end ifset + + + + @c **************************** + @node Getting Started with GNAT + @chapter Getting Started with GNAT + + @noindent + This chapter describes some simple ways of using GNAT to build + executable Ada programs. + @ifset unw + @ref{Running GNAT}, through @ref{Using the gnatmake Utility}, + show how to use the command line environment. + @ref{Introduction to Glide and GVD}, provides a brief + introduction to the visually-oriented IDE for GNAT. + Supplementing Glide on some platforms is GPS, the + GNAT Programming System, which offers a richer graphical + ``look and feel'', enhanced configurability, support for + development in other programming language, comprehensive + browsing features, and many other capabilities. + For information on GPS please refer to + @cite{Using the GNAT Programming System}. + @end ifset + + @menu + * Running GNAT:: + * Running a Simple Ada Program:: + * Running a Program with Multiple Units:: + * Using the gnatmake Utility:: + @ifset vms + * Editing with Emacs:: + @end ifset + @ifclear vms + * Introduction to GPS:: + * Introduction to Glide and GVD:: + @end ifclear + @end menu + + @node Running GNAT + @section Running GNAT + + @noindent + Three steps are needed to create an executable file from an Ada source + file: + + @enumerate + @item + The source file(s) must be compiled. + @item + The file(s) must be bound using the GNAT binder. + @item + All appropriate object files must be linked to produce an executable. + @end enumerate + + @noindent + All three steps are most commonly handled by using the @code{gnatmake} + utility program that, given the name of the main program, automatically + performs the necessary compilation, binding and linking steps. + + + @node Running a Simple Ada Program + @section Running a Simple Ada Program + + @noindent + Any text editor may be used to prepare an Ada program. + @ifclear vms + If @code{Glide} is + used, the optional Ada mode may be helpful in laying out the program. + @end ifclear + The + program text is a normal text file. We will suppose in our initial + example that you have used your editor to prepare the following + standard format text file: + + @smallexample @c ada + @cartouche + with Ada.Text_IO; use Ada.Text_IO; + procedure Hello is + begin + Put_Line ("Hello WORLD!"); + end Hello; + @end cartouche + @end smallexample + + @noindent + This file should be named @file{hello.adb}. + With the normal default file naming conventions, GNAT requires + that each file + contain a single compilation unit whose file name is the + unit name, + with periods replaced by hyphens; the + extension is @file{ads} for a + spec and @file{adb} for a body. + You can override this default file naming convention by use of the + special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). + Alternatively, if you want to rename your files according to this default + convention, which is probably more convenient if you will be using GNAT + for all your compilations, then the @code{gnatchop} utility + can be used to generate correctly-named source files + (@pxref{Renaming Files Using gnatchop}). + + You can compile the program using the following command (@code{$} is used + as the command prompt in the examples in this document): + + @smallexample + $ gcc -c hello.adb + @end smallexample + + @noindent + @code{gcc} is the command used to run the compiler. This compiler is + capable of compiling programs in several languages, including Ada 95 and + C. It assumes that you have given it an Ada program if the file extension is + either @file{.ads} or @file{.adb}, and it will then call + the GNAT compiler to compile the specified file. + + @ifclear vms + The @option{-c} switch is required. It tells @command{gcc} to only do a + compilation. (For C programs, @command{gcc} can also do linking, but this + capability is not used directly for Ada programs, so the @option{-c} + switch must always be present.) + @end ifclear + + This compile command generates a file + @file{hello.o}, which is the object + file corresponding to your Ada program. It also generates + an ``Ada Library Information'' file @file{hello.ali}, + which contains additional information used to check + that an Ada program is consistent. + To build an executable file, + use @code{gnatbind} to bind the program + and @code{gnatlink} to link it. The + argument to both @code{gnatbind} and @code{gnatlink} is the name of the + @file{ALI} file, but the default extension of @file{.ali} can + be omitted. This means that in the most common case, the argument + is simply the name of the main program: + + @smallexample + $ gnatbind hello + $ gnatlink hello + @end smallexample + + @noindent + A simpler method of carrying out these steps is to use + @command{gnatmake}, + a master program that invokes all the required + compilation, binding and linking tools in the correct order. In particular, + @command{gnatmake} automatically recompiles any sources that have been + modified since they were last compiled, or sources that depend + on such modified sources, so that ``version skew'' is avoided. + @cindex Version skew (avoided by @command{gnatmake}) + + @smallexample + $ gnatmake hello.adb + @end smallexample + + @noindent + The result is an executable program called @file{hello}, which can be + run by entering: + + @c The following should be removed (BMB 2001-01-23) + @c @smallexample + @c $ ^./hello^$ RUN HELLO^ + @c @end smallexample + + @smallexample + $ hello + @end smallexample + + @noindent + assuming that the current directory is on the search path + for executable programs. + + @noindent + and, if all has gone well, you will see + + @smallexample + Hello WORLD! + @end smallexample + + @noindent + appear in response to this command. + + + @c **************************************** + @node Running a Program with Multiple Units + @section Running a Program with Multiple Units + + @noindent + Consider a slightly more complicated example that has three files: a + main program, and the spec and body of a package: + + @smallexample @c ada + @cartouche + @group + package Greetings is + procedure Hello; + procedure Goodbye; + end Greetings; + + with Ada.Text_IO; use Ada.Text_IO; + package body Greetings is + procedure Hello is + begin + Put_Line ("Hello WORLD!"); + end Hello; + + procedure Goodbye is + begin + Put_Line ("Goodbye WORLD!"); + end Goodbye; + end Greetings; + @end group + + @group + with Greetings; + procedure Gmain is + begin + Greetings.Hello; + Greetings.Goodbye; + end Gmain; + @end group + @end cartouche + @end smallexample + + @noindent + Following the one-unit-per-file rule, place this program in the + following three separate files: + + @table @file + @item greetings.ads + spec of package @code{Greetings} + + @item greetings.adb + body of package @code{Greetings} + + @item gmain.adb + body of main program + @end table + + @noindent + To build an executable version of + this program, we could use four separate steps to compile, bind, and link + the program, as follows: + + @smallexample + $ gcc -c gmain.adb + $ gcc -c greetings.adb + $ gnatbind gmain + $ gnatlink gmain + @end smallexample + + @noindent + Note that there is no required order of compilation when using GNAT. + In particular it is perfectly fine to compile the main program first. + Also, it is not necessary to compile package specs in the case where + there is an accompanying body; you only need to compile the body. If you want + to submit these files to the compiler for semantic checking and not code + generation, then use the + @option{-gnatc} switch: + + @smallexample + $ gcc -c greetings.ads -gnatc + @end smallexample + + @noindent + Although the compilation can be done in separate steps as in the + above example, in practice it is almost always more convenient + to use the @code{gnatmake} tool. All you need to know in this case + is the name of the main program's source file. The effect of the above four + commands can be achieved with a single one: + + @smallexample + $ gnatmake gmain.adb + @end smallexample + + @noindent + In the next section we discuss the advantages of using @code{gnatmake} in + more detail. + + @c ***************************** + @node Using the gnatmake Utility + @section Using the @command{gnatmake} Utility + + @noindent + If you work on a program by compiling single components at a time using + @code{gcc}, you typically keep track of the units you modify. In order to + build a consistent system, you compile not only these units, but also any + units that depend on the units you have modified. + For example, in the preceding case, + if you edit @file{gmain.adb}, you only need to recompile that file. But if + you edit @file{greetings.ads}, you must recompile both + @file{greetings.adb} and @file{gmain.adb}, because both files contain + units that depend on @file{greetings.ads}. + + @code{gnatbind} will warn you if you forget one of these compilation + steps, so that it is impossible to generate an inconsistent program as a + result of forgetting to do a compilation. Nevertheless it is tedious and + error-prone to keep track of dependencies among units. + One approach to handle the dependency-bookkeeping is to use a + makefile. However, makefiles present maintenance problems of their own: + if the dependencies change as you change the program, you must make + sure that the makefile is kept up-to-date manually, which is also an + error-prone process. + + The @code{gnatmake} utility takes care of these details automatically. + Invoke it using either one of the following forms: + + @smallexample + $ gnatmake gmain.adb + $ gnatmake ^gmain^GMAIN^ + @end smallexample + + @noindent + The argument is the name of the file containing the main program; + you may omit the extension. @code{gnatmake} + examines the environment, automatically recompiles any files that need + recompiling, and binds and links the resulting set of object files, + generating the executable file, @file{^gmain^GMAIN.EXE^}. + In a large program, it + can be extremely helpful to use @code{gnatmake}, because working out by hand + what needs to be recompiled can be difficult. + + Note that @code{gnatmake} + takes into account all the Ada 95 rules that + establish dependencies among units. These include dependencies that result + from inlining subprogram bodies, and from + generic instantiation. Unlike some other + Ada make tools, @code{gnatmake} does not rely on the dependencies that were + found by the compiler on a previous compilation, which may possibly + be wrong when sources change. @code{gnatmake} determines the exact set of + dependencies from scratch each time it is run. + + @ifset vms + @node Editing with Emacs + @section Editing with Emacs + @cindex Emacs + + @noindent + Emacs is an extensible self-documenting text editor that is available in a + separate VMSINSTAL kit. + + Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started, + click on the Emacs Help menu and run the Emacs Tutorial. + In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also + written as @kbd{C-h}), and the tutorial by @kbd{C-h t}. + + Documentation on Emacs and other tools is available in Emacs under the + pull-down menu button: @code{Help - Info}. After selecting @code{Info}, + use the middle mouse button to select a topic (e.g. Emacs). + + In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m} + (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to + get to the Emacs manual. + Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command + prompt. + + The tutorial is highly recommended in order to learn the intricacies of Emacs, + which is sufficiently extensible to provide for a complete programming + environment and shell for the sophisticated user. + @end ifset + + @ifclear vms + @node Introduction to GPS + @section Introduction to GPS + @cindex GPS (GNAT Programming System) + @cindex GNAT Programming System (GPS) + @noindent + Although the command line interface (@command{gnatmake}, etc.) alone + is sufficient, a graphical Interactive Development + Environment can make it easier for you to compose, navigate, and debug + programs. This section describes the main features of GPS + (``GNAT Programming System''), the GNAT graphical IDE. + You will see how to use GPS to build and debug an executable, and + you will also learn some of the basics of the GNAT ``project'' facility. + + GPS enables you to do much more than is presented here; + e.g., you can produce a call graph, interface to a third-party + Version Control System, and inspect the generated assembly language + for a program. + Indeed, GPS also supports languages other than Ada. + Such additional information, and an explanation of all of the GPS menu + items. may be found in the on-line help, which includes + a user's guide and a tutorial (these are also accessible from the GNAT + startup menu). + + @menu + * Building a New Program with GPS:: + * Simple Debugging with GPS:: + @end menu + + + @node Building a New Program with GPS + @subsection Building a New Program with GPS + @noindent + GPS invokes the GNAT compilation tools using information + contained in a @emph{project} (also known as a @emph{project file}): + a collection of properties such + as source directories, identities of main subprograms, tool switches, etc., + and their associated values. + (See @ref{GNAT Project Manager}, for details.) + In order to run GPS, you will need to either create a new project + or else open an existing one. + + This section will explain how you can use GPS to create a project, + to associate Ada source files with a project, and to build and run + programs. + + @enumerate + @item @emph{Creating a project} + + Invoke GPS, either from the command line or the platform's IDE. + After it starts, GPS will display a ``Welcome'' screen with three + radio buttons: + + @itemize @bullet + @item + @code{Start with default project in directory} + + @item + @code{Create new project with wizard} + + @item + @code{Open existing project} + @end itemize + + @noindent + Select @code{Create new project with wizard} and press @code{OK}. + A new window will appear. In the text box labeled with + @code{Enter the name of the project to create}, type @file{sample} + as the project name. + In the next box, browse to choose the directory in which you + would like to create the project file. + After selecting an appropriate directory, press @code{Forward}. + + A window will appear with the title + @code{Version Control System Configuration}. + Simply press @code{Forward}. + + A window will appear with the title + @code{Please select the source directories for this project}. + The directory that you specified for the project file will be selected + by default as the one to use for sources; simply press @code{Forward}. + + A window will appear with the title + @code{Please select the build directory for this project}. + The directory that you specified for the project file will be selected + by default for object files and executables; + simply press @code{Forward}. + + A window will appear with the title + @code{Please select the main units for this project}. + You will supply this information later, after creating the source file. + Simply press @code{Forward} for now. + + A window will appear with the title + @code{Please select the switches to build the project}. + Press @code{Apply}. This will create a project file named + @file{sample.prj} in the directory that you had specified. + + @item @emph{Creating and saving the source file} + + After you create the new project, a GPS window will appear, which is + partitioned into two main sections: + + @itemize @bullet + @item + A @emph{Workspace area}, initially greyed out, which you will use for + creating and editing source files + + @item + Directly below, a @emph{Messages area}, which initially displays a + ``Welcome'' message. + (If the Messages area is not visible, drag its border upward to expand it.) + @end itemize + + @noindent + Select @code{File} on the menu bar, and then the @code{New} command. + The Workspace area will become white, and you can now + enter the source program explicitly. + Type the following text + + @smallexample @c ada + @group + with Ada.Text_IO; use Ada.Text_IO; + procedure Hello is + begin + Put_Line("Hello from GPS!"); + end Hello; + @end group + @end smallexample + + @noindent + Select @code{File}, then @code{Save As}, and enter the source file name + @file{hello.adb}. + The file will be saved in the same directory you specified as the + location of the default project file. + + + @item @emph{Updating the project file} + + You need to add the new source file to the project. + To do this, select + the @code{Project} menu and then @code{Edit project properties}. + Click the @code{Main files} tab on the left, and then the + @code{Add} button. + Choose @file{hello.adb} from the list, and press @code{Open}. + The project settings window will reflect this action. + Click @code{OK}. + + @item @emph{Building and running the program} + + In the main GPS window, now choose the @code{Build} menu, then @code{Make}, + and select @file{hello.adb}. + The Messages window will display the resulting invocations of @command{gcc}, + @command{gnatbind}, and @command{gnatlink} + (reflecting the default switch settings from the + project file that you created) and then a ``successful compilation/build'' + message. + + To run the program, choose the @code{Build} menu, then @code{Run}, and + select @command{hello}. + An @emph{Arguments Selection} window will appear. + There are no command line arguments, so just click @code{OK}. + + The Messages window will now display the program's output (the string + @code{Hello from GPS}), and at the bottom of the GPS window a status + update is displayed (@code{Run: hello}). + Close the GPS window (or select @code{File}, then @code{Exit}) to + terminate this GPS session. + @end enumerate + + + + @node Simple Debugging with GPS + @subsection Simple Debugging with GPS + @noindent + This section illustrates basic debugging techniques (setting breakpoints, + examining/modifying variables, single stepping). + + @enumerate + @item @emph{Opening a project} + + Start GPS and select @code{Open existing project}; browse to + specify the project file @file{sample.prj} that you had created in the + earlier example. + + @item @emph{Creating a source file} + + Select @code{File}, then @code{New}, and type in the following program: + + @smallexample @c ada + @group + with Ada.Text_IO; use Ada.Text_IO; + procedure Example is + Line : String (1..80); + N : Natural; + begin + Put_Line("Type a line of text at each prompt; an empty line to exit"); + loop + Put(": "); + Get_Line (Line, N); + Put_Line (Line (1..N) ); + exit when N=0; + end loop; + end Example; + @end group + @end smallexample + + @noindent + Select @code{File}, then @code{Save as}, and enter the file name + @file{example.adb}. + + @item @emph{Updating the project file} + + Add @code{Example} as a new main unit for the project: + @enumerate a + @item + Select @code{Project}, then @code{Edit Project Properties}. + + @item + Select the @code{Main files} tab, click @code{Add}, then + select the file @file{example.adb} from the list, and + click @code{Open}. + You will see the file name appear in the list of main units + + @item + Click @code{OK} + @end enumerate + + @item @emph{Building/running the executable} + + To build the executable + select @code{Build}, then @code{Make}, and then choose @file{example.adb}. + + Run the program to see its effect (in the Messages area). + Each line that you enter is displayed; an empty line will + cause the loop to exit and the program to terminate. + + @item @emph{Debugging the program} + + Note that the @option{-g} switches to @command{gcc} and @command{gnatlink}, + which are required for debugging, are on by default when you create + a new project. + Thus unless you intentionally remove these settings, you will be able + to debug any program that you develop using GPS. + + @enumerate a + @item @emph{Initializing} + + Select @code{Debug}, then @code{Initialize}, then @file{example} + + @item @emph{Setting a breakpoint} + + After performing the initialization step, you will observe a small + icon to the right of each line number. + This serves as a toggle for breakpoints; clicking the icon will + set a breakpoint at the corresponding line (the icon will change to + a red circle with an ``x''), and clicking it again + will remove the breakpoint / reset the icon. + + For purposes of this example, set a breakpoint at line 10 (the + statement @code{Put_Line@ (Line@ (1..N));} + + @item @emph{Starting program execution} + + Select @code{Debug}, then @code{Run}. When the + @code{Program Arguments} window appears, click @code{OK}. + A console window will appear; enter some line of text, + e.g. @code{abcde}, at the prompt. + The program will pause execution when it gets to the + breakpoint, and the corresponding line is highlighted. + + @item @emph{Examining a variable} + + Move the mouse over one of the occurrences of the variable @code{N}. + You will see the value (5) displayed, in ``tool tip'' fashion. + Right click on @code{N}, select @code{Debug}, then select @code{Display N}. + You will see information about @code{N} appear in the @code{Debugger Data} + pane, showing the value as 5. + + + @item @emph{Assigning a new value to a variable} + + Right click on the @code{N} in the @code{Debugger Data} pane, and + select @code{Set value of N}. + When the input window appears, enter the value @code{4} and click + @code{OK}. + This value does not automatically appear in the @code{Debugger Data} + pane; to see it, right click again on the @code{N} in the + @code{Debugger Data} pane and select @code{Update value}. + The new value, 4, will appear in red. + + @item @emph{Single stepping} + + Select @code{Debug}, then @code{Next}. + This will cause the next statement to be executed, in this case the + call of @code{Put_Line} with the string slice. + Notice in the console window that the displayed string is simply + @code{abcd} and not @code{abcde} which you had entered. + This is because the upper bound of the slice is now 4 rather than 5. + + @item @emph{Removing a breakpoint} + + Toggle the breakpoint icon at line 10. + + @item @emph{Resuming execution from a breakpoint} + + Select @code{Debug}, then @code{Continue}. + The program will reach the next iteration of the loop, and + wait for input after displaying the prompt. + This time, just hit the @kbd{Enter} key. + The value of @code{N} will be 0, and the program will terminate. + The console window will disappear. + @end enumerate + @end enumerate + + + @node Introduction to Glide and GVD + @section Introduction to Glide and GVD + @cindex Glide + @cindex GVD + @noindent + This section describes the main features of Glide, + a GNAT graphical IDE, and also shows how to use the basic commands in GVD, + the GNU Visual Debugger. + These tools may be present in addition to, or in place of, GPS on some + platforms. + Additional information on Glide and GVD may be found + in the on-line help for these tools. + + @menu + * Building a New Program with Glide:: + * Simple Debugging with GVD:: + * Other Glide Features:: + @end menu + + @node Building a New Program with Glide + @subsection Building a New Program with Glide + @noindent + The simplest way to invoke Glide is to enter @command{glide} + at the command prompt. It will generally be useful to issue this + as a background command, thus allowing you to continue using + your command window for other purposes while Glide is running: + + @smallexample + $ glide& + @end smallexample + + @noindent + Glide will start up with an initial screen displaying the top-level menu items + as well as some other information. The menu selections are as follows + @itemize @bullet + @item @code{Buffers} + @item @code{Files} + @item @code{Tools} + @item @code{Edit} + @item @code{Search} + @item @code{Mule} + @item @code{Glide} + @item @code{Help} + @end itemize + + @noindent + For this introductory example, you will need to create a new Ada source file. + First, select the @code{Files} menu. This will pop open a menu with around + a dozen or so items. To create a file, select the @code{Open file...} choice. + Depending on the platform, you may see a pop-up window where you can browse + to an appropriate directory and then enter the file name, or else simply + see a line at the bottom of the Glide window where you can likewise enter + the file name. Note that in Glide, when you attempt to open a non-existent + file, the effect is to create a file with that name. For this example enter + @file{hello.adb} as the name of the file. + + A new buffer will now appear, occupying the entire Glide window, + with the file name at the top. The menu selections are slightly different + from the ones you saw on the opening screen; there is an @code{Entities} item, + and in place of @code{Glide} there is now an @code{Ada} item. Glide uses + the file extension to identify the source language, so @file{adb} indicates + an Ada source file. + + You will enter some of the source program lines explicitly, + and use the syntax-oriented template mechanism to enter other lines. + First, type the following text: + @smallexample + with Ada.Text_IO; use Ada.Text_IO; + procedure Hello is + begin + @end smallexample + + @noindent + Observe that Glide uses different colors to distinguish reserved words from + identifiers. Also, after the @code{procedure Hello is} line, the cursor is + automatically indented in anticipation of declarations. When you enter + @code{begin}, Glide recognizes that there are no declarations and thus places + @code{begin} flush left. But after the @code{begin} line the cursor is again + indented, where the statement(s) will be placed. + + The main part of the program will be a @code{for} loop. Instead of entering + the text explicitly, however, use a statement template. Select the @code{Ada} + item on the top menu bar, move the mouse to the @code{Statements} item, + and you will see a large selection of alternatives. Choose @code{for loop}. + You will be prompted (at the bottom of the buffer) for a loop name; + simply press the @key{Enter} key since a loop name is not needed. + You should see the beginning of a @code{for} loop appear in the source + program window. You will now be prompted for the name of the loop variable; + enter a line with the identifier @code{ind} (lower case). Note that, + by default, Glide capitalizes the name (you can override such behavior + if you wish, although this is outside the scope of this introduction). + Next, Glide prompts you for the loop range; enter a line containing + @code{1..5} and you will see this also appear in the source program, + together with the remaining elements of the @code{for} loop syntax. + + Next enter the statement (with an intentional error, a missing semicolon) + that will form the body of the loop: + @smallexample + Put_Line("Hello, World" & Integer'Image(I)) + @end smallexample + + @noindent + Finally, type @code{end Hello;} as the last line in the program. + Now save the file: choose the @code{File} menu item, and then the + @code{Save buffer} selection. You will see a message at the bottom + of the buffer confirming that the file has been saved. + + You are now ready to attempt to build the program. Select the @code{Ada} + item from the top menu bar. Although we could choose simply to compile + the file, we will instead attempt to do a build (which invokes + @command{gnatmake}) since, if the compile is successful, we want to build + an executable. Thus select @code{Ada build}. This will fail because of the + compilation error, and you will notice that the Glide window has been split: + the top window contains the source file, and the bottom window contains the + output from the GNAT tools. Glide allows you to navigate from a compilation + error to the source file position corresponding to the error: click the + middle mouse button (or simultaneously press the left and right buttons, + on a two-button mouse) on the diagnostic line in the tool window. The + focus will shift to the source window, and the cursor will be positioned + on the character at which the error was detected. + + Correct the error: type in a semicolon to terminate the statement. + Although you can again save the file explicitly, you can also simply invoke + @code{Ada} @result{} @code{Build} and you will be prompted to save the file. + This time the build will succeed; the tool output window shows you the + options that are supplied by default. The GNAT tools' output (e.g. + object and ALI files, executable) will go in the directory from which + Glide was launched. + + To execute the program, choose @code{Ada} and then @code{Run}. + You should see the program's output displayed in the bottom window: + + @smallexample + Hello, world 1 + Hello, world 2 + Hello, world 3 + Hello, world 4 + Hello, world 5 + @end smallexample + + @node Simple Debugging with GVD + @subsection Simple Debugging with GVD + + @noindent + This section describes how to set breakpoints, examine/modify variables, + and step through execution. + + In order to enable debugging, you need to pass the @option{-g} switch + to both the compiler and to @command{gnatlink}. If you are using + the command line, passing @option{-g} to @command{gnatmake} will have + this effect. You can then launch GVD, e.g. on the @code{hello} program, + by issuing the command: + + @smallexample + $ gvd hello + @end smallexample + + @noindent + If you are using Glide, then @option{-g} is passed to the relevant tools + by default when you do a build. Start the debugger by selecting the + @code{Ada} menu item, and then @code{Debug}. + + GVD comes up in a multi-part window. One pane shows the names of files + comprising your executable; another pane shows the source code of the current + unit (initially your main subprogram), another pane shows the debugger output + and user interactions, and the fourth pane (the data canvas at the top + of the window) displays data objects that you have selected. + + To the left of the source file pane, you will notice green dots adjacent + to some lines. These are lines for which object code exists and where + breakpoints can thus be set. You set/reset a breakpoint by clicking + the green dot. When a breakpoint is set, the dot is replaced by an @code{X} + in a red circle. Clicking the circle toggles the breakpoint off, + and the red circle is replaced by the green dot. + + For this example, set a breakpoint at the statement where @code{Put_Line} + is invoked. + + Start program execution by selecting the @code{Run} button on the top menu bar. + (The @code{Start} button will also start your program, but it will + cause program execution to break at the entry to your main subprogram.) + Evidence of reaching the breakpoint will appear: the source file line will be + highlighted, and the debugger interactions pane will display + a relevant message. + + You can examine the values of variables in several ways. Move the mouse + over an occurrence of @code{Ind} in the @code{for} loop, and you will see + the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind} + and select @code{Display Ind}; a box showing the variable's name and value + will appear in the data canvas. + + Although a loop index is a constant with respect to Ada semantics, + you can change its value in the debugger. Right-click in the box + for @code{Ind}, and select the @code{Set Value of Ind} item. + Enter @code{2} as the new value, and press @command{OK}. + The box for @code{Ind} shows the update. + + Press the @code{Step} button on the top menu bar; this will step through + one line of program text (the invocation of @code{Put_Line}), and you can + observe the effect of having modified @code{Ind} since the value displayed + is @code{2}. + + Remove the breakpoint, and resume execution by selecting the @code{Cont} + button. You will see the remaining output lines displayed in the debugger + interaction window, along with a message confirming normal program + termination. + + @node Other Glide Features + @subsection Other Glide Features + + @noindent + You may have observed that some of the menu selections contain abbreviations; + e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu. + These are @emph{shortcut keys} that you can use instead of selecting + menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means + @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead + of selecting @code{Files} and then @code{Open file...}. + + To abort a Glide command, type @key{Ctrl-g}. + + If you want Glide to start with an existing source file, you can either + launch Glide as above and then open the file via @code{Files} @result{} + @code{Open file...}, or else simply pass the name of the source file + on the command line: + + @smallexample + $ glide hello.adb& + @end smallexample + + @noindent + While you are using Glide, a number of @emph{buffers} exist. + You create some explicitly; e.g., when you open/create a file. + Others arise as an effect of the commands that you issue; e.g., the buffer + containing the output of the tools invoked during a build. If a buffer + is hidden, you can bring it into a visible window by first opening + the @code{Buffers} menu and then selecting the desired entry. + + If a buffer occupies only part of the Glide screen and you want to expand it + to fill the entire screen, then click in the buffer and then select + @code{Files} @result{} @code{One Window}. + + If a window is occupied by one buffer and you want to split the window + to bring up a second buffer, perform the following steps: + @itemize @bullet + @item Select @code{Files} @result{} @code{Split Window}; + this will produce two windows each of which holds the original buffer + (these are not copies, but rather different views of the same buffer contents) + + @item With the focus in one of the windows, + select the desired buffer from the @code{Buffers} menu + @end itemize + + @noindent + To exit from Glide, choose @code{Files} @result{} @code{Exit}. + @end ifclear + + @node The GNAT Compilation Model + @chapter The GNAT Compilation Model + @cindex GNAT compilation model + @cindex Compilation model + + @menu + * Source Representation:: + * Foreign Language Representation:: + * File Naming Rules:: + * Using Other File Names:: + * Alternative File Naming Schemes:: + * Generating Object Files:: + * Source Dependencies:: + * The Ada Library Information Files:: + * Binding an Ada Program:: + * Mixed Language Programming:: + * Building Mixed Ada & C++ Programs:: + * Comparison between GNAT and C/C++ Compilation Models:: + * Comparison between GNAT and Conventional Ada Library Models:: + @ifset vms + * Placement of temporary files:: + @end ifset + @end menu + + @noindent + This chapter describes the compilation model used by GNAT. Although + similar to that used by other languages, such as C and C++, this model + is substantially different from the traditional Ada compilation models, + which are based on a library. The model is initially described without + reference to the library-based model. If you have not previously used an + Ada compiler, you need only read the first part of this chapter. The + last section describes and discusses the differences between the GNAT + model and the traditional Ada compiler models. If you have used other + Ada compilers, this section will help you to understand those + differences, and the advantages of the GNAT model. + + @node Source Representation + @section Source Representation + @cindex Latin-1 + + @noindent + Ada source programs are represented in standard text files, using + Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar + 7-bit ASCII set, plus additional characters used for + representing foreign languages (@pxref{Foreign Language Representation} + for support of non-USA character sets). The format effector characters + are represented using their standard ASCII encodings, as follows: + + @table @code + @item VT + @findex VT + Vertical tab, @code{16#0B#} + + @item HT + @findex HT + Horizontal tab, @code{16#09#} + + @item CR + @findex CR + Carriage return, @code{16#0D#} + + @item LF + @findex LF + Line feed, @code{16#0A#} + + @item FF + @findex FF + Form feed, @code{16#0C#} + @end table + + @noindent + Source files are in standard text file format. In addition, GNAT will + recognize a wide variety of stream formats, in which the end of physical + physical lines is marked by any of the following sequences: + @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful + in accommodating files that are imported from other operating systems. + + @cindex End of source file + @cindex Source file, end + @findex SUB + The end of a source file is normally represented by the physical end of + file. However, the control character @code{16#1A#} (@code{SUB}) is also + recognized as signalling the end of the source file. Again, this is + provided for compatibility with other operating systems where this + code is used to represent the end of file. + + Each file contains a single Ada compilation unit, including any pragmas + associated with the unit. For example, this means you must place a + package declaration (a package @dfn{spec}) and the corresponding body in + separate files. An Ada @dfn{compilation} (which is a sequence of + compilation units) is represented using a sequence of files. Similarly, + you will place each subunit or child unit in a separate file. + + @node Foreign Language Representation + @section Foreign Language Representation + + @noindent + GNAT supports the standard character sets defined in Ada 95 as well as + several other non-standard character sets for use in localized versions + of the compiler (@pxref{Character Set Control}). + @menu + * Latin-1:: + * Other 8-Bit Codes:: + * Wide Character Encodings:: + @end menu + + @node Latin-1 + @subsection Latin-1 + @cindex Latin-1 + + @noindent + The basic character set is Latin-1. This character set is defined by ISO + standard 8859, part 1. The lower half (character codes @code{16#00#} + ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half + is used to represent additional characters. These include extended letters + used by European languages, such as French accents, the vowels with umlauts + used in German, and the extra letter A-ring used in Swedish. + + @findex Ada.Characters.Latin_1 + For a complete list of Latin-1 codes and their encodings, see the source + file of library unit @code{Ada.Characters.Latin_1} in file + @file{a-chlat1.ads}. + You may use any of these extended characters freely in character or + string literals. In addition, the extended characters that represent + letters can be used in identifiers. + + @node Other 8-Bit Codes + @subsection Other 8-Bit Codes + + @noindent + GNAT also supports several other 8-bit coding schemes: + + @table @asis + @item ISO 8859-2 (Latin-2) + @cindex Latin-2 + @cindex ISO 8859-2 + Latin-2 letters allowed in identifiers, with uppercase and lowercase + equivalence. + + @item ISO 8859-3 (Latin-3) + @cindex Latin-3 + @cindex ISO 8859-3 + Latin-3 letters allowed in identifiers, with uppercase and lowercase + equivalence. + + @item ISO 8859-4 (Latin-4) + @cindex Latin-4 + @cindex ISO 8859-4 + Latin-4 letters allowed in identifiers, with uppercase and lowercase + equivalence. + + @item ISO 8859-5 (Cyrillic) + @cindex ISO 8859-5 + @cindex Cyrillic + ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and + lowercase equivalence. + + @item ISO 8859-15 (Latin-9) + @cindex ISO 8859-15 + @cindex Latin-9 + ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and + lowercase equivalence + + @item IBM PC (code page 437) + @cindex code page 437 + This code page is the normal default for PCs in the U.S. It corresponds + to the original IBM PC character set. This set has some, but not all, of + the extended Latin-1 letters, but these letters do not have the same + encoding as Latin-1. In this mode, these letters are allowed in + identifiers with uppercase and lowercase equivalence. + + @item IBM PC (code page 850) + @cindex code page 850 + This code page is a modification of 437 extended to include all the + Latin-1 letters, but still not with the usual Latin-1 encoding. In this + mode, all these letters are allowed in identifiers with uppercase and + lowercase equivalence. + + @item Full Upper 8-bit + Any character in the range 80-FF allowed in identifiers, and all are + considered distinct. In other words, there are no uppercase and lowercase + equivalences in this range. This is useful in conjunction with + certain encoding schemes used for some foreign character sets (e.g. + the typical method of representing Chinese characters on the PC). + + @item No Upper-Half + No upper-half characters in the range 80-FF are allowed in identifiers. + This gives Ada 83 compatibility for identifier names. + @end table + + @noindent + For precise data on the encodings permitted, and the uppercase and lowercase + equivalences that are recognized, see the file @file{csets.adb} in + the GNAT compiler sources. You will need to obtain a full source release + of GNAT to obtain this file. + + @node Wide Character Encodings + @subsection Wide Character Encodings + + @noindent + GNAT allows wide character codes to appear in character and string + literals, and also optionally in identifiers, by means of the following + possible encoding schemes: + + @table @asis + + @item Hex Coding + In this encoding, a wide character is represented by the following five + character sequence: + + @smallexample + ESC a b c d + @end smallexample + + @noindent + Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal + characters (using uppercase letters) of the wide character code. For + example, ESC A345 is used to represent the wide character with code + @code{16#A345#}. + This scheme is compatible with use of the full Wide_Character set. + + @item Upper-Half Coding + @cindex Upper-Half Coding + The wide character with encoding @code{16#abcd#} where the upper bit is on + (in other words, ``a'' is in the range 8-F) is represented as two bytes, + @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control + character, but is not required to be in the upper half. This method can + be also used for shift-JIS or EUC, where the internal coding matches the + external coding. + + @item Shift JIS Coding + @cindex Shift JIS Coding + A wide character is represented by a two-character sequence, + @code{16#ab#} and + @code{16#cd#}, with the restrictions described for upper-half encoding as + described above. The internal character code is the corresponding JIS + character according to the standard algorithm for Shift-JIS + conversion. Only characters defined in the JIS code set table can be + used with this encoding method. + + @item EUC Coding + @cindex EUC Coding + A wide character is represented by a two-character sequence + @code{16#ab#} and + @code{16#cd#}, with both characters being in the upper half. The internal + character code is the corresponding JIS character according to the EUC + encoding algorithm. Only characters defined in the JIS code set table + can be used with this encoding method. + + @item UTF-8 Coding + A wide character is represented using + UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO + 10646-1/Am.2. Depending on the character value, the representation + is a one, two, or three byte sequence: + @smallexample + @iftex + @leftskip=.7cm + @end iftex + 16#0000#-16#007f#: 2#0xxxxxxx# + 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# + 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# + + @end smallexample + + @noindent + where the xxx bits correspond to the left-padded bits of the + 16-bit character value. Note that all lower half ASCII characters + are represented as ASCII bytes and all upper half characters and + other wide characters are represented as sequences of upper-half + (The full UTF-8 scheme allows for encoding 31-bit characters as + 6-byte sequences, but in this implementation, all UTF-8 sequences + of four or more bytes length will be treated as illegal). + @item Brackets Coding + In this encoding, a wide character is represented by the following eight + character sequence: + + @smallexample + [ " a b c d " ] + @end smallexample + + @noindent + Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal + characters (using uppercase letters) of the wide character code. For + example, [``A345''] is used to represent the wide character with code + @code{16#A345#}. It is also possible (though not required) to use the + Brackets coding for upper half characters. For example, the code + @code{16#A3#} can be represented as @code{[``A3'']}. + + This scheme is compatible with use of the full Wide_Character set, + and is also the method used for wide character encoding in the standard + ACVC (Ada Compiler Validation Capability) test suite distributions. + + @end table + + @noindent + Note: Some of these coding schemes do not permit the full use of the + Ada 95 character set. For example, neither Shift JIS, nor EUC allow the + use of the upper half of the Latin-1 set. + + @node File Naming Rules + @section File Naming Rules + + @noindent + The default file name is determined by the name of the unit that the + file contains. The name is formed by taking the full expanded name of + the unit and replacing the separating dots with hyphens and using + ^lowercase^uppercase^ for all letters. + + An exception arises if the file name generated by the above rules starts + with one of the characters + @ifset vms + A,G,I, or S, + @end ifset + @ifclear vms + a,g,i, or s, + @end ifclear + and the second character is a + minus. In this case, the character ^tilde^dollar sign^ is used in place + of the minus. The reason for this special rule is to avoid clashes with + the standard names for child units of the packages System, Ada, + Interfaces, and GNAT, which use the prefixes + @ifset vms + S- A- I- and G- + @end ifset + @ifclear vms + s- a- i- and g- + @end ifclear + respectively. + + The file extension is @file{.ads} for a spec and + @file{.adb} for a body. The following list shows some + examples of these rules. + + @table @file + @item main.ads + Main (spec) + @item main.adb + Main (body) + @item arith_functions.ads + Arith_Functions (package spec) + @item arith_functions.adb + Arith_Functions (package body) + @item func-spec.ads + Func.Spec (child package spec) + @item func-spec.adb + Func.Spec (child package body) + @item main-sub.adb + Sub (subunit of Main) + @item ^a~bad.adb^A$BAD.ADB^ + A.Bad (child package body) + @end table + + @noindent + Following these rules can result in excessively long + file names if corresponding + unit names are long (for example, if child units or subunits are + heavily nested). An option is available to shorten such long file names + (called file name ``krunching''). This may be particularly useful when + programs being developed with GNAT are to be used on operating systems + with limited file name lengths. @xref{Using gnatkr}. + + Of course, no file shortening algorithm can guarantee uniqueness over + all possible unit names; if file name krunching is used, it is your + responsibility to ensure no name clashes occur. Alternatively you + can specify the exact file names that you want used, as described + in the next section. Finally, if your Ada programs are migrating from a + compiler with a different naming convention, you can use the gnatchop + utility to produce source files that follow the GNAT naming conventions. + (For details @pxref{Renaming Files Using gnatchop}.) + + Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating + systems, case is not significant. So for example on @code{Windows XP} + if the canonical name is @code{main-sub.adb}, you can use the file name + @code{Main-Sub.adb} instead. However, case is significant for other + operating systems, so for example, if you want to use other than + canonically cased file names on a Unix system, you need to follow + the procedures described in the next section. + + @node Using Other File Names + @section Using Other File Names + @cindex File names + + @noindent + In the previous section, we have described the default rules used by + GNAT to determine the file name in which a given unit resides. It is + often convenient to follow these default rules, and if you follow them, + the compiler knows without being explicitly told where to find all + the files it needs. + + However, in some cases, particularly when a program is imported from + another Ada compiler environment, it may be more convenient for the + programmer to specify which file names contain which units. GNAT allows + arbitrary file names to be used by means of the Source_File_Name pragma. + The form of this pragma is as shown in the following examples: + @cindex Source_File_Name pragma + + @smallexample @c ada + @cartouche + pragma Source_File_Name (My_Utilities.Stacks, + Spec_File_Name => "myutilst_a.ada"); + pragma Source_File_name (My_Utilities.Stacks, + Body_File_Name => "myutilst.ada"); + @end cartouche + @end smallexample + + @noindent + As shown in this example, the first argument for the pragma is the unit + name (in this example a child unit). The second argument has the form + of a named association. The identifier + indicates whether the file name is for a spec or a body; + the file name itself is given by a string literal. + + The source file name pragma is a configuration pragma, which means that + normally it will be placed in the @file{gnat.adc} + file used to hold configuration + pragmas that apply to a complete compilation environment. + For more details on how the @file{gnat.adc} file is created and used + @pxref{Handling of Configuration Pragmas} + @cindex @file{gnat.adc} + + @ifclear vms + GNAT allows completely arbitrary file names to be specified using the + source file name pragma. However, if the file name specified has an + extension other than @file{.ads} or @file{.adb} it is necessary to use + a special syntax when compiling the file. The name in this case must be + preceded by the special sequence @code{-x} followed by a space and the name + of the language, here @code{ada}, as in: + + @smallexample + $ gcc -c -x ada peculiar_file_name.sim + @end smallexample + @end ifclear + + @noindent + @code{gnatmake} handles non-standard file names in the usual manner (the + non-standard file name for the main program is simply used as the + argument to gnatmake). Note that if the extension is also non-standard, + then it must be included in the gnatmake command, it may not be omitted. + + @node Alternative File Naming Schemes + @section Alternative File Naming Schemes + @cindex File naming schemes, alternative + @cindex File names + + In the previous section, we described the use of the @code{Source_File_Name} + pragma to allow arbitrary names to be assigned to individual source files. + However, this approach requires one pragma for each file, and especially in + large systems can result in very long @file{gnat.adc} files, and also create + a maintenance problem. + + GNAT also provides a facility for specifying systematic file naming schemes + other than the standard default naming scheme previously described. An + alternative scheme for naming is specified by the use of + @code{Source_File_Name} pragmas having the following format: + @cindex Source_File_Name pragma + + @smallexample @c ada + pragma Source_File_Name ( + Spec_File_Name => FILE_NAME_PATTERN + [,Casing => CASING_SPEC] + [,Dot_Replacement => STRING_LITERAL]); + + pragma Source_File_Name ( + Body_File_Name => FILE_NAME_PATTERN + [,Casing => CASING_SPEC] + [,Dot_Replacement => STRING_LITERAL]); + + pragma Source_File_Name ( + Subunit_File_Name => FILE_NAME_PATTERN + [,Casing => CASING_SPEC] + [,Dot_Replacement => STRING_LITERAL]); + + FILE_NAME_PATTERN ::= STRING_LITERAL + CASING_SPEC ::= Lowercase | Uppercase | Mixedcase + @end smallexample + + @noindent + The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. + It contains a single asterisk character, and the unit name is substituted + systematically for this asterisk. The optional parameter + @code{Casing} indicates + whether the unit name is to be all upper-case letters, all lower-case letters, + or mixed-case. If no + @code{Casing} parameter is used, then the default is all + ^lower-case^upper-case^. + + The optional @code{Dot_Replacement} string is used to replace any periods + that occur in subunit or child unit names. If no @code{Dot_Replacement} + argument is used then separating dots appear unchanged in the resulting + file name. + Although the above syntax indicates that the + @code{Casing} argument must appear + before the @code{Dot_Replacement} argument, but it + is also permissible to write these arguments in the opposite order. + + As indicated, it is possible to specify different naming schemes for + bodies, specs, and subunits. Quite often the rule for subunits is the + same as the rule for bodies, in which case, there is no need to give + a separate @code{Subunit_File_Name} rule, and in this case the + @code{Body_File_name} rule is used for subunits as well. + + The separate rule for subunits can also be used to implement the rather + unusual case of a compilation environment (e.g. a single directory) which + contains a subunit and a child unit with the same unit name. Although + both units cannot appear in the same partition, the Ada Reference Manual + allows (but does not require) the possibility of the two units coexisting + in the same environment. + + The file name translation works in the following steps: + + @itemize @bullet + + @item + If there is a specific @code{Source_File_Name} pragma for the given unit, + then this is always used, and any general pattern rules are ignored. + + @item + If there is a pattern type @code{Source_File_Name} pragma that applies to + the unit, then the resulting file name will be used if the file exists. If + more than one pattern matches, the latest one will be tried first, and the + first attempt resulting in a reference to a file that exists will be used. + + @item + If no pattern type @code{Source_File_Name} pragma that applies to the unit + for which the corresponding file exists, then the standard GNAT default + naming rules are used. + + @end itemize + + @noindent + As an example of the use of this mechanism, consider a commonly used scheme + in which file names are all lower case, with separating periods copied + unchanged to the resulting file name, and specs end with @file{.1.ada}, and + bodies end with @file{.2.ada}. GNAT will follow this scheme if the following + two pragmas appear: + + @smallexample @c ada + pragma Source_File_Name + (Spec_File_Name => "*.1.ada"); + pragma Source_File_Name + (Body_File_Name => "*.2.ada"); + @end smallexample + + @noindent + The default GNAT scheme is actually implemented by providing the following + default pragmas internally: + + @smallexample @c ada + pragma Source_File_Name + (Spec_File_Name => "*.ads", Dot_Replacement => "-"); + pragma Source_File_Name + (Body_File_Name => "*.adb", Dot_Replacement => "-"); + @end smallexample + + @noindent + Our final example implements a scheme typically used with one of the + Ada 83 compilers, where the separator character for subunits was ``__'' + (two underscores), specs were identified by adding @file{_.ADA}, bodies + by adding @file{.ADA}, and subunits by + adding @file{.SEP}. All file names were + upper case. Child units were not present of course since this was an + Ada 83 compiler, but it seems reasonable to extend this scheme to use + the same double underscore separator for child units. + + @smallexample @c ada + pragma Source_File_Name + (Spec_File_Name => "*_.ADA", + Dot_Replacement => "__", + Casing = Uppercase); + pragma Source_File_Name + (Body_File_Name => "*.ADA", + Dot_Replacement => "__", + Casing = Uppercase); + pragma Source_File_Name + (Subunit_File_Name => "*.SEP", + Dot_Replacement => "__", + Casing = Uppercase); + @end smallexample + + @node Generating Object Files + @section Generating Object Files + + @noindent + An Ada program consists of a set of source files, and the first step in + compiling the program is to generate the corresponding object files. + These are generated by compiling a subset of these source files. + The files you need to compile are the following: + + @itemize @bullet + @item + If a package spec has no body, compile the package spec to produce the + object file for the package. + + @item + If a package has both a spec and a body, compile the body to produce the + object file for the package. The source file for the package spec need + not be compiled in this case because there is only one object file, which + contains the code for both the spec and body of the package. + + @item + For a subprogram, compile the subprogram body to produce the object file + for the subprogram. The spec, if one is present, is as usual in a + separate file, and need not be compiled. + + @item + @cindex Subunits + In the case of subunits, only compile the parent unit. A single object + file is generated for the entire subunit tree, which includes all the + subunits. + + @item + Compile child units independently of their parent units + (though, of course, the spec of all the ancestor unit must be present in order + to compile a child unit). + + @item + @cindex Generics + Compile generic units in the same manner as any other units. The object + files in this case are small dummy files that contain at most the + flag used for elaboration checking. This is because GNAT always handles generic + instantiation by means of macro expansion. However, it is still necessary to + compile generic units, for dependency checking and elaboration purposes. + @end itemize + + @noindent + The preceding rules describe the set of files that must be compiled to + generate the object files for a program. Each object file has the same + name as the corresponding source file, except that the extension is + @file{.o} as usual. + + You may wish to compile other files for the purpose of checking their + syntactic and semantic correctness. For example, in the case where a + package has a separate spec and body, you would not normally compile the + spec. However, it is convenient in practice to compile the spec to make + sure it is error-free before compiling clients of this spec, because such + compilations will fail if there is an error in the spec. + + GNAT provides an option for compiling such files purely for the + purposes of checking correctness; such compilations are not required as + part of the process of building a program. To compile a file in this + checking mode, use the @option{-gnatc} switch. + + @node Source Dependencies + @section Source Dependencies + + @noindent + A given object file clearly depends on the source file which is compiled + to produce it. Here we are using @dfn{depends} in the sense of a typical + @code{make} utility; in other words, an object file depends on a source + file if changes to the source file require the object file to be + recompiled. + In addition to this basic dependency, a given object may depend on + additional source files as follows: + + @itemize @bullet + @item + If a file being compiled @code{with}'s a unit @var{X}, the object file + depends on the file containing the spec of unit @var{X}. This includes + files that are @code{with}'ed implicitly either because they are parents + of @code{with}'ed child units or they are run-time units required by the + language constructs used in a particular unit. + + @item + If a file being compiled instantiates a library level generic unit, the + object file depends on both the spec and body files for this generic + unit. + + @item + If a file being compiled instantiates a generic unit defined within a + package, the object file depends on the body file for the package as + well as the spec file. + + @item + @findex Inline + @cindex @option{-gnatn} switch + If a file being compiled contains a call to a subprogram for which + pragma @code{Inline} applies and inlining is activated with the + @option{-gnatn} switch, the object file depends on the file containing the + body of this subprogram as well as on the file containing the spec. Note + that for inlining to actually occur as a result of the use of this switch, + it is necessary to compile in optimizing mode. + + @cindex @option{-gnatN} switch + The use of @option{-gnatN} activates a more extensive inlining optimization + that is performed by the front end of the compiler. This inlining does + not require that the code generation be optimized. Like @option{-gnatn}, + the use of this switch generates additional dependencies. + Note that + @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary + to specify both options. + + @item + If an object file O depends on the proper body of a subunit through inlining + or instantiation, it depends on the parent unit of the subunit. This means that + any modification of the parent unit or one of its subunits affects the + compilation of O. + + @item + The object file for a parent unit depends on all its subunit body files. + + @item + The previous two rules meant that for purposes of computing dependencies and + recompilation, a body and all its subunits are treated as an indivisible whole. + + @noindent + These rules are applied transitively: if unit @code{A} @code{with}'s + unit @code{B}, whose elaboration calls an inlined procedure in package + @code{C}, the object file for unit @code{A} will depend on the body of + @code{C}, in file @file{c.adb}. + + The set of dependent files described by these rules includes all the + files on which the unit is semantically dependent, as described in the + Ada 95 Language Reference Manual. However, it is a superset of what the + ARM describes, because it includes generic, inline, and subunit dependencies. + + An object file must be recreated by recompiling the corresponding source + file if any of the source files on which it depends are modified. For + example, if the @code{make} utility is used to control compilation, + the rule for an Ada object file must mention all the source files on + which the object file depends, according to the above definition. + The determination of the necessary + recompilations is done automatically when one uses @code{gnatmake}. + @end itemize + + @node The Ada Library Information Files + @section The Ada Library Information Files + @cindex Ada Library Information files + @cindex @file{ALI} files + + @noindent + Each compilation actually generates two output files. The first of these + is the normal object file that has a @file{.o} extension. The second is a + text file containing full dependency information. It has the same + name as the source file, but an @file{.ali} extension. + This file is known as the Ada Library Information (@file{ALI}) file. + The following information is contained in the @file{ALI} file. + + @itemize @bullet + @item + Version information (indicates which version of GNAT was used to compile + the unit(s) in question) + + @item + Main program information (including priority and time slice settings, + as well as the wide character encoding used during compilation). + + @item + List of arguments used in the @code{gcc} command for the compilation + + @item + Attributes of the unit, including configuration pragmas used, an indication + of whether the compilation was successful, exception model used etc. + + @item + A list of relevant restrictions applying to the unit (used for consistency) + checking. + + @item + Categorization information (e.g. use of pragma @code{Pure}). + + @item + Information on all @code{with}'ed units, including presence of + @code{Elaborate} or @code{Elaborate_All} pragmas. + + @item + Information from any @code{Linker_Options} pragmas used in the unit + + @item + Information on the use of @code{Body_Version} or @code{Version} + attributes in the unit. + + @item + Dependency information. This is a list of files, together with + time stamp and checksum information. These are files on which + the unit depends in the sense that recompilation is required + if any of these units are modified. + + @item + Cross-reference data. Contains information on all entities referenced + in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to + provide cross-reference information. + + @end itemize + + @noindent + For a full detailed description of the format of the @file{ALI} file, + see the source of the body of unit @code{Lib.Writ}, contained in file + @file{lib-writ.adb} in the GNAT compiler sources. + + @node Binding an Ada Program + @section Binding an Ada Program + + @noindent + When using languages such as C and C++, once the source files have been + compiled the only remaining step in building an executable program + is linking the object modules together. This means that it is possible to + link an inconsistent version of a program, in which two units have + included different versions of the same header. + + The rules of Ada do not permit such an inconsistent program to be built. + For example, if two clients have different versions of the same package, + it is illegal to build a program containing these two clients. + These rules are enforced by the GNAT binder, which also determines an + elaboration order consistent with the Ada rules. + + The GNAT binder is run after all the object files for a program have + been created. It is given the name of the main program unit, and from + this it determines the set of units required by the program, by reading the + corresponding ALI files. It generates error messages if the program is + inconsistent or if no valid order of elaboration exists. + + If no errors are detected, the binder produces a main program, in Ada by + default, that contains calls to the elaboration procedures of those + compilation unit that require them, followed by + a call to the main program. This Ada program is compiled to generate the + object file for the main program. The name of + the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec + @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the + main program unit. + + Finally, the linker is used to build the resulting executable program, + using the object from the main program from the bind step as well as the + object files for the Ada units of the program. + + @node Mixed Language Programming + @section Mixed Language Programming + @cindex Mixed Language Programming + + @noindent + This section describes how to develop a mixed-language program, + specifically one that comprises units in both Ada and C. + + @menu + * Interfacing to C:: + * Calling Conventions:: + @end menu + + @node Interfacing to C + @subsection Interfacing to C + @noindent + Interfacing Ada with a foreign language such as C involves using + compiler directives to import and/or export entity definitions in each + language---using @code{extern} statements in C, for instance, and the + @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada. For + a full treatment of these topics, read Appendix B, section 1 of the Ada + 95 Language Reference Manual. + + There are two ways to build a program using GNAT that contains some Ada + sources and some foreign language sources, depending on whether or not + the main subprogram is written in Ada. Here is a source example with + the main subprogram in Ada: + + @smallexample + /* file1.c */ + #include + + void print_num (int num) + @{ + printf ("num is %d.\n", num); + return; + @} + + /* file2.c */ + + /* num_from_Ada is declared in my_main.adb */ + extern int num_from_Ada; + + int get_num (void) + @{ + return num_from_Ada; + @} + @end smallexample + + @smallexample @c ada + -- my_main.adb + procedure My_Main is + + -- Declare then export an Integer entity called num_from_Ada + My_Num : Integer := 10; + pragma Export (C, My_Num, "num_from_Ada"); + + -- Declare an Ada function spec for Get_Num, then use + -- C function get_num for the implementation. + function Get_Num return Integer; + pragma Import (C, Get_Num, "get_num"); + + -- Declare an Ada procedure spec for Print_Num, then use + -- C function print_num for the implementation. + procedure Print_Num (Num : Integer); + pragma Import (C, Print_Num, "print_num"); + + begin + Print_Num (Get_Num); + end My_Main; + @end smallexample + + @enumerate + @item + To build this example, first compile the foreign language files to + generate object files: + @smallexample + gcc -c file1.c + gcc -c file2.c + @end smallexample + + @item + Then, compile the Ada units to produce a set of object files and ALI + files: + @smallexample + gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb + @end smallexample + + @item + Run the Ada binder on the Ada main program: + @smallexample + gnatbind my_main.ali + @end smallexample + + @item + Link the Ada main program, the Ada objects and the other language + objects: + @smallexample + gnatlink my_main.ali file1.o file2.o + @end smallexample + @end enumerate + + The last three steps can be grouped in a single command: + @smallexample + gnatmake my_main.adb -largs file1.o file2.o + @end smallexample + + @cindex Binder output file + @noindent + If the main program is in a language other than Ada, then you may have + more than one entry point into the Ada subsystem. You must use a special + binder option to generate callable routines that initialize and + finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). + Calls to the initialization and finalization routines must be inserted + in the main program, or some other appropriate point in the code. The + call to initialize the Ada units must occur before the first Ada + subprogram is called, and the call to finalize the Ada units must occur + after the last Ada subprogram returns. The binder will place the + initialization and finalization subprograms into the + @file{b~@var{xxx}.adb} file where they can be accessed by your C + sources. To illustrate, we have the following example: + + @smallexample + /* main.c */ + extern void adainit (void); + extern void adafinal (void); + extern int add (int, int); + extern int sub (int, int); + + int main (int argc, char *argv[]) + @{ + int a = 21, b = 7; + + adainit(); + + /* Should print "21 + 7 = 28" */ + printf ("%d + %d = %d\n", a, b, add (a, b)); + /* Should print "21 - 7 = 14" */ + printf ("%d - %d = %d\n", a, b, sub (a, b)); + + adafinal(); + @} + @end smallexample + + @smallexample @c ada + -- unit1.ads + package Unit1 is + function Add (A, B : Integer) return Integer; + pragma Export (C, Add, "add"); + end Unit1; + + -- unit1.adb + package body Unit1 is + function Add (A, B : Integer) return Integer is + begin + return A + B; + end Add; + end Unit1; + + -- unit2.ads + package Unit2 is + function Sub (A, B : Integer) return Integer; + pragma Export (C, Sub, "sub"); + end Unit2; + + -- unit2.adb + package body Unit2 is + function Sub (A, B : Integer) return Integer is + begin + return A - B; + end Sub; + end Unit2; + @end smallexample + + @enumerate + @item + The build procedure for this application is similar to the last + example's. First, compile the foreign language files to generate object + files: + @smallexample + gcc -c main.c + @end smallexample + + @item + Next, compile the Ada units to produce a set of object files and ALI + files: + @smallexample + gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb + gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb + @end smallexample + + @item + Run the Ada binder on every generated ALI file. Make sure to use the + @option{-n} option to specify a foreign main program: + @smallexample + gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali + @end smallexample + + @item + Link the Ada main program, the Ada objects and the foreign language + objects. You need only list the last ALI file here: + @smallexample + gnatlink unit2.ali main.o -o exec_file + @end smallexample + + This procedure yields a binary executable called @file{exec_file}. + @end enumerate + + @node Calling Conventions + @subsection Calling Conventions + @cindex Foreign Languages + @cindex Calling Conventions + GNAT follows standard calling sequence conventions and will thus interface + to any other language that also follows these conventions. The following + Convention identifiers are recognized by GNAT: + + @table @code + @cindex Interfacing to Ada + @cindex Other Ada compilers + @cindex Convention Ada + @item Ada + This indicates that the standard Ada calling sequence will be + used and all Ada data items may be passed without any limitations in the + case where GNAT is used to generate both the caller and callee. It is also + possible to mix GNAT generated code and code generated by another Ada + compiler. In this case, the data types should be restricted to simple + cases, including primitive types. Whether complex data types can be passed + depends on the situation. Probably it is safe to pass simple arrays, such + as arrays of integers or floats. Records may or may not work, depending + on whether both compilers lay them out identically. Complex structures + involving variant records, access parameters, tasks, or protected types, + are unlikely to be able to be passed. + + Note that in the case of GNAT running + on a platform that supports DEC Ada 83, a higher degree of compatibility + can be guaranteed, and in particular records are layed out in an identical + manner in the two compilers. Note also that if output from two different + compilers is mixed, the program is responsible for dealing with elaboration + issues. Probably the safest approach is to write the main program in the + version of Ada other than GNAT, so that it takes care of its own elaboration + requirements, and then call the GNAT-generated adainit procedure to ensure + elaboration of the GNAT components. Consult the documentation of the other + Ada compiler for further details on elaboration. + + However, it is not possible to mix the tasking run time of GNAT and + DEC Ada 83, All the tasking operations must either be entirely within + GNAT compiled sections of the program, or entirely within DEC Ada 83 + compiled sections of the program. + + @cindex Interfacing to Assembly + @cindex Convention Assembler + @item Assembler + Specifies assembler as the convention. In practice this has the + same effect as convention Ada (but is not equivalent in the sense of being + considered the same convention). + + @cindex Convention Asm + @findex Asm + @item Asm + Equivalent to Assembler. + + @cindex Interfacing to COBOL + @cindex Convention COBOL + @findex COBOL + @item COBOL + Data will be passed according to the conventions described + in section B.4 of the Ada 95 Reference Manual. + + @findex C + @cindex Interfacing to C + @cindex Convention C + @item C + Data will be passed according to the conventions described + in section B.3 of the Ada 95 Reference Manual. + + @cindex Convention Default + @findex Default + @item Default + Equivalent to C. + + @cindex Convention External + @findex External + @item External + Equivalent to C. + + @findex C++ + @cindex Interfacing to C++ + @cindex Convention C++ + @item CPP + This stands for C++. For most purposes this is identical to C. + See the separate description of the specialized GNAT pragmas relating to + C++ interfacing for further details. + + @findex Fortran + @cindex Interfacing to Fortran + @cindex Convention Fortran + @item Fortran + Data will be passed according to the conventions described + in section B.5 of the Ada 95 Reference Manual. + + @item Intrinsic + This applies to an intrinsic operation, as defined in the Ada 95 + Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, + this means that the body of the subprogram is provided by the compiler itself, + usually by means of an efficient code sequence, and that the user does not + supply an explicit body for it. In an application program, the pragma can + only be applied to the following two sets of names, which the GNAT compiler + recognizes. + + @itemize @bullet + @item + Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_- + Arithmetic. The corresponding subprogram declaration must have + two formal parameters. The + first one must be a signed integer type or a modular type with a binary + modulus, and the second parameter must be of type Natural. + The return type must be the same as the type of the first argument. The size + of this type can only be 8, 16, 32, or 64. + @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/'' + The corresponding operator declaration must have parameters and result type + that have the same root numeric type (for example, all three are long_float + types). This simplifies the definition of operations that use type checking + to perform dimensional checks: + + @smallexample @c ada + type Distance is new Long_Float; + type Time is new Long_Float; + type Velocity is new Long_Float; + function "/" (D : Distance; T : Time) + return Velocity; + pragma Import (Intrinsic, "/"); + @end smallexample + + @noindent + This common idiom is often programmed with a generic definition and an + explicit body. The pragma makes it simpler to introduce such declarations. + It incurs no overhead in compilation time or code size, because it is + implemented as a single machine instruction. + @end itemize + @noindent + + @ifset unw + @findex Stdcall + @cindex Convention Stdcall + @item Stdcall + This is relevant only to NT/Win95 implementations of GNAT, + and specifies that the Stdcall calling sequence will be used, as defined + by the NT API. + + @findex DLL + @cindex Convention DLL + @item DLL + This is equivalent to Stdcall. + + @findex Win32 + @cindex Convention Win32 + @item Win32 + This is equivalent to Stdcall. + @end ifset + + @findex Stubbed + @cindex Convention Stubbed + @item Stubbed + This is a special convention that indicates that the compiler + should provide a stub body that raises @code{Program_Error}. + @end table + + @noindent + GNAT additionally provides a useful pragma @code{Convention_Identifier} + that can be used to parametrize conventions and allow additional synonyms + to be specified. For example if you have legacy code in which the convention + identifier Fortran77 was used for Fortran, you can use the configuration + pragma: + + @smallexample @c ada + pragma Convention_Identifier (Fortran77, Fortran); + @end smallexample + + @noindent + And from now on the identifier Fortran77 may be used as a convention + identifier (for example in an @code{Import} pragma) with the same + meaning as Fortran. + + @node Building Mixed Ada & C++ Programs + @section Building Mixed Ada & C++ Programs + + @noindent + A programmer inexperienced with mixed-language development may find that + building an application containing both Ada and C++ code can be a + challenge. As a matter of fact, interfacing with C++ has not been + standardized in the Ada 95 Reference Manual due to the immaturity of -- + and lack of standards for -- C++ at the time. This section gives a few + hints that should make this task easier. The first section addresses + the differences regarding interfacing with C. The second section + looks into the delicate problem of linking the complete application from + its Ada and C++ parts. The last section gives some hints on how the GNAT + run time can be adapted in order to allow inter-language dispatching + with a new C++ compiler. + + @menu + * Interfacing to C++:: + * Linking a Mixed C++ & Ada Program:: + * A Simple Example:: + * Adapting the Run Time to a New C++ Compiler:: + @end menu + + @node Interfacing to C++ + @subsection Interfacing to C++ + + @noindent + GNAT supports interfacing with C++ compilers generating code that is + compatible with the standard Application Binary Interface of the given + platform. + + @noindent + Interfacing can be done at 3 levels: simple data, subprograms, and + classes. In the first two cases, GNAT offers a specific @var{Convention + CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles + the names of subprograms, and currently, GNAT does not provide any help + to solve the demangling problem. This problem can be addressed in two + ways: + @itemize @bullet + @item + by modifying the C++ code in order to force a C convention using + the @code{extern "C"} syntax. + + @item + by figuring out the mangled name and use it as the Link_Name argument of + the pragma import. + @end itemize + + @noindent + Interfacing at the class level can be achieved by using the GNAT specific + pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT + Reference Manual for additional information. + + @node Linking a Mixed C++ & Ada Program + @subsection Linking a Mixed C++ & Ada Program + + @noindent + Usually the linker of the C++ development system must be used to link + mixed applications because most C++ systems will resolve elaboration + issues (such as calling constructors on global class instances) + transparently during the link phase. GNAT has been adapted to ease the + use of a foreign linker for the last phase. Three cases can be + considered: + @enumerate + + @item + Using GNAT and G++ (GNU C++ compiler) from the same GCC installation: + The C++ linker can simply be called by using the C++ specific driver + called @code{c++}. Note that this setup is not very common because it + may involve recompiling the whole GCC tree from sources, which makes it + harder to upgrade the compilation system for one language without + destabilizing the other. + + @smallexample + $ c++ -c file1.C + $ c++ -c file2.C + $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++ + @end smallexample + + @item + Using GNAT and G++ from two different GCC installations: If both + compilers are on the PATH, the previous method may be used. It is + important to note that environment variables such as C_INCLUDE_PATH, + GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers + at the same time and may make one of the two compilers operate + improperly if set during invocation of the wrong compiler. It is also + very important that the linker uses the proper @file{libgcc.a} GCC + library -- that is, the one from the C++ compiler installation. The + implicit link command as suggested in the gnatmake command from the + former example can be replaced by an explicit link command with the + full-verbosity option in order to verify which library is used: + @smallexample + $ gnatbind ada_unit + $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ + @end smallexample + If there is a problem due to interfering environment variables, it can + be worked around by using an intermediate script. The following example + shows the proper script to use when GNAT has not been installed at its + default location and g++ has been installed at its default location: + + @smallexample + $ cat ./my_script + #!/bin/sh + unset BINUTILS_ROOT + unset GCC_ROOT + c++ $* + $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script + @end smallexample + + @item + Using a non-GNU C++ compiler: The commands previously described can be + used to insure that the C++ linker is used. Nonetheless, you need to add + the path to libgcc explicitly, since some libraries needed by GNAT are + located in this directory: + + @smallexample + $ cat ./my_script + #!/bin/sh + CC $* `gcc -print-libgcc-file-name` + $ gnatlink ada_unit file1.o file2.o --LINK=./my_script + @end smallexample + + Where CC is the name of the non-GNU C++ compiler. + + @end enumerate + + @node A Simple Example + @subsection A Simple Example + @noindent + The following example, provided as part of the GNAT examples, shows how + to achieve procedural interfacing between Ada and C++ in both + directions. The C++ class A has two methods. The first method is exported + to Ada by the means of an extern C wrapper function. The second method + calls an Ada subprogram. On the Ada side, The C++ calls are modelled by + a limited record with a layout comparable to the C++ class. The Ada + subprogram, in turn, calls the C++ method. So, starting from the C++ + main program, the process passes back and forth between the two + languages. + + @noindent + Here are the compilation commands: + @smallexample + $ gnatmake -c simple_cpp_interface + $ c++ -c cpp_main.C + $ c++ -c ex7.C + $ gnatbind -n simple_cpp_interface + $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS) + -lstdc++ ex7.o cpp_main.o + @end smallexample + + @noindent + Here are the corresponding sources: + @smallexample + + //cpp_main.C + + #include "ex7.h" + + extern "C" @{ + void adainit (void); + void adafinal (void); + void method1 (A *t); + @} + + void method1 (A *t) + @{ + t->method1 (); + @} + + int main () + @{ + A obj; + adainit (); + obj.method2 (3030); + adafinal (); + @} + + //ex7.h + + class Origin @{ + public: + int o_value; + @}; + class A : public Origin @{ + public: + void method1 (void); + virtual void method2 (int v); + A(); + int a_value; + @}; + + //ex7.C + + #include "ex7.h" + #include + + extern "C" @{ void ada_method2 (A *t, int v);@} + + void A::method1 (void) + @{ + a_value = 2020; + printf ("in A::method1, a_value = %d \n",a_value); + + @} + + void A::method2 (int v) + @{ + ada_method2 (this, v); + printf ("in A::method2, a_value = %d \n",a_value); + + @} + + A::A(void) + @{ + a_value = 1010; + printf ("in A::A, a_value = %d \n",a_value); + @} + + -- Ada sources + @b{package} @b{body} Simple_Cpp_Interface @b{is} + + @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is} + @b{begin} + Method1 (This); + This.A_Value := V; + @b{end} Ada_Method2; + + @b{end} Simple_Cpp_Interface; + + @b{package} Simple_Cpp_Interface @b{is} + @b{type} A @b{is} @b{limited} + @b{record} + O_Value : Integer; + A_Value : Integer; + @b{end} @b{record}; + @b{pragma} Convention (C, A); + + @b{procedure} Method1 (This : @b{in} @b{out} A); + @b{pragma} Import (C, Method1); + + @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer); + @b{pragma} Export (C, Ada_Method2); + + @b{end} Simple_Cpp_Interface; + @end smallexample + + @node Adapting the Run Time to a New C++ Compiler + @subsection Adapting the Run Time to a New C++ Compiler + @noindent + GNAT offers the capability to derive Ada 95 tagged types directly from + preexisting C++ classes and . See ``Interfacing with C++'' in the + @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving + such a goal + has been made user configurable through a GNAT library unit + @code{Interfaces.CPP}. The default version of this file is adapted to + the GNU C++ compiler. Internal knowledge of the virtual + table layout used by the new C++ compiler is needed to configure + properly this unit. The Interface of this unit is known by the compiler + and cannot be changed except for the value of the constants defining the + characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, + CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source + of this unit for more details. + + @node Comparison between GNAT and C/C++ Compilation Models + @section Comparison between GNAT and C/C++ Compilation Models + + @noindent + The GNAT model of compilation is close to the C and C++ models. You can + think of Ada specs as corresponding to header files in C. As in C, you + don't need to compile specs; they are compiled when they are used. The + Ada @code{with} is similar in effect to the @code{#include} of a C + header. + + One notable difference is that, in Ada, you may compile specs separately + to check them for semantic and syntactic accuracy. This is not always + possible with C headers because they are fragments of programs that have + less specific syntactic or semantic rules. + + The other major difference is the requirement for running the binder, + which performs two important functions. First, it checks for + consistency. In C or C++, the only defense against assembling + inconsistent programs lies outside the compiler, in a makefile, for + example. The binder satisfies the Ada requirement that it be impossible + to construct an inconsistent program when the compiler is used in normal + mode. + + @cindex Elaboration order control + The other important function of the binder is to deal with elaboration + issues. There are also elaboration issues in C++ that are handled + automatically. This automatic handling has the advantage of being + simpler to use, but the C++ programmer has no control over elaboration. + Where @code{gnatbind} might complain there was no valid order of + elaboration, a C++ compiler would simply construct a program that + malfunctioned at run time. + + @node Comparison between GNAT and Conventional Ada Library Models + @section Comparison between GNAT and Conventional Ada Library Models + + @noindent + This section is intended to be useful to Ada programmers who have + previously used an Ada compiler implementing the traditional Ada library + model, as described in the Ada 95 Language Reference Manual. If you + have not used such a system, please go on to the next section. + + @cindex GNAT library + In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of + source files themselves acts as the library. Compiling Ada programs does + not generate any centralized information, but rather an object file and + a ALI file, which are of interest only to the binder and linker. + In a traditional system, the compiler reads information not only from + the source file being compiled, but also from the centralized library. + This means that the effect of a compilation depends on what has been + previously compiled. In particular: + + @itemize @bullet + @item + When a unit is @code{with}'ed, the unit seen by the compiler corresponds + to the version of the unit most recently compiled into the library. + + @item + Inlining is effective only if the necessary body has already been + compiled into the library. + + @item + Compiling a unit may obsolete other units in the library. + @end itemize + + @noindent + In GNAT, compiling one unit never affects the compilation of any other + units because the compiler reads only source files. Only changes to source + files can affect the results of a compilation. In particular: + + @itemize @bullet + @item + When a unit is @code{with}'ed, the unit seen by the compiler corresponds + to the source version of the unit that is currently accessible to the + compiler. + + @item + @cindex Inlining + Inlining requires the appropriate source files for the package or + subprogram bodies to be available to the compiler. Inlining is always + effective, independent of the order in which units are complied. + + @item + Compiling a unit never affects any other compilations. The editing of + sources may cause previous compilations to be out of date if they + depended on the source file being modified. + @end itemize + + @noindent + The most important result of these differences is that order of compilation + is never significant in GNAT. There is no situation in which one is + required to do one compilation before another. What shows up as order of + compilation requirements in the traditional Ada library becomes, in + GNAT, simple source dependencies; in other words, there is only a set + of rules saying what source files must be present when a file is + compiled. + + @ifset vms + @node Placement of temporary files + @section Placement of temporary files + @cindex Temporary files (user control over placement) + + @noindent + GNAT creates temporary files in the directory designated by the environment + variable @env{TMPDIR}. + (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()} + for detailed information on how environment variables are resolved. + For most users the easiest way to make use of this feature is to simply + define @env{TMPDIR} as a job level logical name). + For example, if you wish to use a Ramdisk (assuming DECRAM is installed) + for compiler temporary files, then you can include something like the + following command in your @file{LOGIN.COM} file: + + @smallexample + $ define/job TMPDIR "/disk$scratchram/000000/temp/" + @end smallexample + + @noindent + If @env{TMPDIR} is not defined, then GNAT uses the directory designated by + @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory + designated by @env{TEMP}. + If none of these environment variables are defined then GNAT uses the + directory designated by the logical name @code{SYS$SCRATCH:} + (by default the user's home directory). If all else fails + GNAT uses the current directory for temporary files. + @end ifset + + + @c ************************* + @node Compiling Using gcc + @chapter Compiling Using @code{gcc} + + @noindent + This chapter discusses how to compile Ada programs using the @code{gcc} + command. It also describes the set of switches + that can be used to control the behavior of the compiler. + @menu + * Compiling Programs:: + * Switches for gcc:: + * Search Paths and the Run-Time Library (RTL):: + * Order of Compilation Issues:: + * Examples:: + @end menu + + @node Compiling Programs + @section Compiling Programs + + @noindent + The first step in creating an executable program is to compile the units + of the program using the @code{gcc} command. You must compile the + following files: + + @itemize @bullet + @item + the body file (@file{.adb}) for a library level subprogram or generic + subprogram + + @item + the spec file (@file{.ads}) for a library level package or generic + package that has no body + + @item + the body file (@file{.adb}) for a library level package + or generic package that has a body + + @end itemize + + @noindent + You need @emph{not} compile the following files + + @itemize @bullet + + @item + the spec of a library unit which has a body + + @item + subunits + @end itemize + + @noindent + because they are compiled as part of compiling related units. GNAT + package specs + when the corresponding body is compiled, and subunits when the parent is + compiled. + + @cindex cannot generate code + If you attempt to compile any of these files, you will get one of the + following error messages (where fff is the name of the file you compiled): + + @smallexample + cannot generate code for file @var{fff} (package spec) + to check package spec, use -gnatc + + cannot generate code for file @var{fff} (missing subunits) + to check parent unit, use -gnatc + + cannot generate code for file @var{fff} (subprogram spec) + to check subprogram spec, use -gnatc + + cannot generate code for file @var{fff} (subunit) + to check subunit, use -gnatc + @end smallexample + + @noindent + As indicated by the above error messages, if you want to submit + one of these files to the compiler to check for correct semantics + without generating code, then use the @option{-gnatc} switch. + + The basic command for compiling a file containing an Ada unit is + + @smallexample + $ gcc -c [@var{switches}] @file{file name} + @end smallexample + + @noindent + where @var{file name} is the name of the Ada file (usually + having an extension + @file{.ads} for a spec or @file{.adb} for a body). + @ifclear vms + You specify the + @option{-c} switch to tell @code{gcc} to compile, but not link, the file. + @end ifclear + The result of a successful compilation is an object file, which has the + same name as the source file but an extension of @file{.o} and an Ada + Library Information (ALI) file, which also has the same name as the + source file, but with @file{.ali} as the extension. GNAT creates these + two output files in the current directory, but you may specify a source + file in any directory using an absolute or relative path specification + containing the directory information. + + @findex gnat1 + @code{gcc} is actually a driver program that looks at the extensions of + the file arguments and loads the appropriate compiler. For example, the + GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}. + These programs are in directories known to the driver program (in some + configurations via environment variables you set), but need not be in + your path. The @code{gcc} driver also calls the assembler and any other + utilities needed to complete the generation of the required object + files. + + It is possible to supply several file names on the same @code{gcc} + command. This causes @code{gcc} to call the appropriate compiler for + each file. For example, the following command lists three separate + files to be compiled: + + @smallexample + $ gcc -c x.adb y.adb z.c + @end smallexample + + @noindent + calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and + @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}. + The compiler generates three object files @file{x.o}, @file{y.o} and + @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the + Ada compilations. Any switches apply to all the files ^listed,^listed.^ + @ifclear vms + except for + @option{-gnat@var{x}} switches, which apply only to Ada compilations. + @end ifclear + + @node Switches for gcc + @section Switches for @code{gcc} + + @noindent + The @code{gcc} command accepts switches that control the + compilation process. These switches are fully described in this section. + First we briefly list all the switches, in alphabetical order, then we + describe the switches in more detail in functionally grouped sections. + + @menu + * Output and Error Message Control:: + * Warning Message Control:: + * Debugging and Assertion Control:: + * Run-Time Checks:: + * Stack Overflow Checking:: + * Validity Checking:: + * Style Checking:: + * Using gcc for Syntax Checking:: + * Using gcc for Semantic Checking:: + * Compiling Ada 83 Programs:: + * Character Set Control:: + * File Naming Control:: + * Subprogram Inlining Control:: + * Auxiliary Output Control:: + * Debugging Control:: + * Exception Handling Control:: + * Units to Sources Mapping Files:: + * Integrated Preprocessing:: + @ifset vms + * Return Codes:: + @end ifset + @end menu + + @table @option + @c !sort! + @ifclear vms + @cindex @option{-b} (@code{gcc}) + @item -b @var{target} + Compile your program to run on @var{target}, which is the name of a + system configuration. You must have a GNAT cross-compiler built if + @var{target} is not the same as your host system. + + @item -B@var{dir} + @cindex @option{-B} (@code{gcc}) + Load compiler executables (for example, @code{gnat1}, the Ada compiler) + from @var{dir} instead of the default location. Only use this switch + when multiple versions of the GNAT compiler are available. See the + @code{gcc} manual page for further details. You would normally use the + @option{-b} or @option{-V} switch instead. + + @item -c + @cindex @option{-c} (@code{gcc}) + Compile. Always use this switch when compiling Ada programs. + + Note: for some other languages when using @code{gcc}, notably in + the case of C and C++, it is possible to use + use @code{gcc} without a @option{-c} switch to + compile and link in one step. In the case of GNAT, you + cannot use this approach, because the binder must be run + and @code{gcc} cannot be used to run the GNAT binder. + @end ifclear + + @item -fno-inline + @cindex @option{-fno-inline} (@code{gcc}) + Suppresses all back-end inlining, even if other optimization or inlining + switches are set. + This includes suppression of inlining that results + from the use of the pragma @code{Inline_Always}. + See also @option{-gnatn} and @option{-gnatN}. + + @item -fstack-check + @cindex @option{-fstack-check} (@code{gcc}) + Activates stack checking. + See @ref{Stack Overflow Checking}, for details of the use of this option. + + @item ^-g^/DEBUG^ + @cindex @option{^-g^/DEBUG^} (@code{gcc}) + Generate debugging information. This information is stored in the object + file and copied from there to the final executable file by the linker, + where it can be read by the debugger. You must use the + @option{^-g^/DEBUG^} switch if you plan on using the debugger. + + @item -gnat83 + @cindex @option{-gnat83} (@code{gcc}) + Enforce Ada 83 restrictions. + + @item -gnata + @cindex @option{-gnata} (@code{gcc}) + Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be + activated. + + @item -gnatA + @cindex @option{-gnatA} (@code{gcc}) + Avoid processing @file{gnat.adc}. If a gnat.adc file is present, + it will be ignored. + + @item -gnatb + @cindex @option{-gnatb} (@code{gcc}) + Generate brief messages to @file{stderr} even if verbose mode set. + + @item -gnatc + @cindex @option{-gnatc} (@code{gcc}) + Check syntax and semantics only (no code generation attempted). + + @item -gnatd + @cindex @option{-gnatd} (@code{gcc}) + Specify debug options for the compiler. The string of characters after + the @option{-gnatd} specify the specific debug options. The possible + characters are 0-9, a-z, A-Z, optionally preceded by a dot. See + compiler source file @file{debug.adb} for details of the implemented + debug options. Certain debug options are relevant to applications + programmers, and these are documented at appropriate points in this + users guide. + + @item -gnatD + @cindex @option{-gnatD} (@code{gcc}) + Output expanded source files for source level debugging. This switch + also suppress generation of cross-reference information + (see @option{-gnatx}). + + @item -gnatec=@var{path} + @cindex @option{-gnatec} (@code{gcc}) + Specify a configuration pragma file + @ifclear vms + (the equal sign is optional) + @end ifclear + (see @ref{The Configuration Pragmas Files}). + + @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value] + @cindex @option{-gnateD} (@code{gcc}) + Defines a symbol, associated with value, for preprocessing. + (see @ref{Integrated Preprocessing}) + + @item -gnatef + @cindex @option{-gnatef} (@code{gcc}) + Display full source path name in brief error messages. + + @item -gnatem=@var{path} + @cindex @option{-gnatem} (@code{gcc}) + Specify a mapping file + @ifclear vms + (the equal sign is optional) + @end ifclear + (see @ref{Units to Sources Mapping Files}). + + @item -gnatep=@var{file} + @cindex @option{-gnatep} (@code{gcc}) + Specify a preprocessing data file + @ifclear vms + (the equal sign is optional) + @end ifclear + (see @ref{Integrated Preprocessing}). + + @item -gnatE + @cindex @option{-gnatE} (@code{gcc}) + Full dynamic elaboration checks. + + @item -gnatf + @cindex @option{-gnatf} (@code{gcc}) + Full errors. Multiple errors per line, all undefined references, do not + attempt to suppress cascaded errors. + + @item -gnatF + @cindex @option{-gnatF} (@code{gcc}) + Externals names are folded to all uppercase. + + @item -gnatg + @cindex @option{-gnatg} (@code{gcc}) + Internal GNAT implementation mode. This should not be used for + applications programs, it is intended only for use by the compiler + and its run-time library. For documentation, see the GNAT sources. + Note that @option{-gnatg} implies @option{-gnatwu} so that warnings + are generated on unreferenced entities, and all warnings are treated + as errors. + + @item -gnatG + @cindex @option{-gnatG} (@code{gcc}) + List generated expanded code in source form. + + @item ^-gnath^/HELP^ + @cindex @option{^-gnath^/HELP^} (@code{gcc}) + Output usage information. The output is written to @file{stdout}. + + @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c} + @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc}) + Identifier character set + @ifclear vms + (@var{c}=1/2/3/4/8/9/p/f/n/w). + @end ifclear + @ifset vms + For details of the possible selections for @var{c}, + see @xref{Character Set Control}. + @end ifset + + @item -gnatk=@var{n} + @cindex @option{-gnatk} (@code{gcc}) + Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^. + + @item -gnatl + @cindex @option{-gnatl} (@code{gcc}) + Output full source listing with embedded error messages. + + @item -gnatL + @cindex @option{-gnatL} (@code{gcc}) + Use the longjmp/setjmp method for exception handling + + @item -gnatm=@var{n} + @cindex @option{-gnatm} (@code{gcc}) + Limit number of detected error or warning messages to @var{n} + where @var{n} is in the range 1..999_999. The default setting if + no switch is given is 9999. Compilation is terminated if this + limit is exceeded. + + @item -gnatn + @cindex @option{-gnatn} (@code{gcc}) + Activate inlining for subprograms for which + pragma @code{inline} is specified. This inlining is performed + by the GCC back-end. + + @item -gnatN + @cindex @option{-gnatN} (@code{gcc}) + Activate front end inlining for subprograms for which + pragma @code{Inline} is specified. This inlining is performed + by the front end and will be visible in the + @option{-gnatG} output. + In some cases, this has proved more effective than the back end + inlining resulting from the use of + @option{-gnatn}. + Note that + @option{-gnatN} automatically implies + @option{-gnatn} so it is not necessary + to specify both options. There are a few cases that the back-end inlining + catches that cannot be dealt with in the front-end. + + @item -gnato + @cindex @option{-gnato} (@code{gcc}) + Enable numeric overflow checking (which is not normally enabled by + default). Not that division by zero is a separate check that is not + controlled by this switch (division by zero checking is on by default). + + @item -gnatp + @cindex @option{-gnatp} (@code{gcc}) + Suppress all checks. + + @item -gnatP + @cindex @option{-gnatP} (@code{gcc}) + Enable polling. This is required on some systems (notably Windows NT) to + obtain asynchronous abort and asynchronous transfer of control capability. + See the description of pragma Polling in the GNAT Reference Manual for + full details. + + @item -gnatq + @cindex @option{-gnatq} (@code{gcc}) + Don't quit; try semantics, even if parse errors. + + @item -gnatQ + @cindex @option{-gnatQ} (@code{gcc}) + Don't quit; generate @file{ALI} and tree files even if illegalities. + + @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^ + @cindex @option{-gnatR} (@code{gcc}) + Output representation information for declared types and objects. + + @item -gnats + @cindex @option{-gnats} (@code{gcc}) + Syntax check only. + + @item -gnatS + @cindex @option{-gnatS} (@code{gcc}) + Print package Standard. + + @item -gnatt + @cindex @option{-gnatt} (@code{gcc}) + Generate tree output file. + + @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn} + @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc}) + All compiler tables start at @var{nnn} times usual starting size. + + @item -gnatu + @cindex @option{-gnatu} (@code{gcc}) + List units for this compilation. + + @item -gnatU + @cindex @option{-gnatU} (@code{gcc}) + Tag all error messages with the unique string ``error:'' + + @item -gnatv + @cindex @option{-gnatv} (@code{gcc}) + Verbose mode. Full error output with source lines to @file{stdout}. + + @item -gnatV + @cindex @option{-gnatV} (@code{gcc}) + Control level of validity checking. See separate section describing + this feature. + + @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^ + @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc}) + Warning mode where + ^@var{xxx} is a string of option letters that^the list of options^ denotes + the exact warnings that + are enabled or disabled. (see @ref{Warning Message Control}) + + @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e} + @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc}) + Wide character encoding method + @ifclear vms + (@var{e}=n/h/u/s/e/8). + @end ifclear + @ifset vms + (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8}) + @end ifset + + @item -gnatx + @cindex @option{-gnatx} (@code{gcc}) + Suppress generation of cross-reference information. + + @item ^-gnaty^/STYLE_CHECKS=(option,option..)^ + @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc}) + Enable built-in style checks. (see @ref{Style Checking}) + + @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m} + @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc}) + Distribution stub generation and compilation + @ifclear vms + (@var{m}=r/c for receiver/caller stubs). + @end ifclear + @ifset vms + (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs + to be generated and compiled). + @end ifset + + @item -gnatZ + Use the zero cost method for exception handling + + @item ^-I^/SEARCH=^@var{dir} + @cindex @option{^-I^/SEARCH^} (@code{gcc}) + @cindex RTL + Direct GNAT to search the @var{dir} directory for source files needed by + the current compilation + (@pxref{Search Paths and the Run-Time Library (RTL)}). + + @item ^-I-^/NOCURRENT_DIRECTORY^ + @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc}) + @cindex RTL + Except for the source file named in the command line, do not look for source + files in the directory containing the source file named in the command line + (@pxref{Search Paths and the Run-Time Library (RTL)}). + + @ifclear vms + @item -mbig-switch + @cindex @option{-mbig-switch} (@command{gcc}) + @cindex @code{case} statement (effect of @option{-mbig-switch} option) + This standard gcc switch causes the compiler to use larger offsets in its + jump table representation for @code{case} statements. + This may result in less efficient code, but is sometimes necessary + (for example on HP-UX targets) + @cindex HP-UX and @option{-mbig-switch} option + in order to compile large and/or nested @code{case} statements. + + @item -o @var{file} + @cindex @option{-o} (@code{gcc}) + This switch is used in @code{gcc} to redirect the generated object file + and its associated ALI file. Beware of this switch with GNAT, because it may + cause the object file and ALI file to have different names which in turn + may confuse the binder and the linker. + @end ifclear + + @item -nostdinc + @cindex @option{-nostdinc} (@command{gcc}) + Inhibit the search of the default location for the GNAT Run Time + Library (RTL) source files. + + @item -nostdlib + @cindex @option{-nostdlib} (@command{gcc}) + Inhibit the search of the default location for the GNAT Run Time + Library (RTL) ALI files. + + @ifclear vms + @item -O[@var{n}] + @cindex @option{-O} (@code{gcc}) + @var{n} controls the optimization level. + + @table @asis + @item n = 0 + No optimization, the default setting if no @option{-O} appears + + @item n = 1 + Normal optimization, the default if you specify @option{-O} without + an operand. + + @item n = 2 + Extensive optimization + + @item n = 3 + Extensive optimization with automatic inlining of subprograms not + specified by pragma @code{Inline}. This applies only to + inlining within a unit. For details on control of inlining + see @xref{Subprogram Inlining Control}. + @end table + @end ifclear + + @ifset vms + @item /NOOPTIMIZE + @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE}) + Equivalent to @option{/OPTIMIZE=NONE}. + This is the default behavior in the absence of an @option{/OPTMIZE} + qualifier. + + @item /OPTIMIZE[=(keyword[,...])] + @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE}) + Selects the level of optimization for your program. The supported + keywords are as follows: + @table @code + @item ALL + Perform most optimizations, including those that + are expensive. + This is the default if the @option{/OPTMIZE} qualifier is supplied + without keyword options. + + @item NONE + Do not do any optimizations. Same as @code{/NOOPTIMIZE}. + + @item SOME + Perform some optimizations, but omit ones that are costly. + + @item DEVELOPMENT + Same as @code{SOME}. + + @item INLINING + Full optimization, and also attempt automatic inlining of small + subprograms within a unit even when pragma @code{Inline} + is not specified (@pxref{Inlining of Subprograms}). + + @item UNROLL_LOOPS + Try to unroll loops. This keyword may be specified together with + any keyword above other than @code{NONE}. Loop unrolling + usually, but not always, improves the performance of programs. + @end table + @end ifset + + @ifclear vms + @item -pass-exit-codes + @cindex @option{-pass-exit-codes} (@code{gcc}) + Catch exit codes from the compiler and use the most meaningful as + exit status. + @end ifclear + + @item --RTS=@var{rts-path} + @cindex @option{--RTS} (@code{gcc}) + Specifies the default location of the runtime library. Same meaning as the + equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). + + @item ^-S^/ASM^ + @cindex @option{^-S^/ASM^} (@code{gcc}) + ^Used in place of @option{-c} to^Used to^ + cause the assembler source file to be + generated, using @file{^.s^.S^} as the extension, + instead of the object file. + This may be useful if you need to examine the generated assembly code. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@code{gcc}) + Show commands generated by the @code{gcc} driver. Normally used only for + debugging purposes or if you need to be sure what version of the + compiler you are executing. + + @ifclear vms + @item -V @var{ver} + @cindex @option{-V} (@code{gcc}) + Execute @var{ver} version of the compiler. This is the @code{gcc} + version, not the GNAT version. + @end ifclear + + @end table + + @ifclear vms + You may combine a sequence of GNAT switches into a single switch. For + example, the combined switch + + @cindex Combining GNAT switches + @smallexample + -gnatofi3 + @end smallexample + + @noindent + is equivalent to specifying the following sequence of switches: + + @smallexample + -gnato -gnatf -gnati3 + @end smallexample + @end ifclear + + + @c NEED TO CHECK THIS FOR VMS + + @noindent + The following restrictions apply to the combination of switches + in this manner: + + @itemize @bullet + @item + The switch @option{-gnatc} if combined with other switches must come + first in the string. + + @item + The switch @option{-gnats} if combined with other switches must come + first in the string. + + @item + The switches + @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr} + may not be combined with any other switches. + + @ifclear vms + @item + Once a ``y'' appears in the string (that is a use of the @option{-gnaty} + switch), then all further characters in the switch are interpreted + as style modifiers (see description of @option{-gnaty}). + + @item + Once a ``d'' appears in the string (that is a use of the @option{-gnatd} + switch), then all further characters in the switch are interpreted + as debug flags (see description of @option{-gnatd}). + + @item + Once a ``w'' appears in the string (that is a use of the @option{-gnatw} + switch), then all further characters in the switch are interpreted + as warning mode modifiers (see description of @option{-gnatw}). + + @item + Once a ``V'' appears in the string (that is a use of the @option{-gnatV} + switch), then all further characters in the switch are interpreted + as validity checking options (see description of @option{-gnatV}). + @end ifclear + @end itemize + + + @node Output and Error Message Control + @subsection Output and Error Message Control + @findex stderr + + @noindent + The standard default format for error messages is called ``brief format''. + Brief format messages are written to @file{stderr} (the standard error + file) and have the following form: + + @smallexample + e.adb:3:04: Incorrect spelling of keyword "function" + e.adb:4:20: ";" should be "is" + @end smallexample + + @noindent + The first integer after the file name is the line number in the file, + and the second integer is the column number within the line. + @code{glide} can parse the error messages + and point to the referenced character. + The following switches provide control over the error message + format: + + @table @option + @c !sort! + @item -gnatv + @cindex @option{-gnatv} (@code{gcc}) + @findex stdout + @ifclear vms + The v stands for verbose. + @end ifclear + The effect of this setting is to write long-format error + messages to @file{stdout} (the standard output file. + The same program compiled with the + @option{-gnatv} switch would generate: + + @smallexample + @cartouche + 3. funcion X (Q : Integer) + | + >>> Incorrect spelling of keyword "function" + 4. return Integer; + | + >>> ";" should be "is" + @end cartouche + @end smallexample + + @noindent + The vertical bar indicates the location of the error, and the @samp{>>>} + prefix can be used to search for error messages. When this switch is + used the only source lines output are those with errors. + + @item -gnatl + @cindex @option{-gnatl} (@code{gcc}) + @ifclear vms + The @code{l} stands for list. + @end ifclear + This switch causes a full listing of + the file to be generated. The output might look as follows: + + @smallexample + @cartouche + 1. procedure E is + 2. V : Integer; + 3. funcion X (Q : Integer) + | + >>> Incorrect spelling of keyword "function" + 4. return Integer; + | + >>> ";" should be "is" + 5. begin + 6. return Q + Q; + 7. end; + 8. begin + 9. V := X + X; + 10.end E; + @end cartouche + @end smallexample + + @noindent + @findex stderr + When you specify the @option{-gnatv} or @option{-gnatl} switches and + standard output is redirected, a brief summary is written to + @file{stderr} (standard error) giving the number of error messages and + warning messages generated. + + @item -gnatU + @cindex @option{-gnatU} (@code{gcc}) + This switch forces all error messages to be preceded by the unique + string ``error:''. This means that error messages take a few more + characters in space, but allows easy searching for and identification + of error messages. + + @item -gnatb + @cindex @option{-gnatb} (@code{gcc}) + @ifclear vms + The @code{b} stands for brief. + @end ifclear + This switch causes GNAT to generate the + brief format error messages to @file{stderr} (the standard error + file) as well as the verbose + format message or full listing (which as usual is written to + @file{stdout} (the standard output file). + + @item -gnatm^^=^@var{n} + @cindex @option{-gnatm} (@code{gcc}) + @ifclear vms + The @code{m} stands for maximum. + @end ifclear + @var{n} is a decimal integer in the + range of 1 to 999 and limits the number of error messages to be + generated. For example, using @option{-gnatm2} might yield + + @smallexample + e.adb:3:04: Incorrect spelling of keyword "function" + e.adb:5:35: missing ".." + fatal error: maximum errors reached + compilation abandoned + @end smallexample + + @item -gnatf + @cindex @option{-gnatf} (@code{gcc}) + @cindex Error messages, suppressing + @ifclear vms + The @code{f} stands for full. + @end ifclear + Normally, the compiler suppresses error messages that are likely to be + redundant. This switch causes all error + messages to be generated. In particular, in the case of + references to undefined variables. If a given variable is referenced + several times, the normal format of messages is + @smallexample + e.adb:7:07: "V" is undefined (more references follow) + @end smallexample + + @noindent + where the parenthetical comment warns that there are additional + references to the variable @code{V}. Compiling the same program with the + @option{-gnatf} switch yields + + @smallexample + e.adb:7:07: "V" is undefined + e.adb:8:07: "V" is undefined + e.adb:8:12: "V" is undefined + e.adb:8:16: "V" is undefined + e.adb:9:07: "V" is undefined + e.adb:9:12: "V" is undefined + @end smallexample + + @noindent + The @option{-gnatf} switch also generates additional information for + some error messages. Some examples are: + + @itemize @bullet + @item + Full details on entities not available in high integrity mode + @item + Details on possibly non-portable unchecked conversion + @item + List possible interpretations for ambiguous calls + @item + Additional details on incorrect parameters + @end itemize + + + @item -gnatq + @cindex @option{-gnatq} (@code{gcc}) + @ifclear vms + The @code{q} stands for quit (really ``don't quit''). + @end ifclear + In normal operation mode, the compiler first parses the program and + determines if there are any syntax errors. If there are, appropriate + error messages are generated and compilation is immediately terminated. + This switch tells + GNAT to continue with semantic analysis even if syntax errors have been + found. This may enable the detection of more errors in a single run. On + the other hand, the semantic analyzer is more likely to encounter some + internal fatal error when given a syntactically invalid tree. + + @item -gnatQ + @cindex @option{-gnatQ} (@code{gcc}) + In normal operation mode, the @file{ALI} file is not generated if any + illegalities are detected in the program. The use of @option{-gnatQ} forces + generation of the @file{ALI} file. This file is marked as being in + error, so it cannot be used for binding purposes, but it does contain + reasonably complete cross-reference information, and thus may be useful + for use by tools (e.g. semantic browsing tools or integrated development + environments) that are driven from the @file{ALI} file. This switch + implies @option{-gnatq}, since the semantic phase must be run to get a + meaningful ALI file. + + In addition, if @option{-gnatt} is also specified, then the tree file is + generated even if there are illegalities. It may be useful in this case + to also specify @option{-gnatq} to ensure that full semantic processing + occurs. The resulting tree file can be processed by ASIS, for the purpose + of providing partial information about illegal units, but if the error + causes the tree to be badly malformed, then ASIS may crash during the + analysis. + + When @option{-gnatQ} is used and the generated @file{ALI} file is marked as + being in error, @code{gnatmake} will attempt to recompile the source when it + finds such an @file{ALI} file, including with switch @option{-gnatc}. + + Note that @option{-gnatQ} has no effect if @option{-gnats} is specified, + since ALI files are never generated if @option{-gnats} is set. + + @end table + + + @node Warning Message Control + @subsection Warning Message Control + @cindex Warning messages + @noindent + In addition to error messages, which correspond to illegalities as defined + in the Ada 95 Reference Manual, the compiler detects two kinds of warning + situations. + + First, the compiler considers some constructs suspicious and generates a + warning message to alert you to a possible error. Second, if the + compiler detects a situation that is sure to raise an exception at + run time, it generates a warning message. The following shows an example + of warning messages: + @smallexample + e.adb:4:24: warning: creation of object may raise Storage_Error + e.adb:10:17: warning: static value out of range + e.adb:10:17: warning: "Constraint_Error" will be raised at run time + @end smallexample + + @noindent + GNAT considers a large number of situations as appropriate + for the generation of warning messages. As always, warnings are not + definite indications of errors. For example, if you do an out-of-range + assignment with the deliberate intention of raising a + @code{Constraint_Error} exception, then the warning that may be + issued does not indicate an error. Some of the situations for which GNAT + issues warnings (at least some of the time) are given in the following + list. This list is not complete, and new warnings are often added to + subsequent versions of GNAT. The list is intended to give a general idea + of the kinds of warnings that are generated. + + @itemize @bullet + @item + Possible infinitely recursive calls + + @item + Out-of-range values being assigned + + @item + Possible order of elaboration problems + + @item + Unreachable code + + @item + Fixed-point type declarations with a null range + + @item + Variables that are never assigned a value + + @item + Variables that are referenced before being initialized + + @item + Task entries with no corresponding @code{accept} statement + + @item + Duplicate accepts for the same task entry in a @code{select} + + @item + Objects that take too much storage + + @item + Unchecked conversion between types of differing sizes + + @item + Missing @code{return} statement along some execution path in a function + + @item + Incorrect (unrecognized) pragmas + + @item + Incorrect external names + + @item + Allocation from empty storage pool + + @item + Potentially blocking operation in protected type + + @item + Suspicious parenthesization of expressions + + @item + Mismatching bounds in an aggregate + + @item + Attempt to return local value by reference + + + @item + Premature instantiation of a generic body + + @item + Attempt to pack aliased components + + @item + Out of bounds array subscripts + + @item + Wrong length on string assignment + + @item + Violations of style rules if style checking is enabled + + @item + Unused @code{with} clauses + + @item + @code{Bit_Order} usage that does not have any effect + + @item + @code{Standard.Duration} used to resolve universal fixed expression + + @item + Dereference of possibly null value + + @item + Declaration that is likely to cause storage error + + @item + Internal GNAT unit @code{with}'ed by application unit + + @item + Values known to be out of range at compile time + + @item + Unreferenced labels and variables + + @item + Address overlays that could clobber memory + + @item + Unexpected initialization when address clause present + + @item + Bad alignment for address clause + + @item + Useless type conversions + + @item + Redundant assignment statements and other redundant constructs + + @item + Useless exception handlers + + @item + Accidental hiding of name by child unit + + + @item + Access before elaboration detected at compile time + + @item + A range in a @code{for} loop that is known to be null or might be null + + @end itemize + + @noindent + The following switches are available to control the handling of + warning messages: + + @table @option + @c !sort! + @item -gnatwa + @emph{Activate all optional errors.} + @cindex @option{-gnatwa} (@code{gcc}) + This switch activates most optional warning messages, see remaining list + in this section for details on optional warning messages that can be + individually controlled. The warnings that are not turned on by this + switch are + @option{-gnatwd} (implicit dereferencing), + @option{-gnatwh} (hiding), + and @option{-gnatwl} (elaboration warnings). + All other optional warnings are turned on. + + @item -gnatwA + @emph{Suppress all optional errors.} + @cindex @option{-gnatwA} (@code{gcc}) + This switch suppresses all optional warning messages, see remaining list + in this section for details on optional warning messages that can be + individually controlled. + + @item -gnatwc + @emph{Activate warnings on conditionals.} + @cindex @option{-gnatwc} (@code{gcc}) + @cindex Conditionals, constant + This switch activates warnings for conditional expressions used in + tests that are known to be True or False at compile time. The default + is that such warnings are not generated. + Note that this warning does + not get issued for the use of boolean variables or constants whose + values are known at compile time, since this is a standard technique + for conditional compilation in Ada, and this would generate too many + ``false positive'' warnings. + This warning can also be turned on using @option{-gnatwa}. + + @item -gnatwC + @emph{Suppress warnings on conditionals.} + @cindex @option{-gnatwC} (@code{gcc}) + This switch suppresses warnings for conditional expressions used in + tests that are known to be True or False at compile time. + + @item -gnatwd + @emph{Activate warnings on implicit dereferencing.} + @cindex @option{-gnatwd} (@code{gcc}) + If this switch is set, then the use of a prefix of an access type + in an indexed component, slice, or selected component without an + explicit @code{.all} will generate a warning. With this warning + enabled, access checks occur only at points where an explicit + @code{.all} appears in the source code (assuming no warnings are + generated as a result of this switch). The default is that such + warnings are not generated. + Note that @option{-gnatwa} does not affect the setting of + this warning option. + + @item -gnatwD + @emph{Suppress warnings on implicit dereferencing.} + @cindex @option{-gnatwD} (@code{gcc}) + @cindex Implicit dereferencing + @cindex Dereferencing, implicit + This switch suppresses warnings for implicit dereferences in + indexed components, slices, and selected components. + + @item -gnatwe + @emph{Treat warnings as errors.} + @cindex @option{-gnatwe} (@code{gcc}) + @cindex Warnings, treat as error + This switch causes warning messages to be treated as errors. + The warning string still appears, but the warning messages are counted + as errors, and prevent the generation of an object file. + + @item -gnatwf + @emph{Activate warnings on unreferenced formals.} + @cindex @option{-gnatwf} (@code{gcc}) + @cindex Formals, unreferenced + This switch causes a warning to be generated if a formal parameter + is not referenced in the body of the subprogram. This warning can + also be turned on using @option{-gnatwa} or @option{-gnatwu}. + + @item -gnatwF + @emph{Suppress warnings on unreferenced formals.} + @cindex @option{-gnatwF} (@code{gcc}) + This switch suppresses warnings for unreferenced formal + parameters. Note that the + combination @option{-gnatwu} followed by @option{-gnatwF} has the + effect of warning on unreferenced entities other than subprogram + formals. + + @item -gnatwg + @emph{Activate warnings on unrecognized pragmas.} + @cindex @option{-gnatwg} (@code{gcc}) + @cindex Pragmas, unrecognized + This switch causes a warning to be generated if an unrecognized + pragma is encountered. Apart from issuing this warning, the + pragma is ignored and has no effect. This warning can + also be turned on using @option{-gnatwa}. The default + is that such warnings are issued (satisfying the Ada Reference + Manual requirement that such warnings appear). + + @item -gnatwG + @emph{Suppress warnings on unrecognized pragmas.} + @cindex @option{-gnatwG} (@code{gcc}) + This switch suppresses warnings for unrecognized pragmas. + + @item -gnatwh + @emph{Activate warnings on hiding.} + @cindex @option{-gnatwh} (@code{gcc}) + @cindex Hiding of Declarations + This switch activates warnings on hiding declarations. + A declaration is considered hiding + if it is for a non-overloadable entity, and it declares an entity with the + same name as some other entity that is directly or use-visible. The default + is that such warnings are not generated. + Note that @option{-gnatwa} does not affect the setting of this warning option. + + @item -gnatwH + @emph{Suppress warnings on hiding.} + @cindex @option{-gnatwH} (@code{gcc}) + This switch suppresses warnings on hiding declarations. + + @item -gnatwi + @emph{Activate warnings on implementation units.} + @cindex @option{-gnatwi} (@code{gcc}) + This switch activates warnings for a @code{with} of an internal GNAT + implementation unit, defined as any unit from the @code{Ada}, + @code{Interfaces}, @code{GNAT}, + ^^@code{DEC},^ or @code{System} + hierarchies that is not + documented in either the Ada Reference Manual or the GNAT + Programmer's Reference Manual. Such units are intended only + for internal implementation purposes and should not be @code{with}'ed + by user programs. The default is that such warnings are generated + This warning can also be turned on using @option{-gnatwa}. + + @item -gnatwI + @emph{Disable warnings on implementation units.} + @cindex @option{-gnatwI} (@code{gcc}) + This switch disables warnings for a @code{with} of an internal GNAT + implementation unit. + + @item -gnatwj + @emph{Activate warnings on obsolescent features (Annex J).} + @cindex @option{-gnatwj} (@code{gcc}) + @cindex Features, obsolescent + @cindex Obsolescent features + If this warning option is activated, then warnings are generated for + calls to subprograms marked with @code{pragma Obsolescent} and + for use of features in Annex J of the Ada Reference Manual. In the + case of Annex J, not all features are flagged. In particular use + of the renamed packages (like @code{Text_IO}) and use of package + @code{ASCII} are not flagged, since these are very common and + would generate many annoying positive warnings. The default is that + such warnings are not generated. + + @item -gnatwJ + @emph{Suppress warnings on obsolescent features (Annex J).} + @cindex @option{-gnatwJ} (@code{gcc}) + This switch disables warnings on use of obsolescent features. + + @item -gnatwk + @emph{Activate warnings on variables that could be constants.} + @cindex @option{-gnatwk} (@code{gcc}) + This switch activates warnings for variables that are initialized but + never modified, and then could be declared constants. + + @item -gnatwK + @emph{Suppress warnings on variables that could be constants.} + @cindex @option{-gnatwK} (@code{gcc}) + This switch disables warnings on variables that could be declared constants. + + @item -gnatwl + @emph{Activate warnings for missing elaboration pragmas.} + @cindex @option{-gnatwl} (@code{gcc}) + @cindex Elaboration, warnings + This switch activates warnings on missing + @code{pragma Elaborate_All} statements. + See the section in this guide on elaboration checking for details on + when such pragma should be used. Warnings are also generated if you + are using the static mode of elaboration, and a @code{pragma Elaborate} + is encountered. The default is that such warnings + are not generated. + This warning is not automatically turned on by the use of @option{-gnatwa}. + + @item -gnatwL + @emph{Suppress warnings for missing elaboration pragmas.} + @cindex @option{-gnatwL} (@code{gcc}) + This switch suppresses warnings on missing pragma Elaborate_All statements. + See the section in this guide on elaboration checking for details on + when such pragma should be used. + + @item -gnatwm + @emph{Activate warnings on modified but unreferenced variables.} + @cindex @option{-gnatwm} (@code{gcc}) + This switch activates warnings for variables that are assigned (using + an initialization value or with one or more assignment statements) but + whose value is never read. The warning is suppressed for volatile + variables and also for variables that are renamings of other variables + or for which an address clause is given. + This warning can also be turned on using @option{-gnatwa}. + + @item -gnatwM + @emph{Disable warnings on modified but unreferenced variables.} + @cindex @option{-gnatwM} (@code{gcc}) + This switch disables warnings for variables that are assigned or + initialized, but never read. + + @item -gnatwn + @emph{Set normal warnings mode.} + @cindex @option{-gnatwn} (@code{gcc}) + This switch sets normal warning mode, in which enabled warnings are + issued and treated as warnings rather than errors. This is the default + mode. the switch @option{-gnatwn} can be used to cancel the effect of + an explicit @option{-gnatws} or + @option{-gnatwe}. It also cancels the effect of the + implicit @option{-gnatwe} that is activated by the + use of @option{-gnatg}. + + @item -gnatwo + @emph{Activate warnings on address clause overlays.} + @cindex @option{-gnatwo} (@code{gcc}) + @cindex Address Clauses, warnings + This switch activates warnings for possibly unintended initialization + effects of defining address clauses that cause one variable to overlap + another. The default is that such warnings are generated. + This warning can also be turned on using @option{-gnatwa}. + + @item -gnatwO + @emph{Suppress warnings on address clause overlays.} + @cindex @option{-gnatwO} (@code{gcc}) + This switch suppresses warnings on possibly unintended initialization + effects of defining address clauses that cause one variable to overlap + another. + + @item -gnatwp + @emph{Activate warnings on ineffective pragma Inlines.} + @cindex @option{-gnatwp} (@code{gcc}) + @cindex Inlining, warnings + This switch activates warnings for failure of front end inlining + (activated by @option{-gnatN}) to inline a particular call. There are + many reasons for not being able to inline a call, including most + commonly that the call is too complex to inline. + This warning can also be turned on using @option{-gnatwa}. + + @item -gnatwP + @emph{Suppress warnings on ineffective pragma Inlines.} + @cindex @option{-gnatwP} (@code{gcc}) + This switch suppresses warnings on ineffective pragma Inlines. If the + inlining mechanism cannot inline a call, it will simply ignore the + request silently. + + @item -gnatwr + @emph{Activate warnings on redundant constructs.} + @cindex @option{-gnatwr} (@code{gcc}) + This switch activates warnings for redundant constructs. The following + is the current list of constructs regarded as redundant: + This warning can also be turned on using @option{-gnatwa}. + + @itemize @bullet + @item + Assignment of an item to itself. + @item + Type conversion that converts an expression to its own type. + @item + Use of the attribute @code{Base} where @code{typ'Base} is the same + as @code{typ}. + @item + Use of pragma @code{Pack} when all components are placed by a record + representation clause. + @item + Exception handler containing only a reraise statement (raise with no + operand) which has no effect. + @item + Use of the operator abs on an operand that is known at compile time + to be non-negative + @item + Use of an unnecessary extra level of parentheses (C-style) around conditions + in @code{if} statements, @code{while} statements and @code{exit} statements. + @item + Comparison of boolean expressions to an explicit True value. + @end itemize + + @item -gnatwR + @emph{Suppress warnings on redundant constructs.} + @cindex @option{-gnatwR} (@code{gcc}) + This switch suppresses warnings for redundant constructs. + + @item -gnatws + @emph{Suppress all warnings.} + @cindex @option{-gnatws} (@code{gcc}) + This switch completely suppresses the + output of all warning messages from the GNAT front end. + Note that it does not suppress warnings from the @code{gcc} back end. + To suppress these back end warnings as well, use the switch @option{-w} + in addition to @option{-gnatws}. + + @item -gnatwu + @emph{Activate warnings on unused entities.} + @cindex @option{-gnatwu} (@code{gcc}) + This switch activates warnings to be generated for entities that + are declared but not referenced, and for units that are @code{with}'ed + and not + referenced. In the case of packages, a warning is also generated if + no entities in the package are referenced. This means that if the package + is referenced but the only references are in @code{use} + clauses or @code{renames} + declarations, a warning is still generated. A warning is also generated + for a generic package that is @code{with}'ed but never instantiated. + In the case where a package or subprogram body is compiled, and there + is a @code{with} on the corresponding spec + that is only referenced in the body, + a warning is also generated, noting that the + @code{with} can be moved to the body. The default is that + such warnings are not generated. + This switch also activates warnings on unreferenced formals + (it is includes the effect of @option{-gnatwf}). + This warning can also be turned on using @option{-gnatwa}. + + @item -gnatwU + @emph{Suppress warnings on unused entities.} + @cindex @option{-gnatwU} (@code{gcc}) + This switch suppresses warnings for unused entities and packages. + It also turns off warnings on unreferenced formals (and thus includes + the effect of @option{-gnatwF}). + + @item -gnatwv + @emph{Activate warnings on unassigned variables.} + @cindex @option{-gnatwv} (@code{gcc}) + @cindex Unassigned variable warnings + This switch activates warnings for access to variables which + may not be properly initialized. The default is that + such warnings are generated. + + @item -gnatwV + @emph{Suppress warnings on unassigned variables.} + @cindex @option{-gnatwV} (@code{gcc}) + This switch suppresses warnings for access to variables which + may not be properly initialized. + + @item -gnatwx + @emph{Activate warnings on Export/Import pragmas.} + @cindex @option{-gnatwx} (@code{gcc}) + @cindex Export/Import pragma warnings + This switch activates warnings on Export/Import pragmas when + the compiler detects a possible conflict between the Ada and + foreign language calling sequences. For example, the use of + default parameters in a convention C procedure is dubious + because the C compiler cannot supply the proper default, so + a warning is issued. The default is that such warnings are + generated. + + @item -gnatwX + @emph{Suppress warnings on Export/Import pragmas.} + @cindex @option{-gnatwX} (@code{gcc}) + This switch suppresses warnings on Export/Import pragmas. + The sense of this is that you are telling the compiler that + you know what you are doing in writing the pragma, and it + should not complain at you. + + @item -gnatwz + @emph{Activate warnings on unchecked conversions.} + @cindex @option{-gnatwz} (@code{gcc}) + @cindex Unchecked_Conversion warnings + This switch activates warnings for unchecked conversions + where the types are known at compile time to have different + sizes. The default + is that such warnings are generated. + + @item -gnatwZ + @emph{Suppress warnings on unchecked conversions.} + @cindex @option{-gnatwZ} (@code{gcc}) + This switch suppresses warnings for unchecked conversions + where the types are known at compile time to have different + sizes. + + @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^ + @cindex @option{-Wuninitialized} + The warnings controlled by the @option{-gnatw} switch are generated by the + front end of the compiler. In some cases, the @option{^gcc^GCC^} back end + can provide additional warnings. One such useful warning is provided by + @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in + conjunction with tunrning on optimization mode. This causes the flow + analysis circuits of the back end optimizer to output additional + warnings about uninitialized variables. + + @item ^-w^/NO_BACK_END_WARNINGS^ + @cindex @option{-w} + This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may + be used in conjunction with @option{-gnatws} to ensure that all warnings + are suppressed during the entire compilation process. + + @end table + + @noindent + @ifclear vms + A string of warning parameters can be used in the same parameter. For example: + + @smallexample + -gnatwaLe + @end smallexample + + @noindent + will turn on all optional warnings except for elaboration pragma warnings, + and also specify that warnings should be treated as errors. + @end ifclear + When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to: + + @table @option + @c !sort! + @item -gnatwB + @item -gnatwC + @item -gnatwK + @item -gnatwD + @item -gnatwL + @item -gnatwH + @item -gnatwi + @item -gnatwP + @item -gnatwn + @item -gnatwo + @item -gnatwz + @item -gnatwx + + @end table + + + @node Debugging and Assertion Control + @subsection Debugging and Assertion Control + + @table @option + @item -gnata + @cindex @option{-gnata} (@code{gcc}) + @findex Assert + @findex Debug + @cindex Assertions + + @noindent + The pragmas @code{Assert} and @code{Debug} normally have no effect and + are ignored. This switch, where @samp{a} stands for assert, causes + @code{Assert} and @code{Debug} pragmas to be activated. + + The pragmas have the form: + + @smallexample + @cartouche + @b{pragma} Assert (@var{Boolean-expression} [, + @var{static-string-expression}]) + @b{pragma} Debug (@var{procedure call}) + @end cartouche + @end smallexample + + @noindent + The @code{Assert} pragma causes @var{Boolean-expression} to be tested. + If the result is @code{True}, the pragma has no effect (other than + possible side effects from evaluating the expression). If the result is + @code{False}, the exception @code{Assert_Failure} declared in the package + @code{System.Assertions} is + raised (passing @var{static-string-expression}, if present, as the + message associated with the exception). If no string expression is + given the default is a string giving the file name and line number + of the pragma. + + The @code{Debug} pragma causes @var{procedure} to be called. Note that + @code{pragma Debug} may appear within a declaration sequence, allowing + debugging procedures to be called between declarations. + + @ifset vms + @item /DEBUG[=debug-level] + @itemx /NODEBUG + Specifies how much debugging information is to be included in + the resulting object file where 'debug-level' is one of the following: + @table @code + @item TRACEBACK + Include both debugger symbol records and traceback + the object file. + This is the default setting. + @item ALL + Include both debugger symbol records and traceback in + object file. + @item NONE + Excludes both debugger symbol records and traceback + the object file. Same as /NODEBUG. + @item SYMBOLS + Includes only debugger symbol records in the object + file. Note that this doesn't include traceback information. + @end table + @end ifset + @end table + + @node Validity Checking + @subsection Validity Checking + @findex Validity Checking + + @noindent + The Ada 95 Reference Manual has specific requirements for checking + for invalid values. In particular, RM 13.9.1 requires that the + evaluation of invalid values (for example from unchecked conversions), + not result in erroneous execution. In GNAT, the result of such an + evaluation in normal default mode is to either use the value + unmodified, or to raise Constraint_Error in those cases where use + of the unmodified value would cause erroneous execution. The cases + where unmodified values might lead to erroneous execution are case + statements (where a wild jump might result from an invalid value), + and subscripts on the left hand side (where memory corruption could + occur as a result of an invalid value). + + The @option{-gnatV^@var{x}^^} switch allows more control over the validity + checking mode. + @ifclear vms + The @code{x} argument is a string of letters that + indicate validity checks that are performed or not performed in addition + to the default checks described above. + @end ifclear + @ifset vms + The options allowed for this qualifier + indicate validity checks that are performed or not performed in addition + to the default checks described above. + @end ifset + + + @table @option + @c !sort! + @item -gnatVa + @emph{All validity checks.} + @cindex @option{-gnatVa} (@code{gcc}) + All validity checks are turned on. + @ifclear vms + That is, @option{-gnatVa} is + equivalent to @option{gnatVcdfimorst}. + @end ifclear + + @item -gnatVc + @emph{Validity checks for copies.} + @cindex @option{-gnatVc} (@code{gcc}) + The right hand side of assignments, and the initializing values of + object declarations are validity checked. + + @item -gnatVd + @emph{Default (RM) validity checks.} + @cindex @option{-gnatVd} (@code{gcc}) + Some validity checks are done by default following normal Ada semantics + (RM 13.9.1 (9-11)). + A check is done in case statements that the expression is within the range + of the subtype. If it is not, Constraint_Error is raised. + For assignments to array components, a check is done that the expression used + as index is within the range. If it is not, Constraint_Error is raised. + Both these validity checks may be turned off using switch @option{-gnatVD}. + They are turned on by default. If @option{-gnatVD} is specified, a subsequent + switch @option{-gnatVd} will leave the checks turned on. + Switch @option{-gnatVD} should be used only if you are sure that all such + expressions have valid values. If you use this switch and invalid values + are present, then the program is erroneous, and wild jumps or memory + overwriting may occur. + + @item -gnatVf + @emph{Validity checks for floating-point values.} + @cindex @option{-gnatVf} (@code{gcc}) + In the absence of this switch, validity checking occurs only for discrete + values. If @option{-gnatVf} is specified, then validity checking also applies + for floating-point values, and NaN's and infinities are considered invalid, + as well as out of range values for constrained types. Note that this means + that standard @code{IEEE} infinity mode is not allowed. The exact contexts + in which floating-point values are checked depends on the setting of other + options. For example, + @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or + @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^} + (the order does not matter) specifies that floating-point parameters of mode + @code{in} should be validity checked. + + @item -gnatVi + @emph{Validity checks for @code{in} mode parameters} + @cindex @option{-gnatVi} (@code{gcc}) + Arguments for parameters of mode @code{in} are validity checked in function + and procedure calls at the point of call. + + @item -gnatVm + @emph{Validity checks for @code{in out} mode parameters.} + @cindex @option{-gnatVm} (@code{gcc}) + Arguments for parameters of mode @code{in out} are validity checked in + procedure calls at the point of call. The @code{'m'} here stands for + modify, since this concerns parameters that can be modified by the call. + Note that there is no specific option to test @code{out} parameters, + but any reference within the subprogram will be tested in the usual + manner, and if an invalid value is copied back, any reference to it + will be subject to validity checking. + + @item -gnatVn + @emph{No validity checks.} + @cindex @option{-gnatVn} (@code{gcc}) + This switch turns off all validity checking, including the default checking + for case statements and left hand side subscripts. Note that the use of + the switch @option{-gnatp} suppresses all run-time checks, including + validity checks, and thus implies @option{-gnatVn}. When this switch + is used, it cancels any other @option{-gnatV} previously issued. + + @item -gnatVo + @emph{Validity checks for operator and attribute operands.} + @cindex @option{-gnatVo} (@code{gcc}) + Arguments for predefined operators and attributes are validity checked. + This includes all operators in package @code{Standard}, + the shift operators defined as intrinsic in package @code{Interfaces} + and operands for attributes such as @code{Pos}. Checks are also made + on individual component values for composite comparisons. + + @item -gnatVp + @emph{Validity checks for parameters.} + @cindex @option{-gnatVp} (@code{gcc}) + This controls the treatment of parameters within a subprogram (as opposed + to @option{-gnatVi} and @option{-gnatVm} which control validity testing + of parameters on a call. If either of these call options is used, then + normally an assumption is made within a subprogram that the input arguments + have been validity checking at the point of call, and do not need checking + again within a subprogram). If @option{-gnatVp} is set, then this assumption + is not made, and parameters are not assumed to be valid, so their validity + will be checked (or rechecked) within the subprogram. + + @item -gnatVr + @emph{Validity checks for function returns.} + @cindex @option{-gnatVr} (@code{gcc}) + The expression in @code{return} statements in functions is validity + checked. + + @item -gnatVs + @emph{Validity checks for subscripts.} + @cindex @option{-gnatVs} (@code{gcc}) + All subscripts expressions are checked for validity, whether they appear + on the right side or left side (in default mode only left side subscripts + are validity checked). + + @item -gnatVt + @emph{Validity checks for tests.} + @cindex @option{-gnatVt} (@code{gcc}) + Expressions used as conditions in @code{if}, @code{while} or @code{exit} + statements are checked, as well as guard expressions in entry calls. + + @end table + + @noindent + The @option{-gnatV} switch may be followed by + ^a string of letters^a list of options^ + to turn on a series of validity checking options. + For example, + @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^} + specifies that in addition to the default validity checking, copies and + function return expressions are to be validity checked. + In order to make it easier + to specify the desired combination of effects, + @ifclear vms + the upper case letters @code{CDFIMORST} may + be used to turn off the corresponding lower case option. + @end ifclear + @ifset vms + the prefix @code{NO} on an option turns off the corresponding validity + checking: + @itemize @bullet + @item @code{NOCOPIES} + @item @code{NODEFAULT} + @item @code{NOFLOATS} + @item @code{NOIN_PARAMS} + @item @code{NOMOD_PARAMS} + @item @code{NOOPERANDS} + @item @code{NORETURNS} + @item @code{NOSUBSCRIPTS} + @item @code{NOTESTS} + @end itemize + @end ifset + Thus + @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^} + turns on all validity checking options except for + checking of @code{@b{in out}} procedure arguments. + + The specification of additional validity checking generates extra code (and + in the case of @option{-gnatVa} the code expansion can be substantial. + However, these additional checks can be very useful in detecting + uninitialized variables, incorrect use of unchecked conversion, and other + errors leading to invalid values. The use of pragma @code{Initialize_Scalars} + is useful in conjunction with the extra validity checking, since this + ensures that wherever possible uninitialized variables have invalid values. + + See also the pragma @code{Validity_Checks} which allows modification of + the validity checking mode at the program source level, and also allows for + temporary disabling of validity checks. + + + @node Style Checking + @subsection Style Checking + @findex Style checking + + @noindent + The @option{-gnaty^x^(option,option,...)^} switch + @cindex @option{-gnaty} (@code{gcc}) + causes the compiler to + enforce specified style rules. A limited set of style rules has been used + in writing the GNAT sources themselves. This switch allows user programs + to activate all or some of these checks. If the source program fails a + specified style check, an appropriate warning message is given, preceded by + the character sequence ``(style)''. + @ifset vms + @code{(option,option,...)} is a sequence of keywords + @end ifset + @ifclear vms + The string @var{x} is a sequence of letters or digits + @end ifclear + indicating the particular style + checks to be performed. The following checks are defined: + + @table @option + @c !sort! + @item 1-9 + @emph{Specify indentation level.} + If a digit from 1-9 appears + ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^ + then proper indentation is checked, with the digit indicating the + indentation level required. + The general style of required indentation is as specified by + the examples in the Ada Reference Manual. Full line comments must be + aligned with the @code{--} starting on a column that is a multiple of + the alignment level. + + @item ^a^ATTRIBUTE^ + @emph{Check attribute casing.} + If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty} + then attribute names, including the case of keywords such as @code{digits} + used as attributes names, must be written in mixed case, that is, the + initial letter and any letter following an underscore must be uppercase. + All other letters must be lowercase. + + @item ^b^BLANKS^ + @emph{Blanks not allowed at statement end.} + If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then + trailing blanks are not allowed at the end of statements. The purpose of this + rule, together with h (no horizontal tabs), is to enforce a canonical format + for the use of blanks to separate source tokens. + + @item ^c^COMMENTS^ + @emph{Check comments.} + If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty} + then comments must meet the following set of rules: + + @itemize @bullet + + @item + The ``@code{--}'' that starts the column must either start in column one, + or else at least one blank must precede this sequence. + + @item + Comments that follow other tokens on a line must have at least one blank + following the ``@code{--}'' at the start of the comment. + + @item + Full line comments must have two blanks following the ``@code{--}'' that + starts the comment, with the following exceptions. + + @item + A line consisting only of the ``@code{--}'' characters, possibly preceded + by blanks is permitted. + + @item + A comment starting with ``@code{--x}'' where @code{x} is a special character + is permitted. + This allows proper processing of the output generated by specialized tools + including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK + annotation + language (where ``@code{--#}'' is used). For the purposes of this rule, a + special character is defined as being in one of the ASCII ranges + @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}. + Note that this usage is not permitted + in GNAT implementation units (i.e. when @option{-gnatg} is used). + + @item + A line consisting entirely of minus signs, possibly preceded by blanks, is + permitted. This allows the construction of box comments where lines of minus + signs are used to form the top and bottom of the box. + + @item + If a comment starts and ends with ``@code{--}'' is permitted as long as at + least one blank follows the initial ``@code{--}''. Together with the preceding + rule, this allows the construction of box comments, as shown in the following + example: + @smallexample + --------------------------- + -- This is a box comment -- + -- with two text lines. -- + --------------------------- + @end smallexample + @end itemize + + @item ^e^END^ + @emph{Check end/exit labels.} + If the ^letter e^word END^ appears in the string after @option{-gnaty} then + optional labels on @code{end} statements ending subprograms and on + @code{exit} statements exiting named loops, are required to be present. + + @item ^f^VTABS^ + @emph{No form feeds or vertical tabs.} + If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then + neither form feeds nor vertical tab characters are not permitted + in the source text. + + @item ^h^HTABS^ + @emph{No horizontal tabs.} + If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then + horizontal tab characters are not permitted in the source text. + Together with the b (no blanks at end of line) check, this + enforces a canonical form for the use of blanks to separate + source tokens. + + @item ^i^IF_THEN^ + @emph{Check if-then layout.} + If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty}, + then the keyword @code{then} must appear either on the same + line as corresponding @code{if}, or on a line on its own, lined + up under the @code{if} with at least one non-blank line in between + containing all or part of the condition to be tested. + + @item ^k^KEYWORD^ + @emph{Check keyword casing.} + If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then + all keywords must be in lower case (with the exception of keywords + such as @code{digits} used as attribute names to which this check + does not apply). + + @item ^l^LAYOUT^ + @emph{Check layout.} + If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then + layout of statement and declaration constructs must follow the + recommendations in the Ada Reference Manual, as indicated by the + form of the syntax rules. For example an @code{else} keyword must + be lined up with the corresponding @code{if} keyword. + + There are two respects in which the style rule enforced by this check + option are more liberal than those in the Ada Reference Manual. First + in the case of record declarations, it is permissible to put the + @code{record} keyword on the same line as the @code{type} keyword, and + then the @code{end} in @code{end record} must line up under @code{type}. + For example, either of the following two layouts is acceptable: + + @smallexample @c ada + @cartouche + type q is record + a : integer; + b : integer; + end record; + + type q is + record + a : integer; + b : integer; + end record; + @end cartouche + @end smallexample + + @noindent + Second, in the case of a block statement, a permitted alternative + is to put the block label on the same line as the @code{declare} or + @code{begin} keyword, and then line the @code{end} keyword up under + the block label. For example both the following are permitted: + + @smallexample @c ada + @cartouche + Block : declare + A : Integer := 3; + begin + Proc (A, A); + end Block; + + Block : + declare + A : Integer := 3; + begin + Proc (A, A); + end Block; + @end cartouche + @end smallexample + + @noindent + The same alternative format is allowed for loops. For example, both of + the following are permitted: + + @smallexample @c ada + @cartouche + Clear : while J < 10 loop + A (J) := 0; + end loop Clear; + + Clear : + while J < 10 loop + A (J) := 0; + end loop Clear; + @end cartouche + @end smallexample + + @item ^m^LINE_LENGTH^ + @emph{Check maximum line length.} + If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty} + then the length of source lines must not exceed 79 characters, including + any trailing blanks. The value of 79 allows convenient display on an + 80 character wide device or window, allowing for possible special + treatment of 80 character lines. Note that this count is of raw + characters in the source text. This means that a tab character counts + as one character in this count and a wide character sequence counts as + several characters (however many are needed in the encoding). + + @item ^Mnnn^MAX_LENGTH=nnn^ + @emph{Set maximum line length.} + If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in + the string after @option{-gnaty} then the length of lines must not exceed the + given value. + + @item ^n^STANDARD_CASING^ + @emph{Check casing of entities in Standard.} + If the ^letter n^word STANDARD_CASING^ appears in the string + after @option{-gnaty} then any identifier from Standard must be cased + to match the presentation in the Ada Reference Manual (for example, + @code{Integer} and @code{ASCII.NUL}). + + @item ^o^ORDERED_SUBPROGRAMS^ + @emph{Check order of subprogram bodies.} + If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string + after @option{-gnaty} then all subprogram bodies in a given scope + (e.g. a package body) must be in alphabetical order. The ordering + rule uses normal Ada rules for comparing strings, ignoring casing + of letters, except that if there is a trailing numeric suffix, then + the value of this suffix is used in the ordering (e.g. Junk2 comes + before Junk10). + + @item ^p^PRAGMA^ + @emph{Check pragma casing.} + If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then + pragma names must be written in mixed case, that is, the + initial letter and any letter following an underscore must be uppercase. + All other letters must be lowercase. + + @item ^r^REFERENCES^ + @emph{Check references.} + If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty} + then all identifier references must be cased in the same way as the + corresponding declaration. No specific casing style is imposed on + identifiers. The only requirement is for consistency of references + with declarations. + + @item ^s^SPECS^ + @emph{Check separate specs.} + If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then + separate declarations (``specs'') are required for subprograms (a + body is not allowed to serve as its own declaration). The only + exception is that parameterless library level procedures are + not required to have a separate declaration. This exception covers + the most frequent form of main program procedures. + + @item ^t^TOKEN^ + @emph{Check token spacing.} + If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then + the following token spacing rules are enforced: + + @itemize @bullet + + @item + The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space. + + @item + The token @code{=>} must be surrounded by spaces. + + @item + The token @code{<>} must be preceded by a space or a left parenthesis. + + @item + Binary operators other than @code{**} must be surrounded by spaces. + There is no restriction on the layout of the @code{**} binary operator. + + @item + Colon must be surrounded by spaces. + + @item + Colon-equal (assignment, initialization) must be surrounded by spaces. + + @item + Comma must be the first non-blank character on the line, or be + immediately preceded by a non-blank character, and must be followed + by a space. + + @item + If the token preceding a left parenthesis ends with a letter or digit, then + a space must separate the two tokens. + + @item + A right parenthesis must either be the first non-blank character on + a line, or it must be preceded by a non-blank character. + + @item + A semicolon must not be preceded by a space, and must not be followed by + a non-blank character. + + @item + A unary plus or minus may not be followed by a space. + + @item + A vertical bar must be surrounded by spaces. + @end itemize + + @noindent + In the above rules, appearing in column one is always permitted, that is, + counts as meeting either a requirement for a required preceding space, + or as meeting a requirement for no preceding space. + + Appearing at the end of a line is also always permitted, that is, counts + as meeting either a requirement for a following space, or as meeting + a requirement for no following space. + + @end table + + @noindent + If any of these style rules is violated, a message is generated giving + details on the violation. The initial characters of such messages are + always ``@code{(style)}''. Note that these messages are treated as warning + messages, so they normally do not prevent the generation of an object + file. The @option{-gnatwe} switch can be used to treat warning messages, + including style messages, as fatal errors. + + @noindent + The switch + @ifclear vms + @option{-gnaty} on its own (that is not + followed by any letters or digits), + is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking + options enabled with the exception of -gnatyo, + @end ifclear + @ifset vms + /STYLE_CHECKS=ALL_BUILTIN enables all checking options with + the exception of ORDERED_SUBPROGRAMS, + @end ifset + with an indentation level of 3. This is the standard + checking option that is used for the GNAT sources. + + + @node Run-Time Checks + @subsection Run-Time Checks + @cindex Division by zero + @cindex Access before elaboration + @cindex Checks, division by zero + @cindex Checks, access before elaboration + + @noindent + If you compile with the default options, GNAT will insert many run-time + checks into the compiled code, including code that performs range + checking against constraints, but not arithmetic overflow checking for + integer operations (including division by zero) or checks for access + before elaboration on subprogram calls. All other run-time checks, as + required by the Ada 95 Reference Manual, are generated by default. + The following @code{gcc} switches refine this default behavior: + + @table @option + @c !sort! + @item -gnatp + @cindex @option{-gnatp} (@code{gcc}) + @cindex Suppressing checks + @cindex Checks, suppressing + @findex Suppress + Suppress all run-time checks as though @code{pragma Suppress (all_checks}) + had been present in the source. Validity checks are also suppressed (in + other words @option{-gnatp} also implies @option{-gnatVn}. + Use this switch to improve the performance + of the code at the expense of safety in the presence of invalid data or + program bugs. + + @item -gnato + @cindex @option{-gnato} (@code{gcc}) + @cindex Overflow checks + @cindex Check, overflow + Enables overflow checking for integer operations. + This causes GNAT to generate slower and larger executable + programs by adding code to check for overflow (resulting in raising + @code{Constraint_Error} as required by standard Ada + semantics). These overflow checks correspond to situations in which + the true value of the result of an operation may be outside the base + range of the result type. The following example shows the distinction: + + @smallexample @c ada + X1 : Integer := Integer'Last; + X2 : Integer range 1 .. 5 := 5; + X3 : Integer := Integer'Last; + X4 : Integer range 1 .. 5 := 5; + F : Float := 2.0E+20; + ... + X1 := X1 + 1; + X2 := X2 + 1; + X3 := Integer (F); + X4 := Integer (F); + @end smallexample + + @noindent + Here the first addition results in a value that is outside the base range + of Integer, and hence requires an overflow check for detection of the + constraint error. Thus the first assignment to @code{X1} raises a + @code{Constraint_Error} exception only if @option{-gnato} is set. + + The second increment operation results in a violation + of the explicit range constraint, and such range checks are always + performed (unless specifically suppressed with a pragma @code{suppress} + or the use of @option{-gnatp}). + + The two conversions of @code{F} both result in values that are outside + the base range of type @code{Integer} and thus will raise + @code{Constraint_Error} exceptions only if @option{-gnato} is used. + The fact that the result of the second conversion is assigned to + variable @code{X4} with a restricted range is irrelevant, since the problem + is in the conversion, not the assignment. + + Basically the rule is that in the default mode (@option{-gnato} not + used), the generated code assures that all integer variables stay + within their declared ranges, or within the base range if there is + no declared range. This prevents any serious problems like indexes + out of range for array operations. + + What is not checked in default mode is an overflow that results in + an in-range, but incorrect value. In the above example, the assignments + to @code{X1}, @code{X2}, @code{X3} all give results that are within the + range of the target variable, but the result is wrong in the sense that + it is too large to be represented correctly. Typically the assignment + to @code{X1} will result in wrap around to the largest negative number. + The conversions of @code{F} will result in some @code{Integer} value + and if that integer value is out of the @code{X4} range then the + subsequent assignment would generate an exception. + + @findex Machine_Overflows + Note that the @option{-gnato} switch does not affect the code generated + for any floating-point operations; it applies only to integer + semantics). + For floating-point, GNAT has the @code{Machine_Overflows} + attribute set to @code{False} and the normal mode of operation is to + generate IEEE NaN and infinite values on overflow or invalid operations + (such as dividing 0.0 by 0.0). + + The reason that we distinguish overflow checking from other kinds of + range constraint checking is that a failure of an overflow check can + generate an incorrect value, but cannot cause erroneous behavior. This + is unlike the situation with a constraint check on an array subscript, + where failure to perform the check can result in random memory description, + or the range check on a case statement, where failure to perform the check + can cause a wild jump. + + Note again that @option{-gnato} is off by default, so overflow checking is + not performed in default mode. This means that out of the box, with the + default settings, GNAT does not do all the checks expected from the + language description in the Ada Reference Manual. If you want all constraint + checks to be performed, as described in this Manual, then you must + explicitly use the -gnato switch either on the @code{gnatmake} or + @code{gcc} command. + + @item -gnatE + @cindex @option{-gnatE} (@code{gcc}) + @cindex Elaboration checks + @cindex Check, elaboration + Enables dynamic checks for access-before-elaboration + on subprogram calls and generic instantiations. + For full details of the effect and use of this switch, + @xref{Compiling Using gcc}. + @end table + + @findex Unsuppress + @noindent + The setting of these switches only controls the default setting of the + checks. You may modify them using either @code{Suppress} (to remove + checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in + the program source. + + @node Stack Overflow Checking + @subsection Stack Overflow Checking + @cindex Stack Overflow Checking + @cindex -fstack-check + + @noindent + For most operating systems, @code{gcc} does not perform stack overflow + checking by default. This means that if the main environment task or + some other task exceeds the available stack space, then unpredictable + behavior will occur. + + To activate stack checking, compile all units with the gcc option + @option{-fstack-check}. For example: + + @smallexample + gcc -c -fstack-check package1.adb + @end smallexample + + @noindent + Units compiled with this option will generate extra instructions to check + that any use of the stack (for procedure calls or for declaring local + variables in declare blocks) do not exceed the available stack space. + If the space is exceeded, then a @code{Storage_Error} exception is raised. + + For declared tasks, the stack size is always controlled by the size + given in an applicable @code{Storage_Size} pragma (or is set to + the default size if no pragma is used. + + For the environment task, the stack size depends on + system defaults and is unknown to the compiler. The stack + may even dynamically grow on some systems, precluding the + normal Ada semantics for stack overflow. In the worst case, + unbounded stack usage, causes unbounded stack expansion + resulting in the system running out of virtual memory. + + The stack checking may still work correctly if a fixed + size stack is allocated, but this cannot be guaranteed. + To ensure that a clean exception is signalled for stack + overflow, set the environment variable + @code{GNAT_STACK_LIMIT} to indicate the maximum + stack area that can be used, as in: + @cindex GNAT_STACK_LIMIT + + @smallexample + SET GNAT_STACK_LIMIT 1600 + @end smallexample + + @noindent + The limit is given in kilobytes, so the above declaration would + set the stack limit of the environment task to 1.6 megabytes. + Note that the only purpose of this usage is to limit the amount + of stack used by the environment task. If it is necessary to + increase the amount of stack for the environment task, then this + is an operating systems issue, and must be addressed with the + appropriate operating systems commands. + + + @node Using gcc for Syntax Checking + @subsection Using @code{gcc} for Syntax Checking + @table @option + @item -gnats + @cindex @option{-gnats} (@code{gcc}) + @ifclear vms + + @noindent + The @code{s} stands for ``syntax''. + @end ifclear + + Run GNAT in syntax checking only mode. For + example, the command + + @smallexample + $ gcc -c -gnats x.adb + @end smallexample + + @noindent + compiles file @file{x.adb} in syntax-check-only mode. You can check a + series of files in a single command + @ifclear vms + , and can use wild cards to specify such a group of files. + Note that you must specify the @option{-c} (compile + only) flag in addition to the @option{-gnats} flag. + @end ifclear + . + You may use other switches in conjunction with @option{-gnats}. In + particular, @option{-gnatl} and @option{-gnatv} are useful to control the + format of any generated error messages. + + When the source file is empty or contains only empty lines and/or comments, + the output is a warning: + + @smallexample + $ gcc -c -gnats -x ada toto.txt + toto.txt:1:01: warning: empty file, contains no compilation units + $ + @end smallexample + + Otherwise, the output is simply the error messages, if any. No object file or + ALI file is generated by a syntax-only compilation. Also, no units other + than the one specified are accessed. For example, if a unit @code{X} + @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax + check only mode does not access the source file containing unit + @code{Y}. + + @cindex Multiple units, syntax checking + Normally, GNAT allows only a single unit in a source file. However, this + restriction does not apply in syntax-check-only mode, and it is possible + to check a file containing multiple compilation units concatenated + together. This is primarily used by the @code{gnatchop} utility + (@pxref{Renaming Files Using gnatchop}). + @end table + + + @node Using gcc for Semantic Checking + @subsection Using @code{gcc} for Semantic Checking + @table @option + @item -gnatc + @cindex @option{-gnatc} (@code{gcc}) + + @ifclear vms + @noindent + The @code{c} stands for ``check''. + @end ifclear + Causes the compiler to operate in semantic check mode, + with full checking for all illegalities specified in the + Ada 95 Reference Manual, but without generation of any object code + (no object file is generated). + + Because dependent files must be accessed, you must follow the GNAT + semantic restrictions on file structuring to operate in this mode: + + @itemize @bullet + @item + The needed source files must be accessible + (@pxref{Search Paths and the Run-Time Library (RTL)}). + + @item + Each file must contain only one compilation unit. + + @item + The file name and unit name must match (@pxref{File Naming Rules}). + @end itemize + + The output consists of error messages as appropriate. No object file is + generated. An @file{ALI} file is generated for use in the context of + cross-reference tools, but this file is marked as not being suitable + for binding (since no object file is generated). + The checking corresponds exactly to the notion of + legality in the Ada 95 Reference Manual. + + Any unit can be compiled in semantics-checking-only mode, including + units that would not normally be compiled (subunits, + and specifications where a separate body is present). + @end table + + @node Compiling Ada 83 Programs + @subsection Compiling Ada 83 Programs + @table @option + @cindex Ada 83 compatibility + @item -gnat83 + @cindex @option{-gnat83} (@code{gcc}) + @cindex ACVC, Ada 83 tests + + @noindent + Although GNAT is primarily an Ada 95 compiler, it accepts this switch to + specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify + this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics + where this can be done easily. + It is not possible to guarantee this switch does a perfect + job; for example, some subtle tests, such as are + found in earlier ACVC tests (and that have been removed from the ACATS suite + for Ada 95), might not compile correctly. + Nevertheless, this switch may be useful in some circumstances, for example + where, due to contractual reasons, legacy code needs to be maintained + using only Ada 83 features. + + With few exceptions (most notably the need to use @code{<>} on + @cindex Generic formal parameters + unconstrained generic formal parameters, the use of the new Ada 95 + reserved words, and the use of packages + with optional bodies), it is not necessary to use the + @option{-gnat83} switch when compiling Ada 83 programs, because, with rare + exceptions, Ada 95 is upwardly compatible with Ada 83. This + means that a correct Ada 83 program is usually also a correct Ada 95 + program. + For further information, please refer to @ref{Compatibility and Porting Guide}. + + @end table + + @node Character Set Control + @subsection Character Set Control + @table @option + @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c} + @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc}) + + @noindent + Normally GNAT recognizes the Latin-1 character set in source program + identifiers, as described in the Ada 95 Reference Manual. + This switch causes + GNAT to recognize alternate character sets in identifiers. @var{c} is a + single character ^^or word^ indicating the character set, as follows: + + @table @code + @item 1 + ISO 8859-1 (Latin-1) identifiers + + @item 2 + ISO 8859-2 (Latin-2) letters allowed in identifiers + + @item 3 + ISO 8859-3 (Latin-3) letters allowed in identifiers + + @item 4 + ISO 8859-4 (Latin-4) letters allowed in identifiers + + @item 5 + ISO 8859-5 (Cyrillic) letters allowed in identifiers + + @item 9 + ISO 8859-15 (Latin-9) letters allowed in identifiers + + @item ^p^PC^ + IBM PC letters (code page 437) allowed in identifiers + + @item ^8^PC850^ + IBM PC letters (code page 850) allowed in identifiers + + @item ^f^FULL_UPPER^ + Full upper-half codes allowed in identifiers + + @item ^n^NO_UPPER^ + No upper-half codes allowed in identifiers + + @item ^w^WIDE^ + Wide-character codes (that is, codes greater than 255) + allowed in identifiers + @end table + + @xref{Foreign Language Representation}, for full details on the + implementation of these character sets. + + @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e} + @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc}) + Specify the method of encoding for wide characters. + @var{e} is one of the following: + + @table @code + + @item ^h^HEX^ + Hex encoding (brackets coding also recognized) + + @item ^u^UPPER^ + Upper half encoding (brackets encoding also recognized) + + @item ^s^SHIFT_JIS^ + Shift/JIS encoding (brackets encoding also recognized) + + @item ^e^EUC^ + EUC encoding (brackets encoding also recognized) + + @item ^8^UTF8^ + UTF-8 encoding (brackets encoding also recognized) + + @item ^b^BRACKETS^ + Brackets encoding only (default value) + @end table + For full details on the these encoding + methods see @xref{Wide Character Encodings}. + Note that brackets coding is always accepted, even if one of the other + options is specified, so for example @option{-gnatW8} specifies that both + brackets and @code{UTF-8} encodings will be recognized. The units that are + with'ed directly or indirectly will be scanned using the specified + representation scheme, and so if one of the non-brackets scheme is + used, it must be used consistently throughout the program. However, + since brackets encoding is always recognized, it may be conveniently + used in standard libraries, allowing these libraries to be used with + any of the available coding schemes. + scheme. If no @option{-gnatW?} parameter is present, then the default + representation is Brackets encoding only. + + Note that the wide character representation that is specified (explicitly + or by default) for the main program also acts as the default encoding used + for Wide_Text_IO files if not specifically overridden by a WCEM form + parameter. + + @end table + @node File Naming Control + @subsection File Naming Control + + @table @option + @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n} + @cindex @option{-gnatk} (@code{gcc}) + Activates file name ``krunching''. @var{n}, a decimal integer in the range + 1-999, indicates the maximum allowable length of a file name (not + including the @file{.ads} or @file{.adb} extension). The default is not + to enable file name krunching. + + For the source file naming rules, @xref{File Naming Rules}. + @end table + + + @node Subprogram Inlining Control + @subsection Subprogram Inlining Control + + @table @option + @c !sort! + @item -gnatn + @cindex @option{-gnatn} (@code{gcc}) + @ifclear vms + The @code{n} here is intended to suggest the first syllable of the + word ``inline''. + @end ifclear + GNAT recognizes and processes @code{Inline} pragmas. However, for the + inlining to actually occur, optimization must be enabled. To enable + inlining of subprograms specified by pragma @code{Inline}, + you must also specify this switch. + In the absence of this switch, GNAT does not attempt + inlining and does not need to access the bodies of + subprograms for which @code{pragma Inline} is specified if they are not + in the current unit. + + If you specify this switch the compiler will access these bodies, + creating an extra source dependency for the resulting object file, and + where possible, the call will be inlined. + For further details on when inlining is possible + see @xref{Inlining of Subprograms}. + + @item -gnatN + @cindex @option{-gnatN} (@code{gcc}) + The front end inlining activated by this switch is generally more extensive, + and quite often more effective than the standard @option{-gnatn} inlining mode. + It will also generate additional dependencies. + Note that + @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary + to specify both options. + @end table + + @node Auxiliary Output Control + @subsection Auxiliary Output Control + + @table @option + @item -gnatt + @cindex @option{-gnatt} (@code{gcc}) + @cindex Writing internal trees + @cindex Internal trees, writing to file + Causes GNAT to write the internal tree for a unit to a file (with the + extension @file{.adt}. + This not normally required, but is used by separate analysis tools. + Typically + these tools do the necessary compilations automatically, so you should + not have to specify this switch in normal operation. + + @item -gnatu + @cindex @option{-gnatu} (@code{gcc}) + Print a list of units required by this compilation on @file{stdout}. + The listing includes all units on which the unit being compiled depends + either directly or indirectly. + + @ifclear vms + @item -pass-exit-codes + @cindex @option{-pass-exit-codes} (@code{gcc}) + If this switch is not used, the exit code returned by @code{gcc} when + compiling multiple files indicates whether all source files have + been successfully used to generate object files or not. + + When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended + exit status and allows an integrated development environment to better + react to a compilation failure. Those exit status are: + + @table @asis + @item 5 + There was an error in at least one source file. + @item 3 + At least one source file did not generate an object file. + @item 2 + The compiler died unexpectedly (internal error for example). + @item 0 + An object file has been generated for every source file. + @end table + @end ifclear + @end table + + @node Debugging Control + @subsection Debugging Control + + @table @option + @c !sort! + @cindex Debugging options + @ifclear vms + @item -gnatd@var{x} + @cindex @option{-gnatd} (@code{gcc}) + Activate internal debugging switches. @var{x} is a letter or digit, or + string of letters or digits, which specifies the type of debugging + outputs desired. Normally these are used only for internal development + or system debugging purposes. You can find full documentation for these + switches in the body of the @code{Debug} unit in the compiler source + file @file{debug.adb}. + @end ifclear + + @item -gnatG + @cindex @option{-gnatG} (@code{gcc}) + This switch causes the compiler to generate auxiliary output containing + a pseudo-source listing of the generated expanded code. Like most Ada + compilers, GNAT works by first transforming the high level Ada code into + lower level constructs. For example, tasking operations are transformed + into calls to the tasking run-time routines. A unique capability of GNAT + is to list this expanded code in a form very close to normal Ada source. + This is very useful in understanding the implications of various Ada + usage on the efficiency of the generated code. There are many cases in + Ada (e.g. the use of controlled types), where simple Ada statements can + generate a lot of run-time code. By using @option{-gnatG} you can identify + these cases, and consider whether it may be desirable to modify the coding + approach to improve efficiency. + + The format of the output is very similar to standard Ada source, and is + easily understood by an Ada programmer. The following special syntactic + additions correspond to low level features used in the generated code that + do not have any exact analogies in pure Ada source form. The following + is a partial list of these special constructions. See the specification + of package @code{Sprint} in file @file{sprint.ads} for a full list. + + @table @code + @item new @var{xxx} [storage_pool = @var{yyy}] + Shows the storage pool being used for an allocator. + + @item at end @var{procedure-name}; + Shows the finalization (cleanup) procedure for a scope. + + @item (if @var{expr} then @var{expr} else @var{expr}) + Conditional expression equivalent to the @code{x?y:z} construction in C. + + @item @var{target}^^^(@var{source}) + A conversion with floating-point truncation instead of rounding. + + @item @var{target}?(@var{source}) + A conversion that bypasses normal Ada semantic checking. In particular + enumeration types and fixed-point types are treated simply as integers. + + @item @var{target}?^^^(@var{source}) + Combines the above two cases. + + @item @var{x} #/ @var{y} + @itemx @var{x} #mod @var{y} + @itemx @var{x} #* @var{y} + @itemx @var{x} #rem @var{y} + A division or multiplication of fixed-point values which are treated as + integers without any kind of scaling. + + @item free @var{expr} [storage_pool = @var{xxx}] + Shows the storage pool associated with a @code{free} statement. + + @item freeze @var{typename} [@var{actions}] + Shows the point at which @var{typename} is frozen, with possible + associated actions to be performed at the freeze point. + + @item reference @var{itype} + Reference (and hence definition) to internal type @var{itype}. + + @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) + Intrinsic function call. + + @item @var{labelname} : label + Declaration of label @var{labelname}. + + @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr} + A multiple concatenation (same effect as @var{expr} & @var{expr} & + @var{expr}, but handled more efficiently). + + @item [constraint_error] + Raise the @code{Constraint_Error} exception. + + @item @var{expression}'reference + A pointer to the result of evaluating @var{expression}. + + @item @var{target-type}!(@var{source-expression}) + An unchecked conversion of @var{source-expression} to @var{target-type}. + + @item [@var{numerator}/@var{denominator}] + Used to represent internal real literals (that) have no exact + representation in base 2-16 (for example, the result of compile time + evaluation of the expression 1.0/27.0). + @end table + + @item -gnatD + @cindex @option{-gnatD} (@code{gcc}) + This switch is used in conjunction with @option{-gnatG} to cause the expanded + source, as described above to be written to files with names + @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name, + for example, if the source file name is @file{hello.adb}, + then a file @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. + The debugging information generated + by the @code{gcc} @option{^-g^/DEBUG^} switch will refer to the generated + @file{^xxx.dg^XXX_DG^} file. This allows you to do source level debugging using + the generated code which is sometimes useful for complex code, for example + to find out exactly which part of a complex construction raised an + exception. This switch also suppress generation of cross-reference + information (see -gnatx). + + @ifclear vms + @item -gnatR[0|1|2|3[s]] + @cindex @option{-gnatR} (@code{gcc}) + This switch controls output from the compiler of a listing showing + representation information for declared types and objects. For + @option{-gnatR0}, no information is output (equivalent to omitting + the @option{-gnatR} switch). For @option{-gnatR1} (which is the default, + so @option{-gnatR} with no parameter has the same effect), size and alignment + information is listed for declared array and record types. For + @option{-gnatR2}, size and alignment information is listed for all + expression information for values that are computed at run time for + variant records. These symbolic expressions have a mostly obvious + format with #n being used to represent the value of the n'th + discriminant. See source files @file{repinfo.ads/adb} in the + @code{GNAT} sources for full details on the format of @option{-gnatR3} + output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then + the output is to a file with the name @file{^file.rep^file_REP^} where + file is the name of the corresponding source file. + @end ifclear + @ifset vms + @item /REPRESENTATION_INFO + @cindex @option{/REPRESENTATION_INFO} (@code{gcc}) + This qualifier controls output from the compiler of a listing showing + representation information for declared types and objects. For + @option{/REPRESENTATION_INFO=NONE}, no information is output + (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier). + @option{/REPRESENTATION_INFO} without option is equivalent to + @option{/REPRESENTATION_INFO=ARRAYS}. + For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment + information is listed for declared array and record types. For + @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information + is listed for all expression information for values that are computed + at run time for variant records. These symbolic expressions have a mostly + obvious format with #n being used to represent the value of the n'th + discriminant. See source files @file{REPINFO.ADS/ADB} in the + @code{GNAT} sources for full details on the format of + @option{/REPRESENTATION_INFO=SYMBOLIC} output. + If _FILE is added at the end of an option + (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}), + then the output is to a file with the name @file{file_REP} where + file is the name of the corresponding source file. + @end ifset + + @item -gnatS + @cindex @option{-gnatS} (@code{gcc}) + The use of the switch @option{-gnatS} for an + Ada compilation will cause the compiler to output a + representation of package Standard in a form very + close to standard Ada. It is not quite possible to + do this and remain entirely Standard (since new + numeric base types cannot be created in standard + Ada), but the output is easily + readable to any Ada programmer, and is useful to + determine the characteristics of target dependent + types in package Standard. + + @item -gnatx + @cindex @option{-gnatx} (@code{gcc}) + Normally the compiler generates full cross-referencing information in + the @file{ALI} file. This information is used by a number of tools, + including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch + suppresses this information. This saves some space and may slightly + speed up compilation, but means that these tools cannot be used. + @end table + + @node Exception Handling Control + @subsection Exception Handling Control + + @noindent + GNAT uses two methods for handling exceptions at run-time. The + @code{longjmp/setjmp} method saves the context when entering + a frame with an exception handler. Then when an exception is + raised, the context can be restored immediately, without the + need for tracing stack frames. This method provides very fast + exception propagation, but introduces significant overhead for + the use of exception handlers, even if no exception is raised. + + The other approach is called ``zero cost'' exception handling. + With this method, the compiler builds static tables to describe + the exception ranges. No dynamic code is required when entering + a frame containing an exception handler. When an exception is + raised, the tables are used to control a back trace of the + subprogram invocation stack to locate the required exception + handler. This method has considerably poorer performance for + the propagation of exceptions, but there is no overhead for + exception handlers if no exception is raised. + + The following switches can be used to control which of the + two exception handling methods is used. + + @table @option + @c !sort! + + @item -gnatL + @cindex @option{-gnatL} (@code{gcc}) + This switch causes the longjmp/setjmp approach to be used + for exception handling. If this is the default mechanism for the + target (see below), then this has no effect. If the default + mechanism for the target is zero cost exceptions, then + this switch can be used to modify this default, but it must be + used for all units in the partition, including all run-time + library units. One way to achieve this is to use the + @option{-a} and @option{-f} switches for @code{gnatmake}. + This option is rarely used. One case in which it may be + advantageous is if you have an application where exception + raising is common and the overall performance of the + application is improved by favoring exception propagation. + + @item -gnatZ + @cindex @option{-gnatZ} (@code{gcc}) + @cindex Zero Cost Exceptions + This switch causes the zero cost approach to be sed + for exception handling. If this is the default mechanism for the + target (see below), then this has no effect. If the default + mechanism for the target is longjmp/setjmp exceptions, then + this switch can be used to modify this default, but it must be + used for all units in the partition, including all run-time + library units. One way to achieve this is to use the + @option{-a} and @option{-f} switches for @code{gnatmake}. + This option can only be used if the zero cost approach + is available for the target in use (see below). + @end table + + @noindent + The @code{longjmp/setjmp} approach is available on all targets, but + the @code{zero cost} approach is only available on selected targets. + To determine whether zero cost exceptions can be used for a + particular target, look at the private part of the file system.ads. + Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must + be True to use the zero cost approach. If both of these switches + are set to False, this means that zero cost exception handling + is not yet available for that target. The switch + @code{ZCX_By_Default} indicates the default approach. If this + switch is set to True, then the @code{zero cost} approach is + used by default. + + @node Units to Sources Mapping Files + @subsection Units to Sources Mapping Files + + @table @option + + @item -gnatem^^=^@var{path} + @cindex @option{-gnatem} (@code{gcc}) + A mapping file is a way to communicate to the compiler two mappings: + from unit names to file names (without any directory information) and from + file names to path names (with full directory information). These mappings + are used by the compiler to short-circuit the path search. + + The use of mapping files is not required for correct operation of the + compiler, but mapping files can improve efficiency, particularly when + sources are read over a slow network connection. In normal operation, + you need not be concerned with the format or use of mapping files, + and the @option{-gnatem} switch is not a switch that you would use + explicitly. it is intended only for use by automatic tools such as + @code{gnatmake} running under the project file facility. The + description here of the format of mapping files is provided + for completeness and for possible use by other tools. + + A mapping file is a sequence of sets of three lines. In each set, + the first line is the unit name, in lower case, with ``@code{%s}'' + appended for + specifications and ``@code{%b}'' appended for bodies; the second line is the + file name; and the third line is the path name. + + Example: + @smallexample + main%b + main.2.ada + /gnat/project1/sources/main.2.ada + @end smallexample + + When the switch @option{-gnatem} is specified, the compiler will create + in memory the two mappings from the specified file. If there is any problem + (non existent file, truncated file or duplicate entries), no mapping + will be created. + + Several @option{-gnatem} switches may be specified; however, only the last + one on the command line will be taken into account. + + When using a project file, @code{gnatmake} create a temporary mapping file + and communicates it to the compiler using this switch. + + @end table + + + @node Integrated Preprocessing + @subsection Integrated Preprocessing + + @noindent + GNAT sources may be preprocessed immediately before compilation; the actual + text of the source is not the text of the source file, but is derived from it + through a process called preprocessing. Integrated preprocessing is specified + through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep} + indicates, through a text file, the preprocessing data to be used. + @option{-gnateD} specifies or modifies the values of preprocessing symbol. + + @noindent + It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be + used when Integrated Preprocessing is used. The reason is that preprocessing + with another Preprocessing Data file without changing the sources will + not trigger recompilation without this switch. + + @noindent + Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost + always trigger recompilation for sources that are preprocessed, + because @code{gnatmake} cannot compute the checksum of the source after + preprocessing. + + @noindent + The actual preprocessing function is described in details in section + @ref{Preprocessing Using gnatprep}. This section only describes how integrated + preprocessing is triggered and parameterized. + + @table @code + + @item -gnatep=@var{file} + @cindex @option{-gnatep} (@code{gcc}) + This switch indicates to the compiler the file name (without directory + information) of the preprocessor data file to use. The preprocessor data file + should be found in the source directories. + + @noindent + A preprocessing data file is a text file with significant lines indicating + how should be preprocessed either a specific source or all sources not + mentioned in other lines. A significant line is a non empty, non comment line. + Comments are similar to Ada comments. + + @noindent + Each significant line starts with either a literal string or the character '*'. + A literal string is the file name (without directory information) of the source + to preprocess. A character '*' indicates the preprocessing for all the sources + that are not specified explicitly on other lines (order of the lines is not + significant). It is an error to have two lines with the same file name or two + lines starting with the character '*'. + + @noindent + After the file name or the character '*', another optional literal string + indicating the file name of the definition file to be used for preprocessing. + (see @ref{Form of Definitions File}. The definition files are found by the + compiler in one of the source directories. In some cases, when compiling + a source in a directory other than the current directory, if the definition + file is in the current directory, it may be necessary to add the current + directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise + the compiler would not find the definition file. + + @noindent + Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may + be found. Those ^switches^switches^ are: + + @table @code + + @item -b + Causes both preprocessor lines and the lines deleted by + preprocessing to be replaced by blank lines, preserving the line number. + This ^switch^switch^ is always implied; however, if specified after @option{-c} + it cancels the effect of @option{-c}. + + @item -c + Causes both preprocessor lines and the lines deleted + by preprocessing to be retained as comments marked + with the special string ``@code{--! }''. + + @item -Dsymbol=value + Define or redefine a symbol, associated with value. A symbol is an Ada + identifier, or an Ada reserved word, with the exception of @code{if}, + @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}. + @code{value} is either a literal string, an Ada identifier or any Ada reserved + word. A symbol declared with this ^switch^switch^ replaces a symbol with the + same name defined in a definition file. + + @item -s + Causes a sorted list of symbol names and values to be + listed on the standard output file. + + @item -u + Causes undefined symbols to be treated as having the value @code{FALSE} + in the context + of a preprocessor test. In the absence of this option, an undefined symbol in + a @code{#if} or @code{#elsif} test will be treated as an error. + + @end table + + @noindent + Examples of valid lines in a preprocessor data file: + + @smallexample + "toto.adb" "prep.def" -u + -- preprocess "toto.adb", using definition file "prep.def", + -- undefined symbol are False. + + * -c -DVERSION=V101 + -- preprocess all other sources without a definition file; + -- suppressed lined are commented; symbol VERSION has the value V101. + + "titi.adb" "prep2.def" -s + -- preprocess "titi.adb", using definition file "prep2.def"; + -- list all symbols with their values. + @end smallexample + + @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value] + @cindex @option{-gnateD} (@code{gcc}) + Define or redefine a preprocessing symbol, associated with value. If no value + is given on the command line, then the value of the symbol is @code{True}. + A symbol is an identifier, following normal Ada (case-insensitive) + rules for its syntax, and value is any sequence (including an empty sequence) + of characters from the set (letters, digits, period, underline). + Ada reserved words may be used as symbols, with the exceptions of @code{if}, + @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}. + + @noindent + A symbol declared with this ^switch^switch^ on the command line replaces a + symbol with the same name either in a definition file or specified with a + ^switch^switch^ -D in the preprocessor data file. + + @noindent + This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}. + + @end table + + @ifset vms + @node Return Codes + @subsection Return Codes + @cindex Return Codes + @cindex @option{/RETURN_CODES=VMS} + + @noindent + On VMS, GNAT compiled programs return POSIX-style codes by default, + e.g. @option{/RETURN_CODES=POSIX}. + + To enable VMS style return codes, GNAT LINK with the option + @option{/RETURN_CODES=VMS}. For example: + + @smallexample + GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS + @end smallexample + + @noindent + Programs built with /RETURN_CODES=VMS are suitable to be called in + VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX + are suitable for spawning with appropriate GNAT RTL routines. + + @end ifset + + + @node Search Paths and the Run-Time Library (RTL) + @section Search Paths and the Run-Time Library (RTL) + + @noindent + With the GNAT source-based library system, the compiler must be able to + find source files for units that are needed by the unit being compiled. + Search paths are used to guide this process. + + The compiler compiles one source file whose name must be given + explicitly on the command line. In other words, no searching is done + for this file. To find all other source files that are needed (the most + common being the specs of units), the compiler examines the following + directories, in the following order: + + @enumerate + @item + The directory containing the source file of the main unit being compiled + (the file name on the command line). + + @item + Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the + @code{gcc} command line, in the order given. + + @item + @findex ADA_INCLUDE_PATH + Each of the directories listed in the value of the + @code{ADA_INCLUDE_PATH} ^environment variable^logical name^. + @ifclear vms + Construct this value + exactly as the @code{PATH} environment variable: a list of directory + names separated by colons (semicolons when working with the NT version). + @end ifclear + @ifset vms + Normally, define this value as a logical name containing a comma separated + list of directory names. + + This variable can also be defined by means of an environment string + (an argument to the DEC C exec* set of functions). + + Logical Name: + @smallexample + DEFINE ANOTHER_PATH FOO:[BAG] + DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] + @end smallexample + + By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] + first, followed by the standard Ada 95 + libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE]. + If this is not redefined, the user will obtain the DEC Ada 83 IO packages + (Text_IO, Sequential_IO, etc) + instead of the Ada95 packages. Thus, in order to get the Ada 95 + packages by default, ADA_INCLUDE_PATH must be redefined. + @end ifset + + @item + @findex ADA_PRJ_INCLUDE_FILE + Each of the directories listed in the text file whose name is given + by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^. + + @noindent + @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^ + driver when project files are used. It should not normally be set + by other means. + + @item + The content of the @file{ada_source_path} file which is part of the GNAT + installation tree and is used to store standard libraries such as the + GNAT Run Time Library (RTL) source files. + @ifclear vms + @ref{Installing an Ada Library} + @end ifclear + @end enumerate + + @noindent + Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^} + inhibits the use of the directory + containing the source file named in the command line. You can still + have this directory on your search path, but in this case it must be + explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch. + + Specifying the switch @option{-nostdinc} + inhibits the search of the default location for the GNAT Run Time + Library (RTL) source files. + + The compiler outputs its object files and ALI files in the current + working directory. + @ifclear vms + Caution: The object file can be redirected with the @option{-o} switch; + however, @code{gcc} and @code{gnat1} have not been coordinated on this + so the @file{ALI} file will not go to the right place. Therefore, you should + avoid using the @option{-o} switch. + @end ifclear + + @findex System.IO + The packages @code{Ada}, @code{System}, and @code{Interfaces} and their + children make up the GNAT RTL, together with the simple @code{System.IO} + package used in the @code{"Hello World"} example. The sources for these units + are needed by the compiler and are kept together in one directory. Not + all of the bodies are needed, but all of the sources are kept together + anyway. In a normal installation, you need not specify these directory + names when compiling or binding. Either the environment variables or + the built-in defaults cause these files to be found. + + In addition to the language-defined hierarchies (@code{System}, @code{Ada} and + @code{Interfaces}), the GNAT distribution provides a fourth hierarchy, + consisting of child units of @code{GNAT}. This is a collection of generally + useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for + further details. + + Besides simplifying access to the RTL, a major use of search paths is + in compiling sources from multiple directories. This can make + development environments much more flexible. + + + @node Order of Compilation Issues + @section Order of Compilation Issues + + @noindent + If, in our earlier example, there was a spec for the @code{hello} + procedure, it would be contained in the file @file{hello.ads}; yet this + file would not have to be explicitly compiled. This is the result of the + model we chose to implement library management. Some of the consequences + of this model are as follows: + + @itemize @bullet + @item + There is no point in compiling specs (except for package + specs with no bodies) because these are compiled as needed by clients. If + you attempt a useless compilation, you will receive an error message. + It is also useless to compile subunits because they are compiled as needed + by the parent. + + @item + There are no order of compilation requirements: performing a + compilation never obsoletes anything. The only way you can obsolete + something and require recompilations is to modify one of the + source files on which it depends. + + @item + There is no library as such, apart from the ALI files + (@pxref{The Ada Library Information Files}, for information on the format + of these files). For now we find it convenient to create separate ALI files, + but eventually the information therein may be incorporated into the object + file directly. + + @item + When you compile a unit, the source files for the specs of all units + that it @code{with}'s, all its subunits, and the bodies of any generics it + instantiates must be available (reachable by the search-paths mechanism + described above), or you will receive a fatal error message. + @end itemize + + @node Examples + @section Examples + + @noindent + The following are some typical Ada compilation command line examples: + + @table @code + @item $ gcc -c xyz.adb + Compile body in file @file{xyz.adb} with all default options. + + @ifclear vms + @item $ gcc -c -O2 -gnata xyz-def.adb + @end ifclear + @ifset vms + @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb + @end ifset + + Compile the child unit package in file @file{xyz-def.adb} with extensive + optimizations, and pragma @code{Assert}/@code{Debug} statements + enabled. + + @item $ gcc -c -gnatc abc-def.adb + Compile the subunit in file @file{abc-def.adb} in semantic-checking-only + mode. + @end table + + @node Binding Using gnatbind + @chapter Binding Using @code{gnatbind} + @findex gnatbind + + @menu + * Running gnatbind:: + * Switches for gnatbind:: + * Command-Line Access:: + * Search Paths for gnatbind:: + * Examples of gnatbind Usage:: + @end menu + + @noindent + This chapter describes the GNAT binder, @code{gnatbind}, which is used + to bind compiled GNAT objects. The @code{gnatbind} program performs + four separate functions: + + @enumerate + @item + Checks that a program is consistent, in accordance with the rules in + Chapter 10 of the Ada 95 Reference Manual. In particular, error + messages are generated if a program uses inconsistent versions of a + given unit. + + @item + Checks that an acceptable order of elaboration exists for the program + and issues an error message if it cannot find an order of elaboration + that satisfies the rules in Chapter 10 of the Ada 95 Language Manual. + + @item + Generates a main program incorporating the given elaboration order. + This program is a small Ada package (body and spec) that + must be subsequently compiled + using the GNAT compiler. The necessary compilation step is usually + performed automatically by @code{gnatlink}. The two most important + functions of this program + are to call the elaboration routines of units in an appropriate order + and to call the main program. + + @item + Determines the set of object files required by the given main program. + This information is output in the forms of comments in the generated program, + to be read by the @code{gnatlink} utility used to link the Ada application. + @end enumerate + + + @node Running gnatbind + @section Running @code{gnatbind} + + @noindent + The form of the @code{gnatbind} command is + + @smallexample + $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}] + @end smallexample + + @noindent + where @file{@i{mainprog}.adb} is the Ada file containing the main program + unit body. If no switches are specified, @code{gnatbind} constructs an Ada + package in two files whose names are + @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}. + For example, if given the + parameter @file{hello.ali}, for a main program contained in file + @file{hello.adb}, the binder output files would be @file{b~hello.ads} + and @file{b~hello.adb}. + + When doing consistency checking, the binder takes into consideration + any source files it can locate. For example, if the binder determines + that the given main program requires the package @code{Pack}, whose + @file{.ALI} + file is @file{pack.ali} and whose corresponding source spec file is + @file{pack.ads}, it attempts to locate the source file @file{pack.ads} + (using the same search path conventions as previously described for the + @code{gcc} command). If it can locate this source file, it checks that + the time stamps + or source checksums of the source and its references to in @file{ALI} files + match. In other words, any @file{ALI} files that mentions this spec must have + resulted from compiling this version of the source file (or in the case + where the source checksums match, a version close enough that the + difference does not matter). + + @cindex Source files, use by binder + The effect of this consistency checking, which includes source files, is + that the binder ensures that the program is consistent with the latest + version of the source files that can be located at bind time. Editing a + source file without compiling files that depend on the source file cause + error messages to be generated by the binder. + + For example, suppose you have a main program @file{hello.adb} and a + package @code{P}, from file @file{p.ads} and you perform the following + steps: + + @enumerate + @item + Enter @code{gcc -c hello.adb} to compile the main program. + + @item + Enter @code{gcc -c p.ads} to compile package @code{P}. + + @item + Edit file @file{p.ads}. + + @item + Enter @code{gnatbind hello}. + @end enumerate + + @noindent + At this point, the file @file{p.ali} contains an out-of-date time stamp + because the file @file{p.ads} has been edited. The attempt at binding + fails, and the binder generates the following error messages: + + @smallexample + error: "hello.adb" must be recompiled ("p.ads" has been modified) + error: "p.ads" has been modified and must be recompiled + @end smallexample + + @noindent + Now both files must be recompiled as indicated, and then the bind can + succeed, generating a main program. You need not normally be concerned + with the contents of this file, but for reference purposes a sample + binder output file is given in @ref{Example of Binder Output File}. + + In most normal usage, the default mode of @command{gnatbind} which is to + generate the main package in Ada, as described in the previous section. + In particular, this means that any Ada programmer can read and understand + the generated main program. It can also be debugged just like any other + Ada code provided the @option{^-g^/DEBUG^} switch is used for + @command{gnatbind} and @command{gnatlink}. + + However for some purposes it may be convenient to generate the main + program in C rather than Ada. This may for example be helpful when you + are generating a mixed language program with the main program in C. The + GNAT compiler itself is an example. + The use of the @option{^-C^/BIND_FILE=C^} switch + for both @code{gnatbind} and @code{gnatlink} will cause the program to + be generated in C (and compiled using the gnu C compiler). + + + @node Switches for gnatbind + @section Switches for @command{gnatbind} + + @noindent + The following switches are available with @code{gnatbind}; details will + be presented in subsequent sections. + + @menu + * Consistency-Checking Modes:: + * Binder Error Message Control:: + * Elaboration Control:: + * Output Control:: + * Binding with Non-Ada Main Programs:: + * Binding Programs with No Main Subprogram:: + @end menu + + @table @option + @c !sort! + @item ^-aO^/OBJECT_SEARCH^ + @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind}) + Specify directory to be searched for ALI files. + + @item ^-aI^/SOURCE_SEARCH^ + @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind}) + Specify directory to be searched for source file. + + @item ^-A^/BIND_FILE=ADA^ + @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind}) + Generate binder program in Ada (default) + + @item ^-b^/REPORT_ERRORS=BRIEF^ + @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind}) + Generate brief messages to @file{stderr} even if verbose mode set. + + @item ^-c^/NOOUTPUT^ + @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind}) + Check only, no generation of binder output file. + + @item ^-C^/BIND_FILE=C^ + @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind}) + Generate binder program in C + + @item ^-e^/ELABORATION_DEPENDENCIES^ + @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind}) + Output complete list of elaboration-order dependencies. + + @item ^-E^/STORE_TRACEBACKS^ + @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind}) + Store tracebacks in exception occurrences when the target supports it. + This is the default with the zero cost exception mechanism. + @ignore + @c The following may get moved to an appendix + This option is currently supported on the following targets: + all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. + @end ignore + See also the packages @code{GNAT.Traceback} and + @code{GNAT.Traceback.Symbolic} for more information. + @ifclear vms + Note that on x86 ports, you must not use @option{-fomit-frame-pointer} + @code{gcc} option. + @end ifclear vms + + @item ^-F^/FORCE_ELABS_FLAGS^ + @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind}) + Force the checks of elaboration flags. @command{gnatbind} does not normally + generate checks of elaboration flags for the main executable, except when + a Stand-Alone Library is used. However, there are cases when this cannot be + detected by gnatbind. An example is importing an interface of a Stand-Alone + Library through a pragma Import and only specifying through a linker switch + this Stand-Alone Library. This switch is used to guarantee that elaboration + flag checks are generated. + + @item ^-h^/HELP^ + @cindex @option{^-h^/HELP^} (@command{gnatbind}) + Output usage (help) information + + @item ^-I^/SEARCH^ + @cindex @option{^-I^/SEARCH^} (@command{gnatbind}) + Specify directory to be searched for source and ALI files. + + @item ^-I-^/NOCURRENT_DIRECTORY^ + @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind}) + Do not look for sources in the current directory where @code{gnatbind} was + invoked, and do not look for ALI files in the directory containing the + ALI file named in the @code{gnatbind} command line. + + @item ^-l^/ORDER_OF_ELABORATION^ + @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind}) + Output chosen elaboration order. + + @item ^-Lxxx^/BUILD_LIBRARY=xxx^ + @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind}) + Binds the units for library building. In this case the adainit and + adafinal procedures (See @pxref{Binding with Non-Ada Main Programs}) + are renamed to ^xxxinit^XXXINIT^ and + ^xxxfinal^XXXFINAL^. + Implies ^-n^/NOCOMPILE^. + @ifclear vms + (@pxref{GNAT and Libraries}, for more details.) + @end ifclear + @ifset vms + On OpenVMS, these init and final procedures are exported in uppercase + letters. For example if /BUILD_LIBRARY=toto is used, the exported name of + the init procedure will be "TOTOINIT" and the exported name of the final + procedure will be "TOTOFINAL". + @end ifset + + @item ^-Mxyz^/RENAME_MAIN=xyz^ + @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind}) + Rename generated main program from main to xyz + + @item ^-m^/ERROR_LIMIT=^@var{n} + @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind}) + Limit number of detected errors to @var{n}, where @var{n} is + in the range 1..999_999. The default value if no switch is + given is 9999. Binding is terminated if the limit is exceeded. + @ifset unw + Furthermore, under Windows, the sources pointed to by the libraries path + set in the registry are not searched for. + @end ifset + + @item ^-n^/NOMAIN^ + @cindex @option{^-n^/NOMAIN^} (@command{gnatbind}) + No main program. + + @item -nostdinc + @cindex @option{-nostdinc} (@command{gnatbind}) + Do not look for sources in the system default directory. + + @item -nostdlib + @cindex @option{-nostdlib} (@command{gnatbind}) + Do not look for library files in the system default directory. + + @item --RTS=@var{rts-path} + @cindex @option{--RTS} (@code{gnatbind}) + Specifies the default location of the runtime library. Same meaning as the + equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). + + @item ^-o ^/OUTPUT=^@var{file} + @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind}) + Name the output file @var{file} (default is @file{b~@var{xxx}.adb}). + Note that if this option is used, then linking must be done manually, + gnatlink cannot be used. + + @item ^-O^/OBJECT_LIST^ + @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind}) + Output object list. + + @item ^-p^/PESSIMISTIC_ELABORATION^ + @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind}) + Pessimistic (worst-case) elaboration order + + @item ^-s^/READ_SOURCES=ALL^ + @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind}) + Require all source files to be present. + + @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^ + @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind}) + Specifies the value to be used when detecting uninitialized scalar + objects with pragma Initialize_Scalars. + The @var{xxx} ^string specified with the switch^option^ may be either + @itemize @bullet + @item ``@option{^in^INVALID^}'' requesting an invalid value where possible + @item ``@option{^lo^LOW^}'' for the lowest possible value + possible, and the low + @item ``@option{^hi^HIGH^}'' for the highest possible value + @item ``@option{xx}'' for a value consisting of repeated bytes with the + value 16#xx# (i.e. xx is a string of two hexadecimal digits). + @end itemize + + In addition, you can specify @option{-Sev} to indicate that the value is + to be set at run time. In this case, the program will look for an environment + @cindex GNAT_INIT_SCALARS + variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one + of @option{in/lo/hi/xx} with the same meanings as above. + If no environment variable is found, or if it does not have a valid value, + then the default is @option{in} (invalid values). + + @ifclear vms + @item -static + @cindex @option{-static} (@code{gnatbind}) + Link against a static GNAT run time. + + @item -shared + @cindex @option{-shared} (@code{gnatbind}) + Link against a shared GNAT run time when available. + @end ifclear + + @item ^-t^/NOTIME_STAMP_CHECK^ + @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind}) + Tolerate time stamp and other consistency errors + + @item ^-T@var{n}^/TIME_SLICE=@var{n}^ + @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind}) + Set the time slice value to @var{n} milliseconds. If the system supports + the specification of a specific time slice value, then the indicated value + is used. If the system does not support specific time slice values, but + does support some general notion of round-robin scheduling, then any + non-zero value will activate round-robin scheduling. + + A value of zero is treated specially. It turns off time + slicing, and in addition, indicates to the tasking run time that the + semantics should match as closely as possible the Annex D + requirements of the Ada RM, and in particular sets the default + scheduling policy to @code{FIFO_Within_Priorities}. + + @item ^-v^/REPORT_ERRORS=VERBOSE^ + @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind}) + Verbose mode. Write error messages, header, summary output to + @file{stdout}. + + @ifclear vms + @item -w@var{x} + @cindex @option{-w} (@code{gnatbind}) + Warning mode (@var{x}=s/e for suppress/treat as error) + @end ifclear + + @ifset vms + @item /WARNINGS=NORMAL + @cindex @option{/WARNINGS} (@code{gnatbind}) + Normal warnings mode. Warnings are issued but ignored + + @item /WARNINGS=SUPPRESS + @cindex @option{/WARNINGS} (@code{gnatbind}) + All warning messages are suppressed + + @item /WARNINGS=ERROR + @cindex @option{/WARNINGS} (@code{gnatbind}) + Warning messages are treated as fatal errors + @end ifset + + @item ^-x^/READ_SOURCES=NONE^ + @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind}) + Exclude source files (check object consistency only). + + @ifset vms + @item /READ_SOURCES=AVAILABLE + @cindex @option{/READ_SOURCES} (@code{gnatbind}) + Default mode, in which sources are checked for consistency only if + they are available. + @end ifset + + @item ^-z^/ZERO_MAIN^ + @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind}) + No main subprogram. + @end table + + @ifclear vms + @noindent + You may obtain this listing of switches by running @code{gnatbind} with + no arguments. + @end ifclear + + + @node Consistency-Checking Modes + @subsection Consistency-Checking Modes + + @noindent + As described earlier, by default @code{gnatbind} checks + that object files are consistent with one another and are consistent + with any source files it can locate. The following switches control binder + access to sources. + + @table @option + @c !sort! + @item ^-s^/READ_SOURCES=ALL^ + @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind}) + Require source files to be present. In this mode, the binder must be + able to locate all source files that are referenced, in order to check + their consistency. In normal mode, if a source file cannot be located it + is simply ignored. If you specify this switch, a missing source + file is an error. + + @item ^-x^/READ_SOURCES=NONE^ + @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind}) + Exclude source files. In this mode, the binder only checks that ALI + files are consistent with one another. Source files are not accessed. + The binder runs faster in this mode, and there is still a guarantee that + the resulting program is self-consistent. + If a source file has been edited since it was last compiled, and you + specify this switch, the binder will not detect that the object + file is out of date with respect to the source file. Note that this is the + mode that is automatically used by @code{gnatmake} because in this + case the checking against sources has already been performed by + @code{gnatmake} in the course of compilation (i.e. before binding). + + @ifset vms + @item /READ_SOURCES=AVAILABLE + @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind}) + This is the default mode in which source files are checked if they are + available, and ignored if they are not available. + @end ifset + @end table + + @node Binder Error Message Control + @subsection Binder Error Message Control + + @noindent + The following switches provide control over the generation of error + messages from the binder: + + @table @option + @c !sort! + @item ^-v^/REPORT_ERRORS=VERBOSE^ + @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind}) + Verbose mode. In the normal mode, brief error messages are generated to + @file{stderr}. If this switch is present, a header is written + to @file{stdout} and any error messages are directed to @file{stdout}. + All that is written to @file{stderr} is a brief summary message. + + @item ^-b^/REPORT_ERRORS=BRIEF^ + @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind}) + Generate brief error messages to @file{stderr} even if verbose mode is + specified. This is relevant only when used with the + @option{^-v^/REPORT_ERRORS=VERBOSE^} switch. + + @ifclear vms + @item -m@var{n} + @cindex @option{-m} (@code{gnatbind}) + Limits the number of error messages to @var{n}, a decimal integer in the + range 1-999. The binder terminates immediately if this limit is reached. + + @item -M@var{xxx} + @cindex @option{-M} (@code{gnatbind}) + Renames the generated main program from @code{main} to @code{xxx}. + This is useful in the case of some cross-building environments, where + the actual main program is separate from the one generated + by @code{gnatbind}. + @end ifclear + + @item ^-ws^/WARNINGS=SUPPRESS^ + @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind}) + @cindex Warnings + Suppress all warning messages. + + @item ^-we^/WARNINGS=ERROR^ + @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind}) + Treat any warning messages as fatal errors. + + @ifset vms + @item /WARNINGS=NORMAL + Standard mode with warnings generated, but warnings do not get treated + as errors. + @end ifset + + @item ^-t^/NOTIME_STAMP_CHECK^ + @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind}) + @cindex Time stamp checks, in binder + @cindex Binder consistency checks + @cindex Consistency checks, in binder + The binder performs a number of consistency checks including: + + @itemize @bullet + @item + Check that time stamps of a given source unit are consistent + @item + Check that checksums of a given source unit are consistent + @item + Check that consistent versions of @code{GNAT} were used for compilation + @item + Check consistency of configuration pragmas as required + @end itemize + + @noindent + Normally failure of such checks, in accordance with the consistency + requirements of the Ada Reference Manual, causes error messages to be + generated which abort the binder and prevent the output of a binder + file and subsequent link to obtain an executable. + + The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages + into warnings, so that + binding and linking can continue to completion even in the presence of such + errors. The result may be a failed link (due to missing symbols), or a + non-functional executable which has undefined semantics. + @emph{This means that + @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations, + with extreme care.} + @end table + + @node Elaboration Control + @subsection Elaboration Control + + @noindent + The following switches provide additional control over the elaboration + order. For full details see @xref{Elaboration Order Handling in GNAT}. + + @table @option + @item ^-p^/PESSIMISTIC_ELABORATION^ + @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind}) + Normally the binder attempts to choose an elaboration order that is + likely to minimize the likelihood of an elaboration order error resulting + in raising a @code{Program_Error} exception. This switch reverses the + action of the binder, and requests that it deliberately choose an order + that is likely to maximize the likelihood of an elaboration error. + This is useful in ensuring portability and avoiding dependence on + accidental fortuitous elaboration ordering. + + Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^} + switch if dynamic + elaboration checking is used (@option{-gnatE} switch used for compilation). + This is because in the default static elaboration mode, all necessary + @code{Elaborate_All} pragmas are implicitly inserted. + These implicit pragmas are still respected by the binder in + @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a + safe elaboration order is assured. + @end table + + @node Output Control + @subsection Output Control + + @noindent + The following switches allow additional control over the output + generated by the binder. + + @table @option + @c !sort! + + @item ^-A^/BIND_FILE=ADA^ + @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind}) + Generate binder program in Ada (default). The binder program is named + @file{b~@var{mainprog}.adb} by default. This can be changed with + @option{^-o^/OUTPUT^} @code{gnatbind} option. + + @item ^-c^/NOOUTPUT^ + @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind}) + Check only. Do not generate the binder output file. In this mode the + binder performs all error checks but does not generate an output file. + + @item ^-C^/BIND_FILE=C^ + @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind}) + Generate binder program in C. The binder program is named + @file{b_@var{mainprog}.c}. + This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind} + option. + + @item ^-e^/ELABORATION_DEPENDENCIES^ + @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind}) + Output complete list of elaboration-order dependencies, showing the + reason for each dependency. This output can be rather extensive but may + be useful in diagnosing problems with elaboration order. The output is + written to @file{stdout}. + + @item ^-h^/HELP^ + @cindex @option{^-h^/HELP^} (@code{gnatbind}) + Output usage information. The output is written to @file{stdout}. + + @item ^-K^/LINKER_OPTION_LIST^ + @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind}) + Output linker options to @file{stdout}. Includes library search paths, + contents of pragmas Ident and Linker_Options, and libraries added + by @code{gnatbind}. + + @item ^-l^/ORDER_OF_ELABORATION^ + @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind}) + Output chosen elaboration order. The output is written to @file{stdout}. + + @item ^-O^/OBJECT_LIST^ + @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind}) + Output full names of all the object files that must be linked to provide + the Ada component of the program. The output is written to @file{stdout}. + This list includes the files explicitly supplied and referenced by the user + as well as implicitly referenced run-time unit files. The latter are + omitted if the corresponding units reside in shared libraries. The + directory names for the run-time units depend on the system configuration. + + @item ^-o ^/OUTPUT=^@var{file} + @cindex @option{^-o^/OUTPUT^} (@code{gnatbind}) + Set name of output file to @var{file} instead of the normal + @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada + binder generated body filename. In C mode you would normally give + @var{file} an extension of @file{.c} because it will be a C source program. + Note that if this option is used, then linking must be done manually. + It is not possible to use gnatlink in this case, since it cannot locate + the binder file. + + @item ^-r^/RESTRICTION_LIST^ + @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind}) + Generate list of @code{pragma Restrictions} that could be applied to + the current unit. This is useful for code audit purposes, and also may + be used to improve code generation in some cases. + + @end table + + @node Binding with Non-Ada Main Programs + @subsection Binding with Non-Ada Main Programs + + @noindent + In our description so far we have assumed that the main + program is in Ada, and that the task of the binder is to generate a + corresponding function @code{main} that invokes this Ada main + program. GNAT also supports the building of executable programs where + the main program is not in Ada, but some of the called routines are + written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). + The following switch is used in this situation: + + @table @option + @item ^-n^/NOMAIN^ + @cindex @option{^-n^/NOMAIN^} (@code{gnatbind}) + No main program. The main program is not in Ada. + @end table + + @noindent + In this case, most of the functions of the binder are still required, + but instead of generating a main program, the binder generates a file + containing the following callable routines: + + @table @code + @item adainit + @findex adainit + You must call this routine to initialize the Ada part of the program by + calling the necessary elaboration routines. A call to @code{adainit} is + required before the first call to an Ada subprogram. + + Note that it is assumed that the basic execution environment must be setup + to be appropriate for Ada execution at the point where the first Ada + subprogram is called. In particular, if the Ada code will do any + floating-point operations, then the FPU must be setup in an appropriate + manner. For the case of the x86, for example, full precision mode is + required. The procedure GNAT.Float_Control.Reset may be used to ensure + that the FPU is in the right state. + + @item adafinal + @findex adafinal + You must call this routine to perform any library-level finalization + required by the Ada subprograms. A call to @code{adafinal} is required + after the last call to an Ada subprogram, and before the program + terminates. + @end table + + @noindent + If the @option{^-n^/NOMAIN^} switch + @cindex @option{^-n^/NOMAIN^} (@command{gnatbind}) + @cindex Binder, multiple input files + is given, more than one ALI file may appear on + the command line for @code{gnatbind}. The normal @dfn{closure} + calculation is performed for each of the specified units. Calculating + the closure means finding out the set of units involved by tracing + @code{with} references. The reason it is necessary to be able to + specify more than one ALI file is that a given program may invoke two or + more quite separate groups of Ada units. + + The binder takes the name of its output file from the last specified ALI + file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}. + @cindex @option{^-o^/OUTPUT^} (@command{gnatbind}) + The output is an Ada unit in source form that can + be compiled with GNAT unless the -C switch is used in which case the + output is a C source file, which must be compiled using the C compiler. + This compilation occurs automatically as part of the @code{gnatlink} + processing. + + Currently the GNAT run time requires a FPU using 80 bits mode + precision. Under targets where this is not the default it is required to + call GNAT.Float_Control.Reset before using floating point numbers (this + include float computation, float input and output) in the Ada code. A + side effect is that this could be the wrong mode for the foreign code + where floating point computation could be broken after this call. + + @node Binding Programs with No Main Subprogram + @subsection Binding Programs with No Main Subprogram + + @noindent + It is possible to have an Ada program which does not have a main + subprogram. This program will call the elaboration routines of all the + packages, then the finalization routines. + + The following switch is used to bind programs organized in this manner: + + @table @option + @item ^-z^/ZERO_MAIN^ + @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind}) + Normally the binder checks that the unit name given on the command line + corresponds to a suitable main subprogram. When this switch is used, + a list of ALI files can be given, and the execution of the program + consists of elaboration of these units in an appropriate order. + @end table + + + @node Command-Line Access + @section Command-Line Access + + @noindent + The package @code{Ada.Command_Line} provides access to the command-line + arguments and program name. In order for this interface to operate + correctly, the two variables + + @smallexample + @group + int gnat_argc; + char **gnat_argv; + @end group + @end smallexample + + @noindent + @findex gnat_argv + @findex gnat_argc + are declared in one of the GNAT library routines. These variables must + be set from the actual @code{argc} and @code{argv} values passed to the + main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind} + generates the C main program to automatically set these variables. + If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to + set these variables. If they are not set, the procedures in + @code{Ada.Command_Line} will not be available, and any attempt to use + them will raise @code{Constraint_Error}. If command line access is + required, your main program must set @code{gnat_argc} and + @code{gnat_argv} from the @code{argc} and @code{argv} values passed to + it. + + + @node Search Paths for gnatbind + @section Search Paths for @code{gnatbind} + + @noindent + The binder takes the name of an ALI file as its argument and needs to + locate source files as well as other ALI files to verify object consistency. + + For source files, it follows exactly the same search rules as @code{gcc} + (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the + directories searched are: + + @enumerate + @item + The directory containing the ALI file named in the command line, unless + the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified. + + @item + All directories specified by @option{^-I^/SEARCH^} + switches on the @code{gnatbind} + command line, in the order given. + + @item + @findex ADA_OBJECTS_PATH + Each of the directories listed in the value of the + @code{ADA_OBJECTS_PATH} ^environment variable^logical name^. + @ifset unw + Construct this value + exactly as the @code{PATH} environment variable: a list of directory + names separated by colons (semicolons when working with the NT version + of GNAT). + @end ifset + @ifset vms + Normally, define this value as a logical name containing a comma separated + list of directory names. + + This variable can also be defined by means of an environment string + (an argument to the DEC C exec* set of functions). + + Logical Name: + @smallexample + DEFINE ANOTHER_PATH FOO:[BAG] + DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] + @end smallexample + + By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] + first, followed by the standard Ada 95 + libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB]. + If this is not redefined, the user will obtain the DEC Ada 83 IO packages + (Text_IO, Sequential_IO, etc) + instead of the Ada95 packages. Thus, in order to get the Ada 95 + packages by default, ADA_OBJECTS_PATH must be redefined. + @end ifset + + @item + @findex ADA_PRJ_OBJECTS_FILE + Each of the directories listed in the text file whose name is given + by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^. + + @noindent + @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^ + driver when project files are used. It should not normally be set + by other means. + + @item + The content of the @file{ada_object_path} file which is part of the GNAT + installation tree and is used to store standard libraries such as the + GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is + specified. + @ifclear vms + @ref{Installing an Ada Library} + @end ifclear + @end enumerate + + @noindent + In the binder the switch @option{^-I^/SEARCH^} + @cindex @option{^-I^/SEARCH^} (@command{gnatbind}) + is used to specify both source and + library file paths. Use @option{^-aI^/SOURCE_SEARCH^} + @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind}) + instead if you want to specify + source paths only, and @option{^-aO^/LIBRARY_SEARCH^} + @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind}) + if you want to specify library paths + only. This means that for the binder + @option{^-I^/SEARCH=^}@var{dir} is equivalent to + @option{^-aI^/SOURCE_SEARCH=^}@var{dir} + @option{^-aO^/OBJECT_SEARCH=^}@var{dir}. + The binder generates the bind file (a C language source file) in the + current working directory. + + @findex Ada + @findex System + @findex Interfaces + @findex GNAT + The packages @code{Ada}, @code{System}, and @code{Interfaces} and their + children make up the GNAT Run-Time Library, together with the package + GNAT and its children, which contain a set of useful additional + library functions provided by GNAT. The sources for these units are + needed by the compiler and are kept together in one directory. The ALI + files and object files generated by compiling the RTL are needed by the + binder and the linker and are kept together in one directory, typically + different from the directory containing the sources. In a normal + installation, you need not specify these directory names when compiling + or binding. Either the environment variables or the built-in defaults + cause these files to be found. + + Besides simplifying access to the RTL, a major use of search paths is + in compiling sources from multiple directories. This can make + development environments much more flexible. + + @node Examples of gnatbind Usage + @section Examples of @code{gnatbind} Usage + + @noindent + This section contains a number of examples of using the GNAT binding + utility @code{gnatbind}. + + @table @code + @item gnatbind hello + The main program @code{Hello} (source program in @file{hello.adb}) is + bound using the standard switch settings. The generated main program is + @file{b~hello.adb}. This is the normal, default use of the binder. + + @ifclear vms + @item gnatbind hello -o mainprog.adb + @end ifclear + @ifset vms + @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB + @end ifset + The main program @code{Hello} (source program in @file{hello.adb}) is + bound using the standard switch settings. The generated main program is + @file{mainprog.adb} with the associated spec in + @file{mainprog.ads}. Note that you must specify the body here not the + spec, in the case where the output is in Ada. Note that if this option + is used, then linking must be done manually, since gnatlink will not + be able to find the generated file. + + @ifclear vms + @item gnatbind main -C -o mainprog.c -x + @end ifclear + @ifset vms + @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE + @end ifset + The main program @code{Main} (source program in + @file{main.adb}) is bound, excluding source files from the + consistency checking, generating + the file @file{mainprog.c}. + + @ifclear vms + @item gnatbind -x main_program -C -o mainprog.c + This command is exactly the same as the previous example. Switches may + appear anywhere in the command line, and single letter switches may be + combined into a single switch. + @end ifclear + + @ifclear vms + @item gnatbind -n math dbase -C -o ada-control.c + @end ifclear + @ifset vms + @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c + @end ifset + The main program is in a language other than Ada, but calls to + subprograms in packages @code{Math} and @code{Dbase} appear. This call + to @code{gnatbind} generates the file @file{ada-control.c} containing + the @code{adainit} and @code{adafinal} routines to be called before and + after accessing the Ada units. + @end table + + + @c ------------------------------------ + @node Linking Using gnatlink + @chapter Linking Using @code{gnatlink} + @c ------------------------------------ + @findex gnatlink + + @noindent + This chapter discusses @code{gnatlink}, a tool that links + an Ada program and builds an executable file. This utility + invokes the system linker ^(via the @code{gcc} command)^^ + with a correct list of object files and library references. + @code{gnatlink} automatically determines the list of files and + references for the Ada part of a program. It uses the binder file + generated by the @command{gnatbind} to determine this list. + + @menu + * Running gnatlink:: + * Switches for gnatlink:: + * Setting Stack Size from gnatlink:: + * Setting Heap Size from gnatlink:: + @end menu + + @node Running gnatlink + @section Running @code{gnatlink} + + @noindent + The form of the @code{gnatlink} command is + + @smallexample + $ gnatlink [@var{switches}] @var{mainprog}[.ali] + [@var{non-Ada objects}] [@var{linker options}] + @end smallexample + + @noindent + The arguments of @code{gnatlink} (switches, main @file{ALI} file, + non-Ada objects + or linker options) may be in any order, provided that no non-Ada object may + be mistaken for a main @file{ALI} file. + Any file name @file{F} without the @file{.ali} + extension will be taken as the main @file{ALI} file if a file exists + whose name is the concatenation of @file{F} and @file{.ali}. + + @noindent + @file{@var{mainprog}.ali} references the ALI file of the main program. + The @file{.ali} extension of this file can be omitted. From this + reference, @code{gnatlink} locates the corresponding binder file + @file{b~@var{mainprog}.adb} and, using the information in this file along + with the list of non-Ada objects and linker options, constructs a + linker command file to create the executable. + + The arguments other than the @code{gnatlink} switches and the main @file{ALI} + file are passed to the linker uninterpreted. + They typically include the names of + object files for units written in other languages than Ada and any library + references required to resolve references in any of these foreign language + units, or in @code{Import} pragmas in any Ada units. + + @var{linker options} is an optional list of linker specific + switches. + The default linker called by gnatlink is @var{gcc} which in + turn calls the appropriate system linker. + Standard options for the linker such as @option{-lmy_lib} or + @option{-Ldir} can be added as is. + For options that are not recognized by + @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or + @option{-Wl,}. + Refer to the GCC documentation for + details. Here is an example showing how to generate a linker map: + + @ifclear vms + @smallexample + $ gnatlink my_prog -Wl,-Map,MAPFILE + @end smallexample + @end ifclear + + @ifset vms + <> + @end ifset + + Using @var{linker options} it is possible to set the program stack and + heap size. See @ref{Setting Stack Size from gnatlink}, and + @ref{Setting Heap Size from gnatlink}. + + @code{gnatlink} determines the list of objects required by the Ada + program and prepends them to the list of objects passed to the linker. + @code{gnatlink} also gathers any arguments set by the use of + @code{pragma Linker_Options} and adds them to the list of arguments + presented to the linker. + + @ifset vms + @code{gnatlink} accepts the following types of extra files on the command + line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and + options files (.OPT). These are recognized and handled according to their + extension. + @end ifset + + @node Switches for gnatlink + @section Switches for @code{gnatlink} + + @noindent + The following switches are available with the @code{gnatlink} utility: + + @table @option + @c !sort! + + @item ^-A^/BIND_FILE=ADA^ + @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink}) + The binder has generated code in Ada. This is the default. + + @item ^-C^/BIND_FILE=C^ + @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink}) + If instead of generating a file in Ada, the binder has generated one in + C, then the linker needs to know about it. Use this switch to signal + to @code{gnatlink} that the binder has generated C code rather than + Ada code. + + @item ^-f^/FORCE_OBJECT_FILE_LIST^ + @cindex Command line length + @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink}) + On some targets, the command line length is limited, and @code{gnatlink} + will generate a separate file for the linker if the list of object files + is too long. + The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file + to be generated even if + the limit is not exceeded. This is useful in some cases to deal with + special situations where the command line length is exceeded. + + @item ^-g^/DEBUG^ + @cindex Debugging information, including + @cindex @option{^-g^/DEBUG^} (@code{gnatlink}) + The option to include debugging information causes the Ada bind file (in + other words, @file{b~@var{mainprog}.adb}) to be compiled with + @option{^-g^/DEBUG^}. + In addition, the binder does not delete the @file{b~@var{mainprog}.adb}, + @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files. + Without @option{^-g^/DEBUG^}, the binder removes these files by + default. The same procedure apply if a C bind file was generated using + @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames + are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}. + + @item ^-n^/NOCOMPILE^ + @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink}) + Do not compile the file generated by the binder. This may be used when + a link is rerun with different options, but there is no need to recompile + the binder file. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@code{gnatlink}) + Causes additional information to be output, including a full list of the + included object files. This switch option is most useful when you want + to see what set of object files are being used in the link step. + + @item ^-v -v^/VERBOSE/VERBOSE^ + @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink}) + Very verbose mode. Requests that the compiler operate in verbose mode when + it compiles the binder file, and that the system linker run in verbose mode. + + @item ^-o ^/EXECUTABLE=^@var{exec-name} + @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink}) + @var{exec-name} specifies an alternate name for the generated + executable program. If this switch is omitted, the executable has the same + name as the main unit. For example, @code{gnatlink try.ali} creates + an executable called @file{^try^TRY.EXE^}. + + @ifclear vms + @item -b @var{target} + @cindex @option{-b} (@code{gnatlink}) + Compile your program to run on @var{target}, which is the name of a + system configuration. You must have a GNAT cross-compiler built if + @var{target} is not the same as your host system. + + @item -B@var{dir} + @cindex @option{-B} (@code{gnatlink}) + Load compiler executables (for example, @code{gnat1}, the Ada compiler) + from @var{dir} instead of the default location. Only use this switch + when multiple versions of the GNAT compiler are available. See the + @code{gcc} manual page for further details. You would normally use the + @option{-b} or @option{-V} switch instead. + + @item --GCC=@var{compiler_name} + @cindex @option{--GCC=compiler_name} (@code{gnatlink}) + Program used for compiling the binder file. The default is + `@code{gcc}'. You need to use quotes around @var{compiler_name} if + @code{compiler_name} contains spaces or other separator characters. As + an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use + @code{foo -x -y} as your compiler. Note that switch @option{-c} is always + inserted after your command name. Thus in the above example the compiler + command that will be used by @code{gnatlink} will be @code{foo -c -x -y}. + If several @option{--GCC=compiler_name} are used, only the last + @var{compiler_name} is taken into account. However, all the additional + switches are also taken into account. Thus, + @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to + @option{--GCC="bar -x -y -z -t"}. + + @item --LINK=@var{name} + @cindex @option{--LINK=} (@code{gnatlink}) + @var{name} is the name of the linker to be invoked. This is especially + useful in mixed language programs since languages such as C++ require + their own linker to be used. When this switch is omitted, the default + name for the linker is (@file{gcc}). When this switch is used, the + specified linker is called instead of (@file{gcc}) with exactly the same + parameters that would have been passed to (@file{gcc}) so if the desired + linker requires different parameters it is necessary to use a wrapper + script that massages the parameters before invoking the real linker. It + may be useful to control the exact invocation by using the verbose + switch. + + @end ifclear + + @ifset vms + @item /DEBUG=TRACEBACK + @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink}) + This qualifier causes sufficient information to be included in the + executable file to allow a traceback, but does not include the full + symbol information needed by the debugger. + + @item /IDENTIFICATION="" + @code{""} specifies the string to be stored in the image file + identification field in the image header. + It overrides any pragma @code{Ident} specified string. + + @item /NOINHIBIT-EXEC + Generate the executable file even if there are linker warnings. + + @item /NOSTART_FILES + Don't link in the object file containing the ``main'' transfer address. + Used when linking with a foreign language main program compiled with a + Digital compiler. + + @item /STATIC + Prefer linking with object libraries over sharable images, even without + /DEBUG. + @end ifset + + @end table + + @node Setting Stack Size from gnatlink + @section Setting Stack Size from @code{gnatlink} + + @noindent + Under Windows systems, it is possible to specify the program stack size from + @code{gnatlink} using either: + + @itemize @bullet + + @item using @option{-Xlinker} linker option + + @smallexample + $ gnatlink hello -Xlinker --stack=0x10000,0x1000 + @end smallexample + + This sets the stack reserve size to 0x10000 bytes and the stack commit + size to 0x1000 bytes. + + @item using @option{-Wl} linker option + + @smallexample + $ gnatlink hello -Wl,--stack=0x1000000 + @end smallexample + + This sets the stack reserve size to 0x1000000 bytes. Note that with + @option{-Wl} option it is not possible to set the stack commit size + because the coma is a separator for this option. + + @end itemize + + @node Setting Heap Size from gnatlink + @section Setting Heap Size from @code{gnatlink} + + @noindent + Under Windows systems, it is possible to specify the program heap size from + @code{gnatlink} using either: + + @itemize @bullet + + @item using @option{-Xlinker} linker option + + @smallexample + $ gnatlink hello -Xlinker --heap=0x10000,0x1000 + @end smallexample + + This sets the heap reserve size to 0x10000 bytes and the heap commit + size to 0x1000 bytes. + + @item using @option{-Wl} linker option + + @smallexample + $ gnatlink hello -Wl,--heap=0x1000000 + @end smallexample + + This sets the heap reserve size to 0x1000000 bytes. Note that with + @option{-Wl} option it is not possible to set the heap commit size + because the coma is a separator for this option. + + @end itemize + + @node The GNAT Make Program gnatmake + @chapter The GNAT Make Program @code{gnatmake} + @findex gnatmake + + @menu + * Running gnatmake:: + * Switches for gnatmake:: + * Mode Switches for gnatmake:: + * Notes on the Command Line:: + * How gnatmake Works:: + * Examples of gnatmake Usage:: + @end menu + @noindent + A typical development cycle when working on an Ada program consists of + the following steps: + + @enumerate + @item + Edit some sources to fix bugs. + + @item + Add enhancements. + + @item + Compile all sources affected. + + @item + Rebind and relink. + + @item + Test. + @end enumerate + + @noindent + The third step can be tricky, because not only do the modified files + @cindex Dependency rules + have to be compiled, but any files depending on these files must also be + recompiled. The dependency rules in Ada can be quite complex, especially + in the presence of overloading, @code{use} clauses, generics and inlined + subprograms. + + @code{gnatmake} automatically takes care of the third and fourth steps + of this process. It determines which sources need to be compiled, + compiles them, and binds and links the resulting object files. + + Unlike some other Ada make programs, the dependencies are always + accurately recomputed from the new sources. The source based approach of + the GNAT compilation model makes this possible. This means that if + changes to the source program cause corresponding changes in + dependencies, they will always be tracked exactly correctly by + @code{gnatmake}. + + @node Running gnatmake + @section Running @code{gnatmake} + + @noindent + The usual form of the @code{gnatmake} command is + + @smallexample + $ gnatmake [@var{switches}] @var{file_name} + [@var{file_names}] [@var{mode_switches}] + @end smallexample + + @noindent + The only required argument is one @var{file_name}, which specifies + a compilation unit that is a main program. Several @var{file_names} can be + specified: this will result in several executables being built. + If @code{switches} are present, they can be placed before the first + @var{file_name}, between @var{file_names} or after the last @var{file_name}. + If @var{mode_switches} are present, they must always be placed after + the last @var{file_name} and all @code{switches}. + + If you are using standard file extensions (.adb and .ads), then the + extension may be omitted from the @var{file_name} arguments. However, if + you are using non-standard extensions, then it is required that the + extension be given. A relative or absolute directory path can be + specified in a @var{file_name}, in which case, the input source file will + be searched for in the specified directory only. Otherwise, the input + source file will first be searched in the directory where + @code{gnatmake} was invoked and if it is not found, it will be search on + the source path of the compiler as described in + @ref{Search Paths and the Run-Time Library (RTL)}. + + All @code{gnatmake} output (except when you specify + @option{^-M^/DEPENDENCIES_LIST^}) is to + @file{stderr}. The output produced by the + @option{^-M^/DEPENDENCIES_LIST^} switch is send to + @file{stdout}. + + @node Switches for gnatmake + @section Switches for @code{gnatmake} + + @noindent + You may specify any of the following switches to @code{gnatmake}: + + @table @option + @c !sort! + @ifclear vms + @item --GCC=@var{compiler_name} + @cindex @option{--GCC=compiler_name} (@code{gnatmake}) + Program used for compiling. The default is `@code{gcc}'. You need to use + quotes around @var{compiler_name} if @code{compiler_name} contains + spaces or other separator characters. As an example @option{--GCC="foo -x + -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your + compiler. Note that switch @option{-c} is always inserted after your + command name. Thus in the above example the compiler command that will + be used by @code{gnatmake} will be @code{foo -c -x -y}. + If several @option{--GCC=compiler_name} are used, only the last + @var{compiler_name} is taken into account. However, all the additional + switches are also taken into account. Thus, + @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to + @option{--GCC="bar -x -y -z -t"}. + + @item --GNATBIND=@var{binder_name} + @cindex @option{--GNATBIND=binder_name} (@code{gnatmake}) + Program used for binding. The default is `@code{gnatbind}'. You need to + use quotes around @var{binder_name} if @var{binder_name} contains spaces + or other separator characters. As an example @option{--GNATBIND="bar -x + -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your + binder. Binder switches that are normally appended by @code{gnatmake} to + `@code{gnatbind}' are now appended to the end of @code{bar -x -y}. + + @item --GNATLINK=@var{linker_name} + @cindex @option{--GNATLINK=linker_name} (@code{gnatmake}) + Program used for linking. The default is `@code{gnatlink}'. You need to + use quotes around @var{linker_name} if @var{linker_name} contains spaces + or other separator characters. As an example @option{--GNATLINK="lan -x + -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your + linker. Linker switches that are normally appended by @code{gnatmake} to + `@code{gnatlink}' are now appended to the end of @code{lan -x -y}. + + @end ifclear + + @item ^-a^/ALL_FILES^ + @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake}) + Consider all files in the make process, even the GNAT internal system + files (for example, the predefined Ada library files), as well as any + locked files. Locked files are files whose ALI file is write-protected. + By default, + @code{gnatmake} does not check these files, + because the assumption is that the GNAT internal files are properly up + to date, and also that any write protected ALI files have been properly + installed. Note that if there is an installation problem, such that one + of these files is not up to date, it will be properly caught by the + binder. + You may have to specify this switch if you are working on GNAT + itself. The switch @option{^-a^/ALL_FILES^} is also useful + in conjunction with @option{^-f^/FORCE_COMPILE^} + if you need to recompile an entire application, + including run-time files, using special configuration pragmas, + such as a @code{Normalize_Scalars} pragma. + + By default + @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT + internal files with + @ifclear vms + @code{gcc -c -gnatpg} rather than @code{gcc -c}. + @end ifclear + @ifset vms + the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch. + @end ifset + + @item ^-b^/ACTIONS=BIND^ + @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake}) + Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do + compilation and binding, but no link. + Can be combined with @option{^-l^/ACTIONS=LINK^} + to do binding and linking. When not combined with + @option{^-c^/ACTIONS=COMPILE^} + all the units in the closure of the main program must have been previously + compiled and must be up to date. The root unit specified by @var{file_name} + may be given without extension, with the source extension or, if no GNAT + Project File is specified, with the ALI file extension. + + @item ^-c^/ACTIONS=COMPILE^ + @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake}) + Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^} + is also specified. Do not perform linking, except if both + @option{^-b^/ACTIONS=BIND^} and + @option{^-l^/ACTIONS=LINK^} are also specified. + If the root unit specified by @var{file_name} is not a main unit, this is the + default. Otherwise @code{gnatmake} will attempt binding and linking + unless all objects are up to date and the executable is more recent than + the objects. + + @item ^-C^/MAPPING^ + @cindex @option{^-C^/MAPPING^} (@code{gnatmake}) + Use a temporary mapping file. A mapping file is a way to communicate to the + compiler two mappings: from unit names to file names (without any directory + information) and from file names to path names (with full directory + information). These mappings are used by the compiler to short-circuit the path + search. When @code{gnatmake} is invoked with this switch, it will create + a temporary mapping file, initially populated by the project manager, + if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty. + Each invocation of the compiler will add the newly accessed sources to the + mapping file. This will improve the source search during the next invocation + of the compiler. + + @item ^-C=^/USE_MAPPING_FILE=^@var{file} + @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake}) + Use a specific mapping file. The file, specified as a path name (absolute or + relative) by this switch, should already exist, otherwise the switch is + ineffective. The specified mapping file will be communicated to the compiler. + This switch is not compatible with a project file + (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes + (^-j^/PROCESSES=^nnn, when nnn is greater than 1). + + @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir} + @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake}) + Put all object files and ALI file in directory @var{dir}. + If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files + and ALI files go in the current working directory. + + This switch cannot be used when using a project file. + + @item ^-f^/FORCE_COMPILE^ + @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake}) + Force recompilations. Recompile all sources, even though some object + files may be up to date, but don't recompile predefined or GNAT internal + files or locked files (files with a write-protected ALI file), + unless the @option{^-a^/ALL_FILES^} switch is also specified. + + @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^ + @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake}) + When using project files, if some errors or warnings are detected during + parsing and verbose mode is not in effect (no use of switch + ^-v^/VERBOSE^), then error lines start with the full path name of the project + file, rather than its simple file name. + + @item ^-i^/IN_PLACE^ + @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake}) + In normal mode, @code{gnatmake} compiles all object files and ALI files + into the current directory. If the @option{^-i^/IN_PLACE^} switch is used, + then instead object files and ALI files that already exist are overwritten + in place. This means that once a large project is organized into separate + directories in the desired manner, then @code{gnatmake} will automatically + maintain and update this organization. If no ALI files are found on the + Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), + the new object and ALI files are created in the + directory containing the source being compiled. If another organization + is desired, where objects and sources are kept in different directories, + a useful technique is to create dummy ALI files in the desired directories. + When detecting such a dummy file, @code{gnatmake} will be forced to recompile + the corresponding source file, and it will be put the resulting object + and ALI files in the directory where it found the dummy file. + + @item ^-j^/PROCESSES=^@var{n} + @cindex @option{^-j^/PROCESSES^} (@code{gnatmake}) + @cindex Parallel make + Use @var{n} processes to carry out the (re)compilations. On a + multiprocessor machine compilations will occur in parallel. In the + event of compilation errors, messages from various compilations might + get interspersed (but @code{gnatmake} will give you the full ordered + list of failing compiles at the end). If this is problematic, rerun + the make process with n set to 1 to get a clean list of messages. + + @item ^-k^/CONTINUE_ON_ERROR^ + @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake}) + Keep going. Continue as much as possible after a compilation error. To + ease the programmer's task in case of compilation errors, the list of + sources for which the compile fails is given when @code{gnatmake} + terminates. + + If @code{gnatmake} is invoked with several @file{file_names} and with this + switch, if there are compilation errors when building an executable, + @code{gnatmake} will not attempt to build the following executables. + + @item ^-l^/ACTIONS=LINK^ + @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake}) + Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding + and linking. Linking will not be performed if combined with + @option{^-c^/ACTIONS=COMPILE^} + but not with @option{^-b^/ACTIONS=BIND^}. + When not combined with @option{^-b^/ACTIONS=BIND^} + all the units in the closure of the main program must have been previously + compiled and must be up to date, and the main program need to have been bound. + The root unit specified by @var{file_name} + may be given without extension, with the source extension or, if no GNAT + Project File is specified, with the ALI file extension. + + @item ^-m^/MINIMAL_RECOMPILATION^ + @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake}) + Specifies that the minimum necessary amount of recompilations + be performed. In this mode @code{gnatmake} ignores time + stamp differences when the only + modifications to a source file consist in adding/removing comments, + empty lines, spaces or tabs. This means that if you have changed the + comments in a source file or have simply reformatted it, using this + switch will tell gnatmake not to recompile files that depend on it + (provided other sources on which these files depend have undergone no + semantic modifications). Note that the debugging information may be + out of date with respect to the sources if the @option{-m} switch causes + a compilation to be switched, so the use of this switch represents a + trade-off between compilation time and accurate debugging information. + + @item ^-M^/DEPENDENCIES_LIST^ + @cindex Dependencies, producing list + @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake}) + Check if all objects are up to date. If they are, output the object + dependences to @file{stdout} in a form that can be directly exploited in + a @file{Makefile}. By default, each source file is prefixed with its + (relative or absolute) directory name. This name is whatever you + specified in the various @option{^-aI^/SOURCE_SEARCH^} + and @option{^-I^/SEARCH^} switches. If you use + @code{gnatmake ^-M^/DEPENDENCIES_LIST^} + @option{^-q^/QUIET^} + (see below), only the source file names, + without relative paths, are output. If you just specify the + @option{^-M^/DEPENDENCIES_LIST^} + switch, dependencies of the GNAT internal system files are omitted. This + is typically what you want. If you also specify + the @option{^-a^/ALL_FILES^} switch, + dependencies of the GNAT internal files are also listed. Note that + dependencies of the objects in external Ada libraries (see switch + @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list) + are never reported. + + @item ^-n^/DO_OBJECT_CHECK^ + @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake}) + Don't compile, bind, or link. Checks if all objects are up to date. + If they are not, the full name of the first file that needs to be + recompiled is printed. + Repeated use of this option, followed by compiling the indicated source + file, will eventually result in recompiling all required units. + + @item ^-o ^/EXECUTABLE=^@var{exec_name} + @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake}) + Output executable name. The name of the final executable program will be + @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default + name for the executable will be the name of the input file in appropriate form + for an executable file on the host system. + + This switch cannot be used when invoking @code{gnatmake} with several + @file{file_names}. + + @item ^-P^/PROJECT_FILE=^@var{project} + @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake}) + Use project file @var{project}. Only one such switch can be used. + See @ref{gnatmake and Project Files}. + + @item ^-q^/QUIET^ + @cindex @option{^-q^/QUIET^} (@code{gnatmake}) + Quiet. When this flag is not set, the commands carried out by + @code{gnatmake} are displayed. + + @item ^-s^/SWITCH_CHECK/^ + @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake}) + Recompile if compiler switches have changed since last compilation. + All compiler switches but -I and -o are taken into account in the + following way: + orders between different ``first letter'' switches are ignored, but + orders between same switches are taken into account. For example, + @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O} + is equivalent to @option{-O -g}. + + This switch is recommended when Integrated Preprocessing is used. + + @item ^-u^/UNIQUE^ + @cindex @option{^-u^/UNIQUE^} (@code{gnatmake}) + Unique. Recompile at most the main files. It implies -c. Combined with + -f, it is equivalent to calling the compiler directly. Note that using + ^-u^/UNIQUE^ with a project file and no main has a special meaning + (see @ref{Project Files and Main Subprograms}). + + @item ^-U^/ALL_PROJECTS^ + @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake}) + When used without a project file or with one or several mains on the command + line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main + on the command line, all sources of all project files are checked and compiled + if not up to date, and libraries are rebuilt, if necessary. + + @item ^-v^/REASONS^ + @cindex @option{^-v^/REASONS^} (@code{gnatmake}) + Verbose. Displays the reason for all recompilations @code{gnatmake} + decides are necessary. + + @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x} + Indicates the verbosity of the parsing of GNAT project files. + See @ref{Switches Related to Project Files}. + + @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value} + Indicates that external variable @var{name} has the value @var{value}. + The Project Manager will use this value for occurrences of + @code{external(name)} when parsing the project file. + See @ref{Switches Related to Project Files}. + + @item ^-z^/NOMAIN^ + @cindex @option{^-z^/NOMAIN^} (@code{gnatmake}) + No main subprogram. Bind and link the program even if the unit name + given on the command line is a package name. The resulting executable + will execute the elaboration routines of the package and its closure, + then the finalization routines. + + @item ^-g^/DEBUG^ + @cindex @option{^-g^/DEBUG^} (@code{gnatmake}) + Enable debugging. This switch is simply passed to the compiler and to the + linker. + + @end table + + @table @asis + @item @code{gcc} @asis{switches} + @ifclear vms + Any uppercase switch (other than @option{-A}, + @option{-L} or + @option{-S}) or any switch that is more than one character is passed to + @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.) + @end ifclear + @ifset vms + Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE} + but is recognizable as a valid qualifier for @code{GNAT COMPILE} is + automatically treated as a compiler switch, and passed on to all + compilations that are carried out. + @end ifset + @end table + + @noindent + Source and library search path switches: + + @table @option + @c !sort! + @item ^-aI^/SOURCE_SEARCH=^@var{dir} + @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake}) + When looking for source files also look in directory @var{dir}. + The order in which source files search is undertaken is + described in @ref{Search Paths and the Run-Time Library (RTL)}. + + @item ^-aL^/SKIP_MISSING=^@var{dir} + @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake}) + Consider @var{dir} as being an externally provided Ada library. + Instructs @code{gnatmake} to skip compilation units whose @file{.ALI} + files have been located in directory @var{dir}. This allows you to have + missing bodies for the units in @var{dir} and to ignore out of date bodies + for the same units. You still need to specify + the location of the specs for these units by using the switches + @option{^-aI^/SOURCE_SEARCH=^@var{dir}} + or @option{^-I^/SEARCH=^@var{dir}}. + Note: this switch is provided for compatibility with previous versions + of @code{gnatmake}. The easier method of causing standard libraries + to be excluded from consideration is to write-protect the corresponding + ALI files. + + @item ^-aO^/OBJECT_SEARCH=^@var{dir} + @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake}) + When searching for library and object files, look in directory + @var{dir}. The order in which library files are searched is described in + @ref{Search Paths for gnatbind}. + + @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir} + @cindex Search paths, for @code{gnatmake} + @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake}) + Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir} + ^-aI^/SOURCE_SEARCH=^@var{dir}}. + + @item ^-I^/SEARCH=^@var{dir} + @cindex @option{^-I^/SEARCH^} (@code{gnatmake}) + Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir} + ^-aI^/SOURCE_SEARCH=^@var{dir}}. + + @item ^-I-^/NOCURRENT_DIRECTORY^ + @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake}) + @cindex Source files, suppressing search + Do not look for source files in the directory containing the source + file named in the command line. + Do not look for ALI or object files in the directory + where @code{gnatmake} was invoked. + + @item ^-L^/LIBRARY_SEARCH=^@var{dir} + @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake}) + @cindex Linker libraries + Add directory @var{dir} to the list of directories in which the linker + will search for libraries. This is equivalent to + @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}. + @ifclear vms + Furthermore, under Windows, the sources pointed to by the libraries path + set in the registry are not searched for. + @end ifclear + + @item -nostdinc + @cindex @option{-nostdinc} (@code{gnatmake}) + Do not look for source files in the system default directory. + + @item -nostdlib + @cindex @option{-nostdlib} (@code{gnatmake}) + Do not look for library files in the system default directory. + + @item --RTS=@var{rts-path} + @cindex @option{--RTS} (@code{gnatmake}) + Specifies the default location of the runtime library. GNAT looks for the + runtime + in the following directories, and stops as soon as a valid runtime is found + (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or + @file{ada_object_path} present): + + @itemize @bullet + @item /$rts_path + + @item /$rts_path + + @item /rts-$rts_path + @end itemize + + @noindent + The selected path is handled like a normal RTS path. + + @end table + + @node Mode Switches for gnatmake + @section Mode Switches for @code{gnatmake} + + @noindent + The mode switches (referred to as @code{mode_switches}) allow the + inclusion of switches that are to be passed to the compiler itself, the + binder or the linker. The effect of a mode switch is to cause all + subsequent switches up to the end of the switch list, or up to the next + mode switch, to be interpreted as switches to be passed on to the + designated component of GNAT. + + @table @option + @c !sort! + @item -cargs @var{switches} + @cindex @option{-cargs} (@code{gnatmake}) + Compiler switches. Here @var{switches} is a list of switches + that are valid switches for @code{gcc}. They will be passed on to + all compile steps performed by @code{gnatmake}. + + @item -bargs @var{switches} + @cindex @option{-bargs} (@code{gnatmake}) + Binder switches. Here @var{switches} is a list of switches + that are valid switches for @code{gnatbind}. They will be passed on to + all bind steps performed by @code{gnatmake}. + + @item -largs @var{switches} + @cindex @option{-largs} (@code{gnatmake}) + Linker switches. Here @var{switches} is a list of switches + that are valid switches for @code{gnatlink}. They will be passed on to + all link steps performed by @code{gnatmake}. + + @item -margs @var{switches} + @cindex @option{-margs} (@code{gnatmake}) + Make switches. The switches are directly interpreted by @code{gnatmake}, + regardless of any previous occurrence of @option{-cargs}, @option{-bargs} + or @option{-largs}. + @end table + + @node Notes on the Command Line + @section Notes on the Command Line + + @noindent + This section contains some additional useful notes on the operation + of the @code{gnatmake} command. + + @itemize @bullet + @item + @cindex Recompilation, by @code{gnatmake} + If @code{gnatmake} finds no ALI files, it recompiles the main program + and all other units required by the main program. + This means that @code{gnatmake} + can be used for the initial compile, as well as during subsequent steps of + the development cycle. + + @item + If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb} + is a subunit or body of a generic unit, @code{gnatmake} recompiles + @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a + warning. + + @item + In @code{gnatmake} the switch @option{^-I^/SEARCH^} + is used to specify both source and + library file paths. Use @option{^-aI^/SOURCE_SEARCH^} + instead if you just want to specify + source paths only and @option{^-aO^/OBJECT_SEARCH^} + if you want to specify library paths + only. + + @item + @code{gnatmake} examines both an ALI file and its corresponding object file + for consistency. If an ALI is more recent than its corresponding object, + or if the object file is missing, the corresponding source will be recompiled. + Note that @code{gnatmake} expects an ALI and the corresponding object file + to be in the same directory. + + @item + @code{gnatmake} will ignore any files whose ALI file is write-protected. + This may conveniently be used to exclude standard libraries from + consideration and in particular it means that the use of the + @option{^-f^/FORCE_COMPILE^} switch will not recompile these files + unless @option{^-a^/ALL_FILES^} is also specified. + + @item + @code{gnatmake} has been designed to make the use of Ada libraries + particularly convenient. Assume you have an Ada library organized + as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for + of your Ada compilation units, + whereas @i{^include-dir^[INCLUDE_DIR]^} contains the + specs of these units, but no bodies. Then to compile a unit + stored in @code{main.adb}, which uses this Ada library you would just type + + @smallexample + @ifclear vms + $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main + @end ifclear + @ifset vms + $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]} + /SKIP_MISSING=@i{[OBJ_DIR]} main + @end ifset + @end smallexample + + @item + Using @code{gnatmake} along with the + @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^} + switch provides a mechanism for avoiding unnecessary rcompilations. Using + this switch, + you can update the comments/format of your + source files without having to recompile everything. Note, however, that + adding or deleting lines in a source files may render its debugging + info obsolete. If the file in question is a spec, the impact is rather + limited, as that debugging info will only be useful during the + elaboration phase of your program. For bodies the impact can be more + significant. In all events, your debugger will warn you if a source file + is more recent than the corresponding object, and alert you to the fact + that the debugging information may be out of date. + @end itemize + + @node How gnatmake Works + @section How @code{gnatmake} Works + + @noindent + Generally @code{gnatmake} automatically performs all necessary + recompilations and you don't need to worry about how it works. However, + it may be useful to have some basic understanding of the @code{gnatmake} + approach and in particular to understand how it uses the results of + previous compilations without incorrectly depending on them. + + First a definition: an object file is considered @dfn{up to date} if the + corresponding ALI file exists and its time stamp predates that of the + object file and if all the source files listed in the + dependency section of this ALI file have time stamps matching those in + the ALI file. This means that neither the source file itself nor any + files that it depends on have been modified, and hence there is no need + to recompile this file. + + @code{gnatmake} works by first checking if the specified main unit is up + to date. If so, no compilations are required for the main unit. If not, + @code{gnatmake} compiles the main program to build a new ALI file that + reflects the latest sources. Then the ALI file of the main unit is + examined to find all the source files on which the main program depends, + and @code{gnatmake} recursively applies the above procedure on all these files. + + This process ensures that @code{gnatmake} only trusts the dependencies + in an existing ALI file if they are known to be correct. Otherwise it + always recompiles to determine a new, guaranteed accurate set of + dependencies. As a result the program is compiled ``upside down'' from what may + be more familiar as the required order of compilation in some other Ada + systems. In particular, clients are compiled before the units on which + they depend. The ability of GNAT to compile in any order is critical in + allowing an order of compilation to be chosen that guarantees that + @code{gnatmake} will recompute a correct set of new dependencies if + necessary. + + When invoking @code{gnatmake} with several @var{file_names}, if a unit is + imported by several of the executables, it will be recompiled at most once. + + Note: when using non-standard naming conventions + (See @ref{Using Other File Names}), changing through a configuration pragmas + file the version of a source and invoking @code{gnatmake} to recompile may + have no effect, if the previous version of the source is still accessible + by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^. + + @node Examples of gnatmake Usage + @section Examples of @code{gnatmake} Usage + + @table @code + @item gnatmake hello.adb + Compile all files necessary to bind and link the main program + @file{hello.adb} (containing unit @code{Hello}) and bind and link the + resulting object files to generate an executable file @file{^hello^HELLO.EXE^}. + + @item gnatmake main1 main2 main3 + Compile all files necessary to bind and link the main programs + @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb} + (containing unit @code{Main2}) and @file{main3.adb} + (containing unit @code{Main3}) and bind and link the resulting object files + to generate three executable files @file{^main1^MAIN1.EXE^}, + @file{^main2^MAIN2.EXE^} + and @file{^main3^MAIN3.EXE^}. + + @ifclear vms + @item gnatmake -q Main_Unit -cargs -O2 -bargs -l + @end ifclear + + @ifset vms + @item gnatmake Main_Unit /QUIET + /COMPILER_QUALIFIERS /OPTIMIZE=ALL + /BINDER_QUALIFIERS /ORDER_OF_ELABORATION + @end ifset + Compile all files necessary to bind and link the main program unit + @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will + be done with optimization level 2 and the order of elaboration will be + listed by the binder. @code{gnatmake} will operate in quiet mode, not + displaying commands it is executing. + @end table + + + @c ************************* + @node Improving Performance + @chapter Improving Performance + @cindex Improving performance + + @noindent + This chapter presents several topics related to program performance. + It first describes some of the tradeoffs that need to be considered + and some of the techniques for making your program run faster. + It then documents the @command{gnatelim} tool, which can reduce + the size of program executables. + + @ifnottex + @menu + * Performance Considerations:: + * Reducing the Size of Ada Executables with gnatelim:: + @end menu + @end ifnottex + + + @c ***************************** + @node Performance Considerations + @section Performance Considerations + + @noindent + The GNAT system provides a number of options that allow a trade-off + between + + @itemize @bullet + @item + performance of the generated code + + @item + speed of compilation + + @item + minimization of dependences and recompilation + + @item + the degree of run-time checking. + @end itemize + + @noindent + The defaults (if no options are selected) aim at improving the speed + of compilation and minimizing dependences, at the expense of performance + of the generated code: + + @itemize @bullet + @item + no optimization + + @item + no inlining of subprogram calls + + @item + all run-time checks enabled except overflow and elaboration checks + @end itemize + + @noindent + These options are suitable for most program development purposes. This + chapter describes how you can modify these choices, and also provides + some guidelines on debugging optimized code. + + @menu + * Controlling Run-Time Checks:: + * Use of Restrictions:: + * Optimization Levels:: + * Debugging Optimized Code:: + * Inlining of Subprograms:: + @ifset vms + * Coverage Analysis:: + @end ifset + @end menu + + @node Controlling Run-Time Checks + @subsection Controlling Run-Time Checks + + @noindent + By default, GNAT generates all run-time checks, except arithmetic overflow + checking for integer operations and checks for access before elaboration on + subprogram calls. The latter are not required in default mode, because all + necessary checking is done at compile time. + @cindex @option{-gnatp} (@code{gcc}) + @cindex @option{-gnato} (@code{gcc}) + Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to + be modified. @xref{Run-Time Checks}. + + Our experience is that the default is suitable for most development + purposes. + + We treat integer overflow specially because these + are quite expensive and in our experience are not as important as other + run-time checks in the development process. Note that division by zero + is not considered an overflow check, and divide by zero checks are + generated where required by default. + + Elaboration checks are off by default, and also not needed by default, since + GNAT uses a static elaboration analysis approach that avoids the need for + run-time checking. This manual contains a full chapter discussing the issue + of elaboration checks, and if the default is not satisfactory for your use, + you should read this chapter. + + For validity checks, the minimal checks required by the Ada Reference + Manual (for case statements and assignments to array elements) are on + by default. These can be suppressed by use of the @option{-gnatVn} switch. + Note that in Ada 83, there were no validity checks, so if the Ada 83 mode + is acceptable (or when comparing GNAT performance with an Ada 83 compiler), + it may be reasonable to routinely use @option{-gnatVn}. Validity checks + are also suppressed entirely if @option{-gnatp} is used. + + @cindex Overflow checks + @cindex Checks, overflow + @findex Suppress + @findex Unsuppress + @cindex pragma Suppress + @cindex pragma Unsuppress + Note that the setting of the switches controls the default setting of + the checks. They may be modified using either @code{pragma Suppress} (to + remove checks) or @code{pragma Unsuppress} (to add back suppressed + checks) in the program source. + + @node Use of Restrictions + @subsection Use of Restrictions + + @noindent + The use of pragma Restrictions allows you to control which features are + permitted in your program. Apart from the obvious point that if you avoid + relatively expensive features like finalization (enforceable by the use + of pragma Restrictions (No_Finalization), the use of this pragma does not + affect the generated code in most cases. + + One notable exception to this rule is that the possibility of task abort + results in some distributed overhead, particularly if finalization or + exception handlers are used. The reason is that certain sections of code + have to be marked as non-abortable. + + If you use neither the @code{abort} statement, nor asynchronous transfer + of control (@code{select .. then abort}), then this distributed overhead + is removed, which may have a general positive effect in improving + overall performance. Especially code involving frequent use of tasking + constructs and controlled types will show much improved performance. + The relevant restrictions pragmas are + + @smallexample + pragma Restrictions (No_Abort_Statements); + pragma Restrictions (Max_Asynchronous_Select_Nesting => 0); + @end smallexample + + @noindent + It is recommended that these restriction pragmas be used if possible. Note + that this also means that you can write code without worrying about the + possibility of an immediate abort at any point. + + @node Optimization Levels + @subsection Optimization Levels + @cindex @option{^-O^/OPTIMIZE^} (@code{gcc}) + + @noindent + The default is optimization off. This results in the fastest compile + times, but GNAT makes absolutely no attempt to optimize, and the + generated programs are considerably larger and slower than when + optimization is enabled. You can use the + @ifclear vms + @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3, + @end ifclear + @ifset vms + @code{OPTIMIZE} qualifier + @end ifset + to @code{gcc} to control the optimization level: + + @table @option + @item ^-O0^/OPTIMIZE=NONE^ + No optimization (the default); + generates unoptimized code but has + the fastest compilation time. + + @item ^-O1^/OPTIMIZE=SOME^ + Medium level optimization; + optimizes reasonably well but does not + degrade compilation time significantly. + + @item ^-O2^/OPTIMIZE=ALL^ + @ifset vms + @itemx /OPTIMIZE=DEVELOPMENT + @end ifset + Full optimization; + generates highly optimized code and has + the slowest compilation time. + + @item ^-O3^/OPTIMIZE=INLINING^ + Full optimization as in @option{-O2}, + and also attempts automatic inlining of small + subprograms within a unit (@pxref{Inlining of Subprograms}). + @end table + + @noindent + Higher optimization levels perform more global transformations on the + program and apply more expensive analysis algorithms in order to generate + faster and more compact code. The price in compilation time, and the + resulting improvement in execution time, + both depend on the particular application and the hardware environment. + You should experiment to find the best level for your application. + + Since the precise set of optimizations done at each level will vary from + release to release (and sometime from target to target), it is best to think + of the optimization settings in general terms. + The @cite{Using GNU GCC} manual contains details about + ^the @option{-O} settings and a number of @option{-f} options that^how to^ + individually enable or disable specific optimizations. + + Unlike some other compilation systems, ^@command{gcc}^GNAT^ has + been tested extensively at all optimization levels. There are some bugs + which appear only with optimization turned on, but there have also been + bugs which show up only in @emph{unoptimized} code. Selecting a lower + level of optimization does not improve the reliability of the code + generator, which in practice is highly reliable at all optimization + levels. + + Note regarding the use of @option{-O3}: The use of this optimization level + is generally discouraged with GNAT, since it often results in larger + executables which run more slowly. See further discussion of this point + in @pxref{Inlining of Subprograms}. + + + @node Debugging Optimized Code + @subsection Debugging Optimized Code + @cindex Debugging optimized code + @cindex Optimization and debugging + + @noindent + Although it is possible to do a reasonable amount of debugging at + @ifclear vms + non-zero optimization levels, + the higher the level the more likely that + @end ifclear + @ifset vms + @option{/OPTIMIZE} settings other than @code{NONE}, + such settings will make it more likely that + @end ifset + source-level constructs will have been eliminated by optimization. + For example, if a loop is strength-reduced, the loop + control variable may be completely eliminated and thus cannot be + displayed in the debugger. + This can only happen at @option{-O2} or @option{-O3}. + Explicit temporary variables that you code might be eliminated at + ^level^setting^ @option{-O1} or higher. + + The use of the @option{^-g^/DEBUG^} switch, + @cindex @option{^-g^/DEBUG^} (@code{gcc}) + which is needed for source-level debugging, + affects the size of the program executable on disk, + and indeed the debugging information can be quite large. + However, it has no effect on the generated code (and thus does not + degrade performance) + + Since the compiler generates debugging tables for a compilation unit before + it performs optimizations, the optimizing transformations may invalidate some + of the debugging data. You therefore need to anticipate certain + anomalous situations that may arise while debugging optimized code. + These are the most common cases: + + @enumerate + @item + @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next} + commands show + the PC bouncing back and forth in the code. This may result from any of + the following optimizations: + + @itemize @bullet + @item + @i{Common subexpression elimination:} using a single instance of code for a + quantity that the source computes several times. As a result you + may not be able to stop on what looks like a statement. + + @item + @i{Invariant code motion:} moving an expression that does not change within a + loop, to the beginning of the loop. + + @item + @i{Instruction scheduling:} moving instructions so as to + overlap loads and stores (typically) with other code, or in + general to move computations of values closer to their uses. Often + this causes you to pass an assignment statement without the assignment + happening and then later bounce back to the statement when the + value is actually needed. Placing a breakpoint on a line of code + and then stepping over it may, therefore, not always cause all the + expected side-effects. + @end itemize + + @item + @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which + two identical pieces of code are merged and the program counter suddenly + jumps to a statement that is not supposed to be executed, simply because + it (and the code following) translates to the same thing as the code + that @emph{was} supposed to be executed. This effect is typically seen in + sequences that end in a jump, such as a @code{goto}, a @code{return}, or + a @code{break} in a C @code{^switch^switch^} statement. + + @item + @i{The ``roving variable'':} The symptom is an unexpected value in a variable. + There are various reasons for this effect: + + @itemize @bullet + @item + In a subprogram prologue, a parameter may not yet have been moved to its + ``home''. + + @item + A variable may be dead, and its register re-used. This is + probably the most common cause. + + @item + As mentioned above, the assignment of a value to a variable may + have been moved. + + @item + A variable may be eliminated entirely by value propagation or + other means. In this case, GCC may incorrectly generate debugging + information for the variable + @end itemize + + @noindent + In general, when an unexpected value appears for a local variable or parameter + you should first ascertain if that value was actually computed by + your program, as opposed to being incorrectly reported by the debugger. + Record fields or + array elements in an object designated by an access value + are generally less of a problem, once you have ascertained that the access + value is sensible. + Typically, this means checking variables in the preceding code and in the + calling subprogram to verify that the value observed is explainable from other + values (one must apply the procedure recursively to those + other values); or re-running the code and stopping a little earlier + (perhaps before the call) and stepping to better see how the variable obtained + the value in question; or continuing to step @emph{from} the point of the + strange value to see if code motion had simply moved the variable's + assignments later. + @end enumerate + + @noindent + In light of such anomalies, a recommended technique is to use @option{-O0} + early in the software development cycle, when extensive debugging capabilities + are most needed, and then move to @option{-O1} and later @option{-O2} as + the debugger becomes less critical. + Whether to use the @option{^-g^/DEBUG^} switch in the release version is + a release management issue. + @ifclear vms + Note that if you use @option{-g} you can then use the @command{strip} program + on the resulting executable, + which removes both debugging information and global symbols. + @end ifclear + + + @node Inlining of Subprograms + @subsection Inlining of Subprograms + + @noindent + A call to a subprogram in the current unit is inlined if all the + following conditions are met: + + @itemize @bullet + @item + The optimization level is at least @option{-O1}. + + @item + The called subprogram is suitable for inlining: It must be small enough + and not contain nested subprograms or anything else that @code{gcc} + cannot support in inlined subprograms. + + @item + The call occurs after the definition of the body of the subprogram. + + @item + @cindex pragma Inline + @findex Inline + Either @code{pragma Inline} applies to the subprogram or it is + small and automatic inlining (optimization level @option{-O3}) is + specified. + @end itemize + + @noindent + Calls to subprograms in @code{with}'ed units are normally not inlined. + To achieve this level of inlining, the following conditions must all be + true: + + @itemize @bullet + @item + The optimization level is at least @option{-O1}. + + @item + The called subprogram is suitable for inlining: It must be small enough + and not contain nested subprograms or anything else @code{gcc} cannot + support in inlined subprograms. + + @item + The call appears in a body (not in a package spec). + + @item + There is a @code{pragma Inline} for the subprogram. + + @item + @cindex @option{-gnatn} (@code{gcc}) + The @option{^-gnatn^/INLINE^} switch + is used in the @code{gcc} command line + @end itemize + + Note that specifying the @option{-gnatn} switch causes additional + compilation dependencies. Consider the following: + + @smallexample @c ada + @cartouche + package R is + procedure Q; + pragma Inline (Q); + end R; + package body R is + ... + end R; + + with R; + procedure Main is + begin + ... + R.Q; + end Main; + @end cartouche + @end smallexample + + @noindent + With the default behavior (no @option{-gnatn} switch specified), the + compilation of the @code{Main} procedure depends only on its own source, + @file{main.adb}, and the spec of the package in file @file{r.ads}. This + means that editing the body of @code{R} does not require recompiling + @code{Main}. + + On the other hand, the call @code{R.Q} is not inlined under these + circumstances. If the @option{-gnatn} switch is present when @code{Main} + is compiled, the call will be inlined if the body of @code{Q} is small + enough, but now @code{Main} depends on the body of @code{R} in + @file{r.adb} as well as on the spec. This means that if this body is edited, + the main program must be recompiled. Note that this extra dependency + occurs whether or not the call is in fact inlined by @code{gcc}. + + The use of front end inlining with @option{-gnatN} generates similar + additional dependencies. + + @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc}) + Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch + can be used to prevent + all inlining. This switch overrides all other conditions and ensures + that no inlining occurs. The extra dependences resulting from + @option{-gnatn} will still be active, even if + this switch is used to suppress the resulting inlining actions. + + Note regarding the use of @option{-O3}: There is no difference in inlining + behavior between @option{-O2} and @option{-O3} for subprograms with an explicit + pragma @code{Inline} assuming the use of @option{-gnatn} + or @option{-gnatN} (the switches that activate inlining). If you have used + pragma @code{Inline} in appropriate cases, then it is usually much better + to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which + in this case only has the effect of inlining subprograms you did not + think should be inlined. We often find that the use of @option{-O3} slows + down code by performing excessive inlining, leading to increased instruction + cache pressure from the increased code size. So the bottom line here is + that you should not automatically assume that @option{-O3} is better than + @option{-O2}, and indeed you should use @option{-O3} only if tests show that + it actually improves performance. + + @ifset vms + @node Coverage Analysis + @subsection Coverage Analysis + + @noindent + GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows + the user to determine the distribution of execution time across a program, + @pxref{Profiling} for details of usage. + @end ifset + + @node Reducing the Size of Ada Executables with gnatelim + @section Reducing the Size of Ada Executables with @code{gnatelim} + @findex gnatelim + + @noindent + This section describes @command{gnatelim}, a tool which detects unused + subprograms and helps the compiler to create a smaller executable for your + program. + + @menu + * About gnatelim:: + * Running gnatelim:: + * Correcting the List of Eliminate Pragmas:: + * Making Your Executables Smaller:: + * Summary of the gnatelim Usage Cycle:: + @end menu + + @node About gnatelim + @subsection About @code{gnatelim} + + @noindent + When a program shares a set of Ada + packages with other programs, it may happen that this program uses + only a fraction of the subprograms defined in these packages. The code + created for these unused subprograms increases the size of the executable. + + @code{gnatelim} tracks unused subprograms in an Ada program and + outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the + subprograms that are declared but never called. By placing the list of + @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and + recompiling your program, you may decrease the size of its executable, + because the compiler will not generate the code for 'eliminated' subprograms. + See GNAT Reference Manual for more information about this pragma. + + @code{gnatelim} needs as its input data the name of the main subprogram + and a bind file for a main subprogram. + + To create a bind file for @code{gnatelim}, run @code{gnatbind} for + the main subprogram. @code{gnatelim} can work with both Ada and C + bind files; when both are present, it uses the Ada bind file. + The following commands will build the program and create the bind file: + + @smallexample + $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^ + $ gnatbind main_prog + @end smallexample + + Note that @code{gnatelim} needs neither object nor ALI files. + + @node Running gnatelim + @subsection Running @code{gnatelim} + + @noindent + @code{gnatelim} has the following command-line interface: + + @smallexample + $ gnatelim [options] name + @end smallexample + + @noindent + @code{name} should be a name of a source file that contains the main subprogram + of a program (partition). + + @code{gnatelim} has the following switches: + + @table @option + @c !sort! + @item ^-q^/QUIET^ + @cindex @option{^-q^/QUIET^} (@command{gnatelim}) + Quiet mode: by default @code{gnatelim} outputs to the standard error + stream the number of program units left to be processed. This option turns + this trace off. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@command{gnatelim}) + Verbose mode: @code{gnatelim} version information is printed as Ada + comments to the standard output stream. Also, in addition to the number of + program units left @code{gnatelim} will output the name of the current unit + being processed. + + @item ^-a^/ALL^ + @cindex @option{^-a^/ALL^} (@command{gnatelim}) + Also look for subprograms from the GNAT run time that can be eliminated. Note + that when @file{gnat.adc} is produced using this switch, the entire program + must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}. + + @item ^-I^/INCLUDE_DIRS=^@var{dir} + @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim}) + When looking for source files also look in directory @var{dir}. Specifying + @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for + sources in the current directory. + + @item ^-b^/BIND_FILE=^@var{bind_file} + @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim}) + Specifies @var{bind_file} as the bind file to process. If not set, the name + of the bind file is computed from the full expanded Ada name + of a main subprogram. + + @item ^-C^/CONFIG_FILE=^@var{config_file} + @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim}) + Specifies a file @var{config_file} that contains configuration pragmas. The + file must be specified with full path. + + @item ^--GCC^/COMPILER^=@var{compiler_name} + @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim}) + Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one + available on the path. + + @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name} + @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim}) + Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one + available on the path. + + @item -d@var{x} + @cindex @option{-d@var{x}} (@command{gnatelim}) + Activate internal debugging switches. @var{x} is a letter or digit, or + string of letters or digits, which specifies the type of debugging + mode desired. Normally these are used only for internal development + or system debugging purposes. You can find full documentation for these + switches in the spec of the @code{Gnatelim} unit in the compiler + source file @file{gnatelim.ads}. + @end table + + @noindent + @code{gnatelim} sends its output to the standard output stream, and all the + tracing and debug information is sent to the standard error stream. + In order to produce a proper GNAT configuration file + @file{gnat.adc}, redirection must be used: + + @smallexample + @ifset vms + $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC + @end ifset + @ifclear vms + $ gnatelim main_prog.adb > gnat.adc + @end ifclear + @end smallexample + + @ifclear vms + @noindent + or + + @smallexample + $ gnatelim main_prog.adb >> gnat.adc + @end smallexample + + @noindent + in order to append the @code{gnatelim} output to the existing contents of + @file{gnat.adc}. + @end ifclear + + @node Correcting the List of Eliminate Pragmas + @subsection Correcting the List of Eliminate Pragmas + + @noindent + In some rare cases @code{gnatelim} may try to eliminate + subprograms that are actually called in the program. In this case, the + compiler will generate an error message of the form: + + @smallexample + file.adb:106:07: cannot call eliminated subprogram "My_Prog" + @end smallexample + + @noindent + You will need to manually remove the wrong @code{Eliminate} pragmas from + the @file{gnat.adc} file. You should recompile your program + from scratch after that, because you need a consistent @file{gnat.adc} file + during the entire compilation. + + + @node Making Your Executables Smaller + @subsection Making Your Executables Smaller + + @noindent + In order to get a smaller executable for your program you now have to + recompile the program completely with the new @file{gnat.adc} file + created by @code{gnatelim} in your current directory: + + @smallexample + $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^ + @end smallexample + + @noindent + (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to + recompile everything + with the set of pragmas @code{Eliminate} that you have obtained with + @command{gnatelim}). + + Be aware that the set of @code{Eliminate} pragmas is specific to each + program. It is not recommended to merge sets of @code{Eliminate} + pragmas created for different programs in one @file{gnat.adc} file. + + @node Summary of the gnatelim Usage Cycle + @subsection Summary of the gnatelim Usage Cycle + + @noindent + Here is a quick summary of the steps to be taken in order to reduce + the size of your executables with @code{gnatelim}. You may use + other GNAT options to control the optimization level, + to produce the debugging information, to set search path, etc. + + @enumerate + @item + Produce a bind file + + @smallexample + $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^ + $ gnatbind main_prog + @end smallexample + + @item + Generate a list of @code{Eliminate} pragmas + @smallexample + @ifset vms + $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC + @end ifset + @ifclear vms + $ gnatelim main_prog >[>] gnat.adc + @end ifclear + @end smallexample + + @item + Recompile the application + + @smallexample + $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^ + @end smallexample + + @end enumerate + + + + + @c ******************************** + @node Renaming Files Using gnatchop + @chapter Renaming Files Using @code{gnatchop} + @findex gnatchop + + @noindent + This chapter discusses how to handle files with multiple units by using + the @code{gnatchop} utility. This utility is also useful in renaming + files to meet the standard GNAT default file naming conventions. + + @menu + * Handling Files with Multiple Units:: + * Operating gnatchop in Compilation Mode:: + * Command Line for gnatchop:: + * Switches for gnatchop:: + * Examples of gnatchop Usage:: + @end menu + + @node Handling Files with Multiple Units + @section Handling Files with Multiple Units + + @noindent + The basic compilation model of GNAT requires that a file submitted to the + compiler have only one unit and there be a strict correspondence + between the file name and the unit name. + + The @code{gnatchop} utility allows both of these rules to be relaxed, + allowing GNAT to process files which contain multiple compilation units + and files with arbitrary file names. @code{gnatchop} + reads the specified file and generates one or more output files, + containing one unit per file. The unit and the file name correspond, + as required by GNAT. + + If you want to permanently restructure a set of ``foreign'' files so that + they match the GNAT rules, and do the remaining development using the + GNAT structure, you can simply use @command{gnatchop} once, generate the + new set of files and work with them from that point on. + + Alternatively, if you want to keep your files in the ``foreign'' format, + perhaps to maintain compatibility with some other Ada compilation + system, you can set up a procedure where you use @command{gnatchop} each + time you compile, regarding the source files that it writes as temporary + files that you throw away. + + + @node Operating gnatchop in Compilation Mode + @section Operating gnatchop in Compilation Mode + + @noindent + The basic function of @code{gnatchop} is to take a file with multiple units + and split it into separate files. The boundary between files is reasonably + clear, except for the issue of comments and pragmas. In default mode, the + rule is that any pragmas between units belong to the previous unit, except + that configuration pragmas always belong to the following unit. Any comments + belong to the following unit. These rules + almost always result in the right choice of + the split point without needing to mark it explicitly and most users will + find this default to be what they want. In this default mode it is incorrect to + submit a file containing only configuration pragmas, or one that ends in + configuration pragmas, to @code{gnatchop}. + + However, using a special option to activate ``compilation mode'', + @code{gnatchop} + can perform another function, which is to provide exactly the semantics + required by the RM for handling of configuration pragmas in a compilation. + In the absence of configuration pragmas (at the main file level), this + option has no effect, but it causes such configuration pragmas to be handled + in a quite different manner. + + First, in compilation mode, if @code{gnatchop} is given a file that consists of + only configuration pragmas, then this file is appended to the + @file{gnat.adc} file in the current directory. This behavior provides + the required behavior described in the RM for the actions to be taken + on submitting such a file to the compiler, namely that these pragmas + should apply to all subsequent compilations in the same compilation + environment. Using GNAT, the current directory, possibly containing a + @file{gnat.adc} file is the representation + of a compilation environment. For more information on the + @file{gnat.adc} file, see the section on handling of configuration + pragmas @pxref{Handling of Configuration Pragmas}. + + Second, in compilation mode, if @code{gnatchop} + is given a file that starts with + configuration pragmas, and contains one or more units, then these + configuration pragmas are prepended to each of the chopped files. This + behavior provides the required behavior described in the RM for the + actions to be taken on compiling such a file, namely that the pragmas + apply to all units in the compilation, but not to subsequently compiled + units. + + Finally, if configuration pragmas appear between units, they are appended + to the previous unit. This results in the previous unit being illegal, + since the compiler does not accept configuration pragmas that follow + a unit. This provides the required RM behavior that forbids configuration + pragmas other than those preceding the first compilation unit of a + compilation. + + For most purposes, @code{gnatchop} will be used in default mode. The + compilation mode described above is used only if you need exactly + accurate behavior with respect to compilations, and you have files + that contain multiple units and configuration pragmas. In this + circumstance the use of @code{gnatchop} with the compilation mode + switch provides the required behavior, and is for example the mode + in which GNAT processes the ACVC tests. + + @node Command Line for gnatchop + @section Command Line for @code{gnatchop} + + @noindent + The @code{gnatchop} command has the form: + + @smallexample + $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...] + [@var{directory}] + @end smallexample + + @noindent + The only required argument is the file name of the file to be chopped. + There are no restrictions on the form of this file name. The file itself + contains one or more Ada units, in normal GNAT format, concatenated + together. As shown, more than one file may be presented to be chopped. + + When run in default mode, @code{gnatchop} generates one output file in + the current directory for each unit in each of the files. + + @var{directory}, if specified, gives the name of the directory to which + the output files will be written. If it is not specified, all files are + written to the current directory. + + For example, given a + file called @file{hellofiles} containing + + @smallexample @c ada + @group + @cartouche + procedure hello; + + with Text_IO; use Text_IO; + procedure hello is + begin + Put_Line ("Hello"); + end hello; + @end cartouche + @end group + @end smallexample + + @noindent + the command + + @smallexample + $ gnatchop ^hellofiles^HELLOFILES.^ + @end smallexample + + @noindent + generates two files in the current directory, one called + @file{hello.ads} containing the single line that is the procedure spec, + and the other called @file{hello.adb} containing the remaining text. The + original file is not affected. The generated files can be compiled in + the normal manner. + + @noindent + When gnatchop is invoked on a file that is empty or that contains only empty + lines and/or comments, gnatchop will not fail, but will not produce any + new sources. + + For example, given a + file called @file{toto.txt} containing + + @smallexample @c ada + @group + @cartouche + -- Just a comment + @end cartouche + @end group + @end smallexample + + @noindent + the command + + @smallexample + $ gnatchop ^toto.txt^TOT.TXT^ + @end smallexample + + @noindent + will not produce any new file and will result in the following warnings: + + @smallexample + toto.txt:1:01: warning: empty file, contains no compilation units + no compilation units found + no source files written + @end smallexample + + @node Switches for gnatchop + @section Switches for @code{gnatchop} + + @noindent + @command{gnatchop} recognizes the following switches: + + @table @option + @c !sort! + + @item ^-c^/COMPILATION^ + @cindex @option{^-c^/COMPILATION^} (@code{gnatchop}) + Causes @code{gnatchop} to operate in compilation mode, in which + configuration pragmas are handled according to strict RM rules. See + previous section for a full description of this mode. + + @ifclear vms + @item -gnatxxx + This passes the given @option{-gnatxxx} switch to @code{gnat} which is + used to parse the given file. Not all @code{xxx} options make sense, + but for example, the use of @option{-gnati2} allows @code{gnatchop} to + process a source file that uses Latin-2 coding for identifiers. + @end ifclear + + @item ^-h^/HELP^ + Causes @code{gnatchop} to generate a brief help summary to the standard + output file showing usage information. + + @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^ + @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop}) + Limit generated file names to the specified number @code{mm} + of characters. + This is useful if the + resulting set of files is required to be interoperable with systems + which limit the length of file names. + @ifset vms + If no value is given, or + if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given, + a default of 39, suitable for OpenVMS Alpha + Systems, is assumed + @end ifset + @ifclear vms + No space is allowed between the @option{-k} and the numeric value. The numeric + value may be omitted in which case a default of @option{-k8}, + suitable for use + with DOS-like file systems, is used. If no @option{-k} switch + is present then + there is no limit on the length of file names. + @end ifclear + + @item ^-p^/PRESERVE^ + @cindex @option{^-p^/PRESERVE^} (@code{gnatchop}) + Causes the file ^modification^creation^ time stamp of the input file to be + preserved and used for the time stamp of the output file(s). This may be + useful for preserving coherency of time stamps in an environment where + @code{gnatchop} is used as part of a standard build process. + + @item ^-q^/QUIET^ + @cindex @option{^-q^/QUIET^} (@code{gnatchop}) + Causes output of informational messages indicating the set of generated + files to be suppressed. Warnings and error messages are unaffected. + + @item ^-r^/REFERENCE^ + @cindex @option{^-r^/REFERENCE^} (@code{gnatchop}) + @findex Source_Reference + Generate @code{Source_Reference} pragmas. Use this switch if the output + files are regarded as temporary and development is to be done in terms + of the original unchopped file. This switch causes + @code{Source_Reference} pragmas to be inserted into each of the + generated files to refers back to the original file name and line number. + The result is that all error messages refer back to the original + unchopped file. + In addition, the debugging information placed into the object file (when + the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified) + also refers back to this original file so that tools like profilers and + debuggers will give information in terms of the original unchopped file. + + If the original file to be chopped itself contains + a @code{Source_Reference} + pragma referencing a third file, then gnatchop respects + this pragma, and the generated @code{Source_Reference} pragmas + in the chopped file refer to the original file, with appropriate + line numbers. This is particularly useful when @code{gnatchop} + is used in conjunction with @code{gnatprep} to compile files that + contain preprocessing statements and multiple units. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@code{gnatchop}) + Causes @code{gnatchop} to operate in verbose mode. The version + number and copyright notice are output, as well as exact copies of + the gnat1 commands spawned to obtain the chop control information. + + @item ^-w^/OVERWRITE^ + @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop}) + Overwrite existing file names. Normally @code{gnatchop} regards it as a + fatal error if there is already a file with the same name as a + file it would otherwise output, in other words if the files to be + chopped contain duplicated units. This switch bypasses this + check, and causes all but the last instance of such duplicated + units to be skipped. + + @ifclear vms + @item --GCC=xxxx + @cindex @option{--GCC=} (@code{gnatchop}) + Specify the path of the GNAT parser to be used. When this switch is used, + no attempt is made to add the prefix to the GNAT parser executable. + @end ifclear + @end table + + @node Examples of gnatchop Usage + @section Examples of @code{gnatchop} Usage + + @table @code + @ifset vms + @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES] + @end ifset + @ifclear vms + @item gnatchop -w hello_s.ada prerelease/files + @end ifclear + + Chops the source file @file{hello_s.ada}. The output files will be + placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^}, + overwriting any + files with matching names in that directory (no files in the current + directory are modified). + + @item gnatchop ^archive^ARCHIVE.^ + Chops the source file @file{^archive^ARCHIVE.^} + into the current directory. One + useful application of @code{gnatchop} is in sending sets of sources + around, for example in email messages. The required sources are simply + concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^ + command), and then + @code{gnatchop} is used at the other end to reconstitute the original + file names. + + @item gnatchop file1 file2 file3 direc + Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing + the resulting files in the directory @file{direc}. Note that if any units + occur more than once anywhere within this set of files, an error message + is generated, and no files are written. To override this check, use the + @option{^-w^/OVERWRITE^} switch, + in which case the last occurrence in the last file will + be the one that is output, and earlier duplicate occurrences for a given + unit will be skipped. + @end table + + @node Configuration Pragmas + @chapter Configuration Pragmas + @cindex Configuration pragmas + @cindex Pragmas, configuration + + @noindent + In Ada 95, configuration pragmas include those pragmas described as + such in the Ada 95 Reference Manual, as well as + implementation-dependent pragmas that are configuration pragmas. See the + individual descriptions of pragmas in the GNAT Reference Manual for + details on these additional GNAT-specific configuration pragmas. Most + notably, the pragma @code{Source_File_Name}, which allows + specifying non-default names for source files, is a configuration + pragma. The following is a complete list of configuration pragmas + recognized by @code{GNAT}: + + @smallexample + Ada_83 + Ada_95 + C_Pass_By_Copy + Component_Alignment + Discard_Names + Elaboration_Checks + Eliminate + Extend_System + Extensions_Allowed + External_Name_Casing + Float_Representation + Initialize_Scalars + License + Locking_Policy + Long_Float + Normalize_Scalars + Polling + Propagate_Exceptions + Queuing_Policy + Ravenscar + Restricted_Run_Time + Restrictions + Reviewable + Source_File_Name + Style_Checks + Suppress + Task_Dispatching_Policy + Universal_Data + Unsuppress + Use_VADS_Size + Warnings + Validity_Checks + @end smallexample + + @menu + * Handling of Configuration Pragmas:: + * The Configuration Pragmas Files:: + @end menu + + @node Handling of Configuration Pragmas + @section Handling of Configuration Pragmas + + Configuration pragmas may either appear at the start of a compilation + unit, in which case they apply only to that unit, or they may apply to + all compilations performed in a given compilation environment. + + GNAT also provides the @code{gnatchop} utility to provide an automatic + way to handle configuration pragmas following the semantics for + compilations (that is, files with multiple units), described in the RM. + See section @pxref{Operating gnatchop in Compilation Mode} for details. + However, for most purposes, it will be more convenient to edit the + @file{gnat.adc} file that contains configuration pragmas directly, + as described in the following section. + + @node The Configuration Pragmas Files + @section The Configuration Pragmas Files + @cindex @file{gnat.adc} + + @noindent + In GNAT a compilation environment is defined by the current + directory at the time that a compile command is given. This current + directory is searched for a file whose name is @file{gnat.adc}. If + this file is present, it is expected to contain one or more + configuration pragmas that will be applied to the current compilation. + However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not + considered. + + Configuration pragmas may be entered into the @file{gnat.adc} file + either by running @code{gnatchop} on a source file that consists only of + configuration pragmas, or more conveniently by + direct editing of the @file{gnat.adc} file, which is a standard format + source file. + + In addition to @file{gnat.adc}, one additional file containing configuration + pragmas may be applied to the current compilation using the switch + @option{-gnatec}@var{path}. @var{path} must designate an existing file that + contains only configuration pragmas. These configuration pragmas are + in addition to those found in @file{gnat.adc} (provided @file{gnat.adc} + is present and switch @option{-gnatA} is not used). + + It is allowed to specify several switches @option{-gnatec}, however only + the last one on the command line will be taken into account. + + If you are using project file, a separate mechanism is provided using + project attributes, see @ref{Specifying Configuration Pragmas} for more + details. + + @ifset vms + Of special interest to GNAT OpenVMS Alpha is the following + configuration pragma: + + @smallexample @c ada + @cartouche + pragma Extend_System (Aux_DEC); + @end cartouche + @end smallexample + + @noindent + In the presence of this pragma, GNAT adds to the definition of the + predefined package SYSTEM all the additional types and subprograms that are + defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details. + @end ifset + + @node Handling Arbitrary File Naming Conventions Using gnatname + @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} + @cindex Arbitrary File Naming Conventions + + @menu + * Arbitrary File Naming Conventions:: + * Running gnatname:: + * Switches for gnatname:: + * Examples of gnatname Usage:: + @end menu + + @node Arbitrary File Naming Conventions + @section Arbitrary File Naming Conventions + + @noindent + The GNAT compiler must be able to know the source file name of a compilation + unit. When using the standard GNAT default file naming conventions + (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler + does not need additional information. + + @noindent + When the source file names do not follow the standard GNAT default file naming + conventions, the GNAT compiler must be given additional information through + a configuration pragmas file (see @ref{Configuration Pragmas}) + or a project file. + When the non standard file naming conventions are well-defined, + a small number of pragmas @code{Source_File_Name} specifying a naming pattern + (see @ref{Alternative File Naming Schemes}) may be sufficient. However, + if the file naming conventions are irregular or arbitrary, a number + of pragma @code{Source_File_Name} for individual compilation units + must be defined. + To help maintain the correspondence between compilation unit names and + source file names within the compiler, + GNAT provides a tool @code{gnatname} to generate the required pragmas for a + set of files. + + @node Running gnatname + @section Running @code{gnatname} + + @noindent + The usual form of the @code{gnatname} command is + + @smallexample + $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}] + @end smallexample + + @noindent + All of the arguments are optional. If invoked without any argument, + @code{gnatname} will display its usage. + + @noindent + When used with at least one naming pattern, @code{gnatname} will attempt to + find all the compilation units in files that follow at least one of the + naming patterns. To find these compilation units, + @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all + regular files. + + @noindent + One or several Naming Patterns may be given as arguments to @code{gnatname}. + Each Naming Pattern is enclosed between double quotes. + A Naming Pattern is a regular expression similar to the wildcard patterns + used in file names by the Unix shells or the DOS prompt. + + @noindent + Examples of Naming Patterns are + + @smallexample + "*.[12].ada" + "*.ad[sb]*" + "body_*" "spec_*" + @end smallexample + + @noindent + For a more complete description of the syntax of Naming Patterns, + see the second kind of regular expressions described in @file{g-regexp.ads} + (the ``Glob'' regular expressions). + + @noindent + When invoked with no switches, @code{gnatname} will create a configuration + pragmas file @file{gnat.adc} in the current working directory, with pragmas + @code{Source_File_Name} for each file that contains a valid Ada unit. + + @node Switches for gnatname + @section Switches for @code{gnatname} + + @noindent + Switches for @code{gnatname} must precede any specified Naming Pattern. + + @noindent + You may specify any of the following switches to @code{gnatname}: + + @table @option + @c !sort! + + @item ^-c^/CONFIG_FILE=^@file{file} + @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname}) + Create a configuration pragmas file @file{file} (instead of the default + @file{gnat.adc}). + @ifclear vms + There may be zero, one or more space between @option{-c} and + @file{file}. + @end ifclear + @file{file} may include directory information. @file{file} must be + writable. There may be only one switch @option{^-c^/CONFIG_FILE^}. + When a switch @option{^-c^/CONFIG_FILE^} is + specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below). + + @item ^-d^/SOURCE_DIRS=^@file{dir} + @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname}) + Look for source files in directory @file{dir}. There may be zero, one or more + spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}. + When a switch @option{^-d^/SOURCE_DIRS^} + is specified, the current working directory will not be searched for source + files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^} + or @option{^-D^/DIR_FILES^} switch. + Several switches @option{^-d^/SOURCE_DIRS^} may be specified. + If @file{dir} is a relative path, it is relative to the directory of + the configuration pragmas file specified with switch + @option{^-c^/CONFIG_FILE^}, + or to the directory of the project file specified with switch + @option{^-P^/PROJECT_FILE^} or, + if neither switch @option{^-c^/CONFIG_FILE^} + nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the + current working directory. The directory + specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable. + + @item ^-D^/DIRS_FILE=^@file{file} + @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname}) + Look for source files in all directories listed in text file @file{file}. + There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^} + and @file{file}. + @file{file} must be an existing, readable text file. + Each non empty line in @file{file} must be a directory. + Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many + switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in + @file{file}. + + @item ^-f^/FOREIGN_PATTERN=^@file{pattern} + @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname}) + Foreign patterns. Using this switch, it is possible to add sources of languages + other than Ada to the list of sources of a project file. + It is only useful if a ^-P^/PROJECT_FILE^ switch is used. + For example, + @smallexample + gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada" + @end smallexample + @noindent + will look for Ada units in all files with the @file{.ada} extension, + and will add to the list of file for project @file{prj.gpr} the C files + with extension ".^c^C^". + + @item ^-h^/HELP^ + @cindex @option{^-h^/HELP^} (@code{gnatname}) + Output usage (help) information. The output is written to @file{stdout}. + + @item ^-P^/PROJECT_FILE=^@file{proj} + @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname}) + Create or update project file @file{proj}. There may be zero, one or more space + between @option{-P} and @file{proj}. @file{proj} may include directory + information. @file{proj} must be writable. + There may be only one switch @option{^-P^/PROJECT_FILE^}. + When a switch @option{^-P^/PROJECT_FILE^} is specified, + no switch @option{^-c^/CONFIG_FILE^} may be specified. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@code{gnatname}) + Verbose mode. Output detailed explanation of behavior to @file{stdout}. + This includes name of the file written, the name of the directories to search + and, for each file in those directories whose name matches at least one of + the Naming Patterns, an indication of whether the file contains a unit, + and if so the name of the unit. + + @item ^-v -v^/VERBOSE /VERBOSE^ + @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname}) + Very Verbose mode. In addition to the output produced in verbose mode, + for each file in the searched directories whose name matches none of + the Naming Patterns, an indication is given that there is no match. + + @item ^-x^/EXCLUDED_PATTERN=^@file{pattern} + @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname}) + Excluded patterns. Using this switch, it is possible to exclude some files + that would match the name patterns. For example, + @smallexample + gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada" + @end smallexample + @noindent + will look for Ada units in all files with the @file{.ada} extension, + except those whose names end with @file{_nt.ada}. + + @end table + + @node Examples of gnatname Usage + @section Examples of @code{gnatname} Usage + + @ifset vms + @smallexample + $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*" + @end smallexample + @end ifset + + @ifclear vms + @smallexample + $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" + @end smallexample + @end ifclear + + @noindent + In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist + and be writable. In addition, the directory + @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by + @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable. + + @ifclear vms + Note the optional spaces after @option{-c} and @option{-d}. + @end ifclear + + @smallexample + @ifclear vms + $ gnatname -P/home/me/proj -x "*_nt_body.ada" + -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" + @end ifclear + @ifset vms + $ gnatname /PROJECT_FILE=[HOME.ME]PROJ + /EXCLUDED_PATTERN=*_nt_body.ada + /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS]) + /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*" + @end ifset + @end smallexample + + Note that several switches @option{^-d^/SOURCE_DIRS^} may be used, + even in conjunction with one or several switches + @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern + are used in this example. + + + @c ***************************************** + @c * G N A T P r o j e c t M a n a g e r * + @c ***************************************** + @node GNAT Project Manager + @chapter GNAT Project Manager + + @menu + * Introduction:: + * Examples of Project Files:: + * Project File Syntax:: + * Objects and Sources in Project Files:: + * Importing Projects:: + * Project Extension:: + * External References in Project Files:: + * Packages in Project Files:: + * Variables from Imported Projects:: + * Naming Schemes:: + * Library Projects:: + * Using Third-Party Libraries through Projects:: + * Stand-alone Library Projects:: + * Switches Related to Project Files:: + * Tools Supporting Project Files:: + * An Extended Example:: + * Project File Complete Syntax:: + @end menu + + @c **************** + @c * Introduction * + @c **************** + + @node Introduction + @section Introduction + + @noindent + This chapter describes GNAT's @emph{Project Manager}, a facility that allows + you to manage complex builds involving a number of source files, directories, + and compilation options for different system configurations. In particular, + project files allow you to specify: + @itemize @bullet + @item + The directory or set of directories containing the source files, and/or the + names of the specific source files themselves + @item + The directory in which the compiler's output + (@file{ALI} files, object files, tree files) is to be placed + @item + The directory in which the executable programs is to be placed + @item + ^Switch^Switch^ settings for any of the project-enabled tools + (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref}, + @code{gnatfind}); you can apply these settings either globally or to individual + compilation units. + @item + The source files containing the main subprogram(s) to be built + @item + The source programming language(s) (currently Ada and/or C) + @item + Source file naming conventions; you can specify these either globally or for + individual compilation units + @end itemize + + @menu + * Project Files:: + @end menu + + @node Project Files + @subsection Project Files + + @noindent + Project files are written in a syntax close to that of Ada, using familiar + notions such as packages, context clauses, declarations, default values, + assignments, and inheritance. Finally, project files can be built + hierarchically from other project files, simplifying complex system + integration and project reuse. + + A @dfn{project} is a specific set of values for various compilation properties. + The settings for a given project are described by means of + a @dfn{project file}, which is a text file written in an Ada-like syntax. + Property values in project files are either strings or lists of strings. + Properties that are not explicitly set receive default values. A project + file may interrogate the values of @dfn{external variables} (user-defined + command-line switches or environment variables), and it may specify property + settings conditionally, based on the value of such variables. + + In simple cases, a project's source files depend only on other source files + in the same project, or on the predefined libraries. (@emph{Dependence} is + used in + the Ada technical sense; as in one Ada unit @code{with}ing another.) However, + the Project Manager also allows more sophisticated arrangements, + where the source files in one project depend on source files in other + projects: + @itemize @bullet + @item + One project can @emph{import} other projects containing needed source files. + @item + You can organize GNAT projects in a hierarchy: a @emph{child} project + can extend a @emph{parent} project, inheriting the parent's source files and + optionally overriding any of them with alternative versions + @end itemize + + @noindent + More generally, the Project Manager lets you structure large development + efforts into hierarchical subsystems, where build decisions are delegated + to the subsystem level, and thus different compilation environments + (^switch^switch^ settings) used for different subsystems. + + The Project Manager is invoked through the + @option{^-P^/PROJECT_FILE=^@emph{projectfile}} + switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver. + @ifclear vms + There may be zero, one or more spaces between @option{-P} and + @option{@emph{projectfile}}. + @end ifclear + If you want to define (on the command line) an external variable that is + queried by the project file, you must use the + @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch. + The Project Manager parses and interprets the project file, and drives the + invoked tool based on the project settings. + + The Project Manager supports a wide range of development strategies, + for systems of all sizes. Here are some typical practices that are + easily handled: + @itemize @bullet + @item + Using a common set of source files, but generating object files in different + directories via different ^switch^switch^ settings + @item + Using a mostly-shared set of source files, but with different versions of + some unit or units + @end itemize + + @noindent + The destination of an executable can be controlled inside a project file + using the @option{^-o^-o^} + ^switch^switch^. + In the absence of such a ^switch^switch^ either inside + the project file or on the command line, any executable files generated by + @command{gnatmake} are placed in the directory @code{Exec_Dir} specified + in the project file. If no @code{Exec_Dir} is specified, they will be placed + in the object directory of the project. + + You can use project files to achieve some of the effects of a source + versioning system (for example, defining separate projects for + the different sets of sources that comprise different releases) but the + Project Manager is independent of any source configuration management tools + that might be used by the developers. + + The next section introduces the main features of GNAT's project facility + through a sequence of examples; subsequent sections will present the syntax + and semantics in more detail. A more formal description of the project + facility appears in the GNAT Reference Manual. + + @c ***************************** + @c * Examples of Project Files * + @c ***************************** + + @node Examples of Project Files + @section Examples of Project Files + @noindent + This section illustrates some of the typical uses of project files and + explains their basic structure and behavior. + + @menu + * Common Sources with Different ^Switches^Switches^ and Directories:: + * Using External Variables:: + * Importing Other Projects:: + * Extending a Project:: + @end menu + + @node Common Sources with Different ^Switches^Switches^ and Directories + @subsection Common Sources with Different ^Switches^Switches^ and Directories + + @menu + * Source Files:: + * Specifying the Object Directory:: + * Specifying the Exec Directory:: + * Project File Packages:: + * Specifying ^Switch^Switch^ Settings:: + * Main Subprograms:: + * Executable File Names:: + * Source File Naming Conventions:: + * Source Language(s):: + @end menu + + @noindent + Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and + @file{proc.adb} are in the @file{/common} directory. The file + @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s + package @code{Pack}. We want to compile these source files under two sets + of ^switches^switches^: + @itemize @bullet + @item + When debugging, we want to pass the @option{-g} switch to @command{gnatmake}, + and the @option{^-gnata^-gnata^}, + @option{^-gnato^-gnato^}, + and @option{^-gnatE^-gnatE^} switches to the + compiler; the compiler's output is to appear in @file{/common/debug} + @item + When preparing a release version, we want to pass the @option{^-O2^O2^} switch + to the compiler; the compiler's output is to appear in @file{/common/release} + @end itemize + + @noindent + The GNAT project files shown below, respectively @file{debug.gpr} and + @file{release.gpr} in the @file{/common} directory, achieve these effects. + + Schematically: + @smallexample + @group + ^/common^[COMMON]^ + debug.gpr + release.gpr + pack.ads + pack.adb + proc.adb + @end group + @group + ^/common/debug^[COMMON.DEBUG]^ + proc.ali, proc.o + pack.ali, pack.o + @end group + @group + ^/common/release^[COMMON.RELEASE]^ + proc.ali, proc.o + pack.ali, pack.o + @end group + @end smallexample + Here are the corresponding project files: + + @smallexample @c projectfile + @group + project Debug is + for Object_Dir use "debug"; + for Main use ("proc"); + + package Builder is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-g^-g^"); + for Executable ("proc.adb") use "proc1"; + end Builder; + @end group + + @group + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("-fstack-check", + "^-gnata^-gnata^", + "^-gnato^-gnato^", + "^-gnatE^-gnatE^"); + end Compiler; + end Debug; + @end group + @end smallexample + + @smallexample @c projectfile + @group + project Release is + for Object_Dir use "release"; + for Exec_Dir use "."; + for Main use ("proc"); + + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-O2^-O2^"); + end Compiler; + end Release; + @end group + @end smallexample + + @noindent + The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case + insensitive), and analogously the project defined by @file{release.gpr} is + @code{"Release"}. For consistency the file should have the same name as the + project, and the project file's extension should be @code{"gpr"}. These + conventions are not required, but a warning is issued if they are not followed. + + If the current directory is @file{^/temp^[TEMP]^}, then the command + @smallexample + gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^ + @end smallexample + + @noindent + generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^}, + as well as the @code{^proc1^PROC1.EXE^} executable, + using the ^switch^switch^ settings defined in the project file. + + Likewise, the command + @smallexample + gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^ + @end smallexample + + @noindent + generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^}, + and the @code{^proc^PROC.EXE^} + executable in @file{^/common^[COMMON]^}, + using the ^switch^switch^ settings from the project file. + + @node Source Files + @unnumberedsubsubsec Source Files + + @noindent + If a project file does not explicitly specify a set of source directories or + a set of source files, then by default the project's source files are the + Ada source files in the project file directory. Thus @file{pack.ads}, + @file{pack.adb}, and @file{proc.adb} are the source files for both projects. + + @node Specifying the Object Directory + @unnumberedsubsubsec Specifying the Object Directory + + @noindent + Several project properties are modeled by Ada-style @emph{attributes}; + a property is defined by supplying the equivalent of an Ada attribute + definition clause in the project file. + A project's object directory is another such a property; the corresponding + attribute is @code{Object_Dir}, and its value is also a string expression, + specified either as absolute or relative. In the later case, + it is relative to the project file directory. Thus the compiler's + output is directed to @file{^/common/debug^[COMMON.DEBUG]^} + (for the @code{Debug} project) + and to @file{^/common/release^[COMMON.RELEASE]^} + (for the @code{Release} project). + If @code{Object_Dir} is not specified, then the default is the project file + directory itself. + + @node Specifying the Exec Directory + @unnumberedsubsubsec Specifying the Exec Directory + + @noindent + A project's exec directory is another property; the corresponding + attribute is @code{Exec_Dir}, and its value is also a string expression, + either specified as relative or absolute. If @code{Exec_Dir} is not specified, + then the default is the object directory (which may also be the project file + directory if attribute @code{Object_Dir} is not specified). Thus the executable + is placed in @file{^/common/debug^[COMMON.DEBUG]^} + for the @code{Debug} project (attribute @code{Exec_Dir} not specified) + and in @file{^/common^[COMMON]^} for the @code{Release} project. + + @node Project File Packages + @unnumberedsubsubsec Project File Packages + + @noindent + A GNAT tool that is integrated with the Project Manager is modeled by a + corresponding package in the project file. In the example above, + The @code{Debug} project defines the packages @code{Builder} + (for @command{gnatmake}) and @code{Compiler}; + the @code{Release} project defines only the @code{Compiler} package. + + The Ada-like package syntax is not to be taken literally. Although packages in + project files bear a surface resemblance to packages in Ada source code, the + notation is simply a way to convey a grouping of properties for a named + entity. Indeed, the package names permitted in project files are restricted + to a predefined set, corresponding to the project-aware tools, and the contents + of packages are limited to a small set of constructs. + The packages in the example above contain attribute definitions. + + @node Specifying ^Switch^Switch^ Settings + @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings + + @noindent + ^Switch^Switch^ settings for a project-aware tool can be specified through + attributes in the package that corresponds to the tool. + The example above illustrates one of the relevant attributes, + @code{^Default_Switches^Default_Switches^}, which is defined in packages + in both project files. + Unlike simple attributes like @code{Source_Dirs}, + @code{^Default_Switches^Default_Switches^} is + known as an @emph{associative array}. When you define this attribute, you must + supply an ``index'' (a literal string), and the effect of the attribute + definition is to set the value of the array at the specified index. + For the @code{^Default_Switches^Default_Switches^} attribute, + the index is a programming language (in our case, Ada), + and the value specified (after @code{use}) must be a list + of string expressions. + + The attributes permitted in project files are restricted to a predefined set. + Some may appear at project level, others in packages. + For any attribute that is an associative array, the index must always be a + literal string, but the restrictions on this string (e.g., a file name or a + language name) depend on the individual attribute. + Also depending on the attribute, its specified value will need to be either a + string or a string list. + + In the @code{Debug} project, we set the switches for two tools, + @command{gnatmake} and the compiler, and thus we include the two corresponding + packages; each package defines the @code{^Default_Switches^Default_Switches^} + attribute with index @code{"Ada"}. + Note that the package corresponding to + @command{gnatmake} is named @code{Builder}. The @code{Release} project is + similar, but only includes the @code{Compiler} package. + + In project @code{Debug} above, the ^switches^switches^ starting with + @option{-gnat} that are specified in package @code{Compiler} + could have been placed in package @code{Builder}, since @command{gnatmake} + transmits all such ^switches^switches^ to the compiler. + + @node Main Subprograms + @unnumberedsubsubsec Main Subprograms + + @noindent + One of the specifiable properties of a project is a list of files that contain + main subprograms. This property is captured in the @code{Main} attribute, + whose value is a list of strings. If a project defines the @code{Main} + attribute, it is not necessary to identify the main subprogram(s) when + invoking @command{gnatmake} (see @ref{gnatmake and Project Files}). + + @node Executable File Names + @unnumberedsubsubsec Executable File Names + + @noindent + By default, the executable file name corresponding to a main source is + deducted from the main source file name. Through the attributes + @code{Executable} and @code{Executable_Suffix} of package @code{Builder}, + it is possible to change this default. + In project @code{Debug} above, the executable file name + for main source @file{^proc.adb^PROC.ADB^} is + @file{^proc1^PROC1.EXE^}. + Attribute @code{Executable_Suffix}, when specified, may change the suffix + of the the executable files, when no attribute @code{Executable} applies: + its value replace the platform-specific executable suffix. + Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to + specify a non default executable file name when several mains are built at once + in a single @command{gnatmake} command. + + @node Source File Naming Conventions + @unnumberedsubsubsec Source File Naming Conventions + + @noindent + Since the project files above do not specify any source file naming + conventions, the GNAT defaults are used. The mechanism for defining source + file naming conventions -- a package named @code{Naming} -- + is described below (@pxref{Naming Schemes}). + + @node Source Language(s) + @unnumberedsubsubsec Source Language(s) + + @noindent + Since the project files do not specify a @code{Languages} attribute, by + default the GNAT tools assume that the language of the project file is Ada. + More generally, a project can comprise source files + in Ada, C, and/or other languages. + + @node Using External Variables + @subsection Using External Variables + + @noindent + Instead of supplying different project files for debug and release, we can + define a single project file that queries an external variable (set either + on the command line or via an ^environment variable^logical name^) in order to + conditionally define the appropriate settings. Again, assume that the + source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are + located in directory @file{^/common^[COMMON]^}. The following project file, + @file{build.gpr}, queries the external variable named @code{STYLE} and + defines an object directory and ^switch^switch^ settings based on whether + the value is @code{"deb"} (debug) or @code{"rel"} (release), and where + the default is @code{"deb"}. + + @smallexample @c projectfile + @group + project Build is + for Main use ("proc"); + + type Style_Type is ("deb", "rel"); + Style : Style_Type := external ("STYLE", "deb"); + + case Style is + when "deb" => + for Object_Dir use "debug"; + + when "rel" => + for Object_Dir use "release"; + for Exec_Dir use "."; + end case; + @end group + + @group + package Builder is + + case Style is + when "deb" => + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-g^-g^"); + for Executable ("proc") use "proc1"; + end case; + + end Builder; + @end group + + @group + package Compiler is + + case Style is + when "deb" => + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-gnata^-gnata^", + "^-gnato^-gnato^", + "^-gnatE^-gnatE^"); + + when "rel" => + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-O2^-O2^"); + end case; + + end Compiler; + + end Build; + @end group + @end smallexample + + @noindent + @code{Style_Type} is an example of a @emph{string type}, which is the project + file analog of an Ada enumeration type but whose components are string literals + rather than identifiers. @code{Style} is declared as a variable of this type. + + The form @code{external("STYLE", "deb")} is known as an + @emph{external reference}; its first argument is the name of an + @emph{external variable}, and the second argument is a default value to be + used if the external variable doesn't exist. You can define an external + variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch, + or you can use ^an environment variable^a logical name^ + as an external variable. + + Each @code{case} construct is expanded by the Project Manager based on the + value of @code{Style}. Thus the command + @ifclear vms + @smallexample + gnatmake -P/common/build.gpr -XSTYLE=deb + @end smallexample + @end ifclear + + @ifset vms + @smallexample + gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb + @end smallexample + @end ifset + + @noindent + is equivalent to the @command{gnatmake} invocation using the project file + @file{debug.gpr} in the earlier example. So is the command + @smallexample + gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^ + @end smallexample + + @noindent + since @code{"deb"} is the default for @code{STYLE}. + + Analogously, + + @ifclear vms + @smallexample + gnatmake -P/common/build.gpr -XSTYLE=rel + @end smallexample + @end ifclear + + @ifset vms + @smallexample + GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel + @end smallexample + @end ifset + + @noindent + is equivalent to the @command{gnatmake} invocation using the project file + @file{release.gpr} in the earlier example. + + @node Importing Other Projects + @subsection Importing Other Projects + + @noindent + A compilation unit in a source file in one project may depend on compilation + units in source files in other projects. To compile this unit under + control of a project file, the + dependent project must @emph{import} the projects containing the needed source + files. + This effect is obtained using syntax similar to an Ada @code{with} clause, + but where @code{with}ed entities are strings that denote project files. + + As an example, suppose that the two projects @code{GUI_Proj} and + @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and + @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^} + and @file{^/comm^[COMM]^}, respectively. + Suppose that the source files for @code{GUI_Proj} are + @file{gui.ads} and @file{gui.adb}, and that the source files for + @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of + files is located in its respective project file directory. Schematically: + + @smallexample + @group + ^/gui^[GUI]^ + gui_proj.gpr + gui.ads + gui.adb + @end group + + @group + ^/comm^[COMM]^ + comm_proj.gpr + comm.ads + comm.adb + @end group + @end smallexample + + @noindent + We want to develop an application in directory @file{^/app^[APP]^} that + @code{with} the packages @code{GUI} and @code{Comm}, using the properties of + the corresponding project files (e.g. the ^switch^switch^ settings + and object directory). + Skeletal code for a main procedure might be something like the following: + + @smallexample @c ada + @group + with GUI, Comm; + procedure App_Main is + ... + begin + ... + end App_Main; + @end group + @end smallexample + + @noindent + Here is a project file, @file{app_proj.gpr}, that achieves the desired + effect: + + @smallexample @c projectfile + @group + with "/gui/gui_proj", "/comm/comm_proj"; + project App_Proj is + for Main use ("app_main"); + end App_Proj; + @end group + @end smallexample + + @noindent + Building an executable is achieved through the command: + @smallexample + gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^ + @end smallexample + @noindent + which will generate the @code{^app_main^APP_MAIN.EXE^} executable + in the directory where @file{app_proj.gpr} resides. + + If an imported project file uses the standard extension (@code{^gpr^GPR^}) then + (as illustrated above) the @code{with} clause can omit the extension. + + Our example specified an absolute path for each imported project file. + Alternatively, the directory name of an imported object can be omitted + if either + @itemize @bullet + @item + The imported project file is in the same directory as the importing project + file, or + @item + You have defined ^an environment variable^a logical name^ + that includes the directory containing + the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as + the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of + directory names separated by colons (semicolons on Windows). + @end itemize + + @noindent + Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and + @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written + as follows: + + @smallexample @c projectfile + @group + with "gui_proj", "comm_proj"; + project App_Proj is + for Main use ("app_main"); + end App_Proj; + @end group + @end smallexample + + @noindent + Importing other projects can create ambiguities. + For example, the same unit might be present in different imported projects, or + it might be present in both the importing project and in an imported project. + Both of these conditions are errors. Note that in the current version of + the Project Manager, it is illegal to have an ambiguous unit even if the + unit is never referenced by the importing project. This restriction may be + relaxed in a future release. + + @node Extending a Project + @subsection Extending a Project + + @noindent + In large software systems it is common to have multiple + implementations of a common interface; in Ada terms, multiple versions of a + package body for the same specification. For example, one implementation + might be safe for use in tasking programs, while another might only be used + in sequential applications. This can be modeled in GNAT using the concept + of @emph{project extension}. If one project (the ``child'') @emph{extends} + another project (the ``parent'') then by default all source files of the + parent project are inherited by the child, but the child project can + override any of the parent's source files with new versions, and can also + add new files. This facility is the project analog of a type extension in + Object-Oriented Programming. Project hierarchies are permitted (a child + project may be the parent of yet another project), and a project that + inherits one project can also import other projects. + + As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project + file @file{seq_proj.gpr} as well as the source files @file{pack.ads}, + @file{pack.adb}, and @file{proc.adb}: + + @smallexample + @group + ^/seq^[SEQ]^ + pack.ads + pack.adb + proc.adb + seq_proj.gpr + @end group + @end smallexample + + @noindent + Note that the project file can simply be empty (that is, no attribute or + package is defined): + + @smallexample @c projectfile + @group + project Seq_Proj is + end Seq_Proj; + @end group + @end smallexample + + @noindent + implying that its source files are all the Ada source files in the project + directory. + + Suppose we want to supply an alternate version of @file{pack.adb}, in + directory @file{^/tasking^[TASKING]^}, but use the existing versions of + @file{pack.ads} and @file{proc.adb}. We can define a project + @code{Tasking_Proj} that inherits @code{Seq_Proj}: + + @smallexample + @group + ^/tasking^[TASKING]^ + pack.adb + tasking_proj.gpr + @end group + + @group + project Tasking_Proj extends "/seq/seq_proj" is + end Tasking_Proj; + @end group + @end smallexample + + @noindent + The version of @file{pack.adb} used in a build depends on which project file + is specified. + + Note that we could have obtained the desired behavior using project import + rather than project inheritance; a @code{base} project would contain the + sources for @file{pack.ads} and @file{proc.adb}, a sequential project would + import @code{base} and add @file{pack.adb}, and likewise a tasking project + would import @code{base} and add a different version of @file{pack.adb}. The + choice depends on whether other sources in the original project need to be + overridden. If they do, then project extension is necessary, otherwise, + importing is sufficient. + + @noindent + In a project file that extends another project file, it is possible to + indicate that an inherited source is not part of the sources of the extending + project. This is necessary sometimes when a package spec has been overloaded + and no longer requires a body: in this case, it is necessary to indicate that + the inherited body is not part of the sources of the project, otherwise there + will be a compilation error when compiling the spec. + + For that purpose, the attribute @code{Locally_Removed_Files} is used. + Its value is a string list: a list of file names. + + @smallexample @c @projectfile + project B extends "a" is + for Source_Files use ("pkg.ads"); + -- New spec of Pkg does not need a completion + for Locally_Removed_Files use ("pkg.adb"); + end B; + @end smallexample + + Attribute @code{Locally_Removed_Files} may also be used to check if a source + is still needed: if it is possible to build using @code{gnatmake} when such + a source is put in attribute @code{Locally_Removed_Files} of a project P, then + it is possible to remove the source completely from a system that includes + project P. + + @c *********************** + @c * Project File Syntax * + @c *********************** + + @node Project File Syntax + @section Project File Syntax + + @menu + * Basic Syntax:: + * Packages:: + * Expressions:: + * String Types:: + * Variables:: + * Attributes:: + * Associative Array Attributes:: + * case Constructions:: + @end menu + + @noindent + This section describes the structure of project files. + + A project may be an @emph{independent project}, entirely defined by a single + project file. Any Ada source file in an independent project depends only + on the predefined library and other Ada source files in the same project. + + @noindent + A project may also @dfn{depend on} other projects, in either or both of + the following ways: + @itemize @bullet + @item It may import any number of projects + @item It may extend at most one other project + @end itemize + + @noindent + The dependence relation is a directed acyclic graph (the subgraph reflecting + the ``extends'' relation is a tree). + + A project's @dfn{immediate sources} are the source files directly defined by + that project, either implicitly by residing in the project file's directory, + or explicitly through any of the source-related attributes described below. + More generally, a project @var{proj}'s @dfn{sources} are the immediate sources + of @var{proj} together with the immediate sources (unless overridden) of any + project on which @var{proj} depends (either directly or indirectly). + + @node Basic Syntax + @subsection Basic Syntax + + @noindent + As seen in the earlier examples, project files have an Ada-like syntax. + The minimal project file is: + @smallexample @c projectfile + @group + project Empty is + + end Empty; + @end group + @end smallexample + + @noindent + The identifier @code{Empty} is the name of the project. + This project name must be present after the reserved + word @code{end} at the end of the project file, followed by a semi-colon. + + Any name in a project file, such as the project name or a variable name, + has the same syntax as an Ada identifier. + + The reserved words of project files are the Ada reserved words plus + @code{extends}, @code{external}, and @code{project}. Note that the only Ada + reserved words currently used in project file syntax are: + + @itemize @bullet + @item + @code{case} + @item + @code{end} + @item + @code{for} + @item + @code{is} + @item + @code{others} + @item + @code{package} + @item + @code{renames} + @item + @code{type} + @item + @code{use} + @item + @code{when} + @item + @code{with} + @end itemize + + @noindent + Comments in project files have the same syntax as in Ada, two consecutives + hyphens through the end of the line. + + @node Packages + @subsection Packages + + @noindent + A project file may contain @emph{packages}. The name of a package must be one + of the identifiers from the following list. A package + with a given name may only appear once in a project file. Package names are + case insensitive. The following package names are legal: + + @itemize @bullet + @item + @code{Naming} + @item + @code{Builder} + @item + @code{Compiler} + @item + @code{Binder} + @item + @code{Linker} + @item + @code{Finder} + @item + @code{Cross_Reference} + @item + @code{Eliminate} + @item + @code{gnatls} + @item + @code{gnatstub} + @item + @code{IDE} + @end itemize + + @noindent + In its simplest form, a package may be empty: + + @smallexample @c projectfile + @group + project Simple is + package Builder is + end Builder; + end Simple; + @end group + @end smallexample + + @noindent + A package may contain @emph{attribute declarations}, + @emph{variable declarations} and @emph{case constructions}, as will be + described below. + + When there is ambiguity between a project name and a package name, + the name always designates the project. To avoid possible confusion, it is + always a good idea to avoid naming a project with one of the + names allowed for packages or any name that starts with @code{gnat}. + + @node Expressions + @subsection Expressions + + @noindent + An @emph{expression} is either a @emph{string expression} or a + @emph{string list expression}. + + A @emph{string expression} is either a @emph{simple string expression} or a + @emph{compound string expression}. + + A @emph{simple string expression} is one of the following: + @itemize @bullet + @item A literal string; e.g.@code{"comm/my_proj.gpr"} + @item A string-valued variable reference (see @ref{Variables}) + @item A string-valued attribute reference (see @ref{Attributes}) + @item An external reference (see @ref{External References in Project Files}) + @end itemize + + @noindent + A @emph{compound string expression} is a concatenation of string expressions, + using the operator @code{"&"} + @smallexample + Path & "/" & File_Name & ".ads" + @end smallexample + + @noindent + A @emph{string list expression} is either a + @emph{simple string list expression} or a + @emph{compound string list expression}. + + A @emph{simple string list expression} is one of the following: + @itemize @bullet + @item A parenthesized list of zero or more string expressions, + separated by commas + @smallexample + File_Names := (File_Name, "gnat.adc", File_Name & ".orig"); + Empty_List := (); + @end smallexample + @item A string list-valued variable reference + @item A string list-valued attribute reference + @end itemize + + @noindent + A @emph{compound string list expression} is the concatenation (using + @code{"&"}) of a simple string list expression and an expression. Note that + each term in a compound string list expression, except the first, may be + either a string expression or a string list expression. + + @smallexample @c projectfile + @group + File_Name_List := () & File_Name; -- One string in this list + Extended_File_Name_List := File_Name_List & (File_Name & ".orig"); + -- Two strings + Big_List := File_Name_List & Extended_File_Name_List; + -- Concatenation of two string lists: three strings + Illegal_List := "gnat.adc" & Extended_File_Name_List; + -- Illegal: must start with a string list + @end group + @end smallexample + + @node String Types + @subsection String Types + + @noindent + A @emph{string type declaration} introduces a discrete set of string literals. + If a string variable is declared to have this type, its value + is restricted to the given set of literals. + + Here is an example of a string type declaration: + + @smallexample @c projectfile + type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS"); + @end smallexample + + @noindent + Variables of a string type are called @emph{typed variables}; all other + variables are called @emph{untyped variables}. Typed variables are + particularly useful in @code{case} constructions, to support conditional + attribute declarations. + (see @ref{case Constructions}). + + The string literals in the list are case sensitive and must all be different. + They may include any graphic characters allowed in Ada, including spaces. + + A string type may only be declared at the project level, not inside a package. + + A string type may be referenced by its name if it has been declared in the same + project file, or by an expanded name whose prefix is the name of the project + in which it is declared. + + @node Variables + @subsection Variables + + @noindent + A variable may be declared at the project file level, or within a package. + Here are some examples of variable declarations: + + @smallexample @c projectfile + @group + This_OS : OS := external ("OS"); -- a typed variable declaration + That_OS := "GNU/Linux"; -- an untyped variable declaration + @end group + @end smallexample + + @noindent + The syntax of a @emph{typed variable declaration} is identical to the Ada + syntax for an object declaration. By contrast, the syntax of an untyped + variable declaration is identical to an Ada assignment statement. In fact, + variable declarations in project files have some of the characteristics of + an assignment, in that successive declarations for the same variable are + allowed. Untyped variable declarations do establish the expected kind of the + variable (string or string list), and successive declarations for it must + respect the initial kind. + + @noindent + A string variable declaration (typed or untyped) declares a variable + whose value is a string. This variable may be used as a string expression. + @smallexample @c projectfile + File_Name := "readme.txt"; + Saved_File_Name := File_Name & ".saved"; + @end smallexample + + @noindent + A string list variable declaration declares a variable whose value is a list + of strings. The list may contain any number (zero or more) of strings. + + @smallexample @c projectfile + Empty_List := (); + List_With_One_Element := ("^-gnaty^-gnaty^"); + List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^"; + Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada" + "pack2.ada", "util_.ada", "util.ada"); + @end smallexample + + @noindent + The same typed variable may not be declared more than once at project level, + and it may not be declared more than once in any package; it is in effect + a constant. + + The same untyped variable may be declared several times. Declarations are + elaborated in the order in which they appear, so the new value replaces + the old one, and any subsequent reference to the variable uses the new value. + However, as noted above, if a variable has been declared as a string, all + subsequent + declarations must give it a string value. Similarly, if a variable has + been declared as a string list, all subsequent declarations + must give it a string list value. + + A @emph{variable reference} may take several forms: + + @itemize @bullet + @item The simple variable name, for a variable in the current package (if any) + or in the current project + @item An expanded name, whose prefix is a context name. + @end itemize + + @noindent + A @emph{context} may be one of the following: + + @itemize @bullet + @item The name of an existing package in the current project + @item The name of an imported project of the current project + @item The name of an ancestor project (i.e., a project extended by the current + project, either directly or indirectly) + @item An expanded name whose prefix is an imported/parent project name, and + whose selector is a package name in that project. + @end itemize + + @noindent + A variable reference may be used in an expression. + + @node Attributes + @subsection Attributes + + @noindent + A project (and its packages) may have @emph{attributes} that define + the project's properties. Some attributes have values that are strings; + others have values that are string lists. + + There are two categories of attributes: @emph{simple attributes} + and @emph{associative arrays} (see @ref{Associative Array Attributes}). + + Legal project attribute names, and attribute names for each legal package are + listed below. Attributes names are case-insensitive. + + The following attributes are defined on projects (all are simple attributes): + + @multitable @columnfractions .4 .3 + @item @emph{Attribute Name} + @tab @emph{Value} + @item @code{Source_Files} + @tab string list + @item @code{Source_Dirs} + @tab string list + @item @code{Source_List_File} + @tab string + @item @code{Object_Dir} + @tab string + @item @code{Exec_Dir} + @tab string + @item @code{Locally_Removed_Files} + @tab string list + @item @code{Main} + @tab string list + @item @code{Languages} + @tab string list + @item @code{Main_Language} + @tab string + @item @code{Library_Dir} + @tab string + @item @code{Library_Name} + @tab string + @item @code{Library_Kind} + @tab string + @item @code{Library_Version} + @tab string + @item @code{Library_Interface} + @tab string + @item @code{Library_Auto_Init} + @tab string + @item @code{Library_Options} + @tab string list + @item @code{Library_GCC} + @tab string + @end multitable + + @noindent + The following attributes are defined for package @code{Naming} + (see @ref{Naming Schemes}): + + @multitable @columnfractions .4 .2 .2 .2 + @item Attribute Name @tab Category @tab Index @tab Value + @item @code{Spec_Suffix} + @tab associative array + @tab language name + @tab string + @item @code{Body_Suffix} + @tab associative array + @tab language name + @tab string + @item @code{Separate_Suffix} + @tab simple attribute + @tab n/a + @tab string + @item @code{Casing} + @tab simple attribute + @tab n/a + @tab string + @item @code{Dot_Replacement} + @tab simple attribute + @tab n/a + @tab string + @item @code{Spec} + @tab associative array + @tab Ada unit name + @tab string + @item @code{Body} + @tab associative array + @tab Ada unit name + @tab string + @item @code{Specification_Exceptions} + @tab associative array + @tab language name + @tab string list + @item @code{Implementation_Exceptions} + @tab associative array + @tab language name + @tab string list + @end multitable + + @noindent + The following attributes are defined for packages @code{Builder}, + @code{Compiler}, @code{Binder}, + @code{Linker}, @code{Cross_Reference}, and @code{Finder} + (see @ref{^Switches^Switches^ and Project Files}). + + @multitable @columnfractions .4 .2 .2 .2 + @item Attribute Name @tab Category @tab Index @tab Value + @item @code{^Default_Switches^Default_Switches^} + @tab associative array + @tab language name + @tab string list + @item @code{^Switches^Switches^} + @tab associative array + @tab file name + @tab string list + @end multitable + + @noindent + In addition, package @code{Compiler} has a single string attribute + @code{Local_Configuration_Pragmas} and package @code{Builder} has a single + string attribute @code{Global_Configuration_Pragmas}. + + @noindent + Each simple attribute has a default value: the empty string (for string-valued + attributes) and the empty list (for string list-valued attributes). + + An attribute declaration defines a new value for an attribute. + + Examples of simple attribute declarations: + + @smallexample @c projectfile + for Object_Dir use "objects"; + for Source_Dirs use ("units", "test/drivers"); + @end smallexample + + @noindent + The syntax of a @dfn{simple attribute declaration} is similar to that of an + attribute definition clause in Ada. + + Attributes references may be appear in expressions. + The general form for such a reference is @code{'}: + Associative array attributes are functions. Associative + array attribute references must have an argument that is a string literal. + + Examples are: + + @smallexample @c projectfile + project'Object_Dir + Naming'Dot_Replacement + Imported_Project'Source_Dirs + Imported_Project.Naming'Casing + Builder'^Default_Switches^Default_Switches^("Ada") + @end smallexample + + @noindent + The prefix of an attribute may be: + @itemize @bullet + @item @code{project} for an attribute of the current project + @item The name of an existing package of the current project + @item The name of an imported project + @item The name of a parent project that is extended by the current project + @item An expanded name whose prefix is imported/parent project name, + and whose selector is a package name + @end itemize + + @noindent + Example: + @smallexample @c projectfile + @group + project Prj is + for Source_Dirs use project'Source_Dirs & "units"; + for Source_Dirs use project'Source_Dirs & "test/drivers" + end Prj; + @end group + @end smallexample + + @noindent + In the first attribute declaration, initially the attribute @code{Source_Dirs} + has the default value: an empty string list. After this declaration, + @code{Source_Dirs} is a string list of one element: @code{"units"}. + After the second attribute declaration @code{Source_Dirs} is a string list of + two elements: @code{"units"} and @code{"test/drivers"}. + + Note: this example is for illustration only. In practice, + the project file would contain only one attribute declaration: + + @smallexample @c projectfile + for Source_Dirs use ("units", "test/drivers"); + @end smallexample + + @node Associative Array Attributes + @subsection Associative Array Attributes + + @noindent + Some attributes are defined as @emph{associative arrays}. An associative + array may be regarded as a function that takes a string as a parameter + and delivers a string or string list value as its result. + + Here are some examples of single associative array attribute associations: + + @smallexample @c projectfile + for Body ("main") use "Main.ada"; + for ^Switches^Switches^ ("main.ada") + use ("^-v^-v^", + "^-gnatv^-gnatv^"); + for ^Switches^Switches^ ("main.ada") + use Builder'^Switches^Switches^ ("main.ada") + & "^-g^-g^"; + @end smallexample + + @noindent + Like untyped variables and simple attributes, associative array attributes + may be declared several times. Each declaration supplies a new value for the + attribute, and replaces the previous setting. + + @noindent + An associative array attribute may be declared as a full associative array + declaration, with the value of the same attribute in an imported or extended + project. + + @smallexample @c projectfile + package Builder is + for Default_Switches use Default.Builder'Default_Switches; + end Builder; + @end smallexample + + @noindent + In this example, @code{Default} must be either an project imported by the + current project, or the project that the current project extends. If the + attribute is in a package (in this case, in package @code{Builder}), the same + package needs to be specified. + + @noindent + A full associative array declaration replaces any other declaration for the + attribute, including other full associative array declaration. Single + associative array associations may be declare after a full associative + declaration, modifying the value for a single association of the attribute. + + @node case Constructions + @subsection @code{case} Constructions + + @noindent + A @code{case} construction is used in a project file to effect conditional + behavior. + Here is a typical example: + + @smallexample @c projectfile + @group + project MyProj is + type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS"); + + OS : OS_Type := external ("OS", "GNU/Linux"); + @end group + + @group + package Compiler is + case OS is + when "GNU/Linux" | "Unix" => + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-gnath^-gnath^"); + when "NT" => + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-gnatP^-gnatP^"); + when others => + end case; + end Compiler; + end MyProj; + @end group + @end smallexample + + @noindent + The syntax of a @code{case} construction is based on the Ada case statement + (although there is no @code{null} construction for empty alternatives). + + The case expression must a typed string variable. + Each alternative comprises the reserved word @code{when}, either a list of + literal strings separated by the @code{"|"} character or the reserved word + @code{others}, and the @code{"=>"} token. + Each literal string must belong to the string type that is the type of the + case variable. + An @code{others} alternative, if present, must occur last. + + After each @code{=>}, there are zero or more constructions. The only + constructions allowed in a case construction are other case constructions and + attribute declarations. String type declarations, variable declarations and + package declarations are not allowed. + + The value of the case variable is often given by an external reference + (see @ref{External References in Project Files}). + + @c **************************************** + @c * Objects and Sources in Project Files * + @c **************************************** + + @node Objects and Sources in Project Files + @section Objects and Sources in Project Files + + @menu + * Object Directory:: + * Exec Directory:: + * Source Directories:: + * Source File Names:: + @end menu + + @noindent + Each project has exactly one object directory and one or more source + directories. The source directories must contain at least one source file, + unless the project file explicitly specifies that no source files are present + (see @ref{Source File Names}). + + @node Object Directory + @subsection Object Directory + + @noindent + The object directory for a project is the directory containing the compiler's + output (such as @file{ALI} files and object files) for the project's immediate + sources. + + The object directory is given by the value of the attribute @code{Object_Dir} + in the project file. + + @smallexample @c projectfile + for Object_Dir use "objects"; + @end smallexample + + @noindent + The attribute @var{Object_Dir} has a string value, the path name of the object + directory. The path name may be absolute or relative to the directory of the + project file. This directory must already exist, and be readable and writable. + + By default, when the attribute @code{Object_Dir} is not given an explicit value + or when its value is the empty string, the object directory is the same as the + directory containing the project file. + + @node Exec Directory + @subsection Exec Directory + + @noindent + The exec directory for a project is the directory containing the executables + for the project's main subprograms. + + The exec directory is given by the value of the attribute @code{Exec_Dir} + in the project file. + + @smallexample @c projectfile + for Exec_Dir use "executables"; + @end smallexample + + @noindent + The attribute @var{Exec_Dir} has a string value, the path name of the exec + directory. The path name may be absolute or relative to the directory of the + project file. This directory must already exist, and be writable. + + By default, when the attribute @code{Exec_Dir} is not given an explicit value + or when its value is the empty string, the exec directory is the same as the + object directory of the project file. + + @node Source Directories + @subsection Source Directories + + @noindent + The source directories of a project are specified by the project file + attribute @code{Source_Dirs}. + + This attribute's value is a string list. If the attribute is not given an + explicit value, then there is only one source directory, the one where the + project file resides. + + A @code{Source_Dirs} attribute that is explicitly defined to be the empty list, + as in + + @smallexample @c projectfile + for Source_Dirs use (); + @end smallexample + + @noindent + indicates that the project contains no source files. + + Otherwise, each string in the string list designates one or more + source directories. + + @smallexample @c projectfile + for Source_Dirs use ("sources", "test/drivers"); + @end smallexample + + @noindent + If a string in the list ends with @code{"/**"}, then the directory whose path + name precedes the two asterisks, as well as all its subdirectories + (recursively), are source directories. + + @smallexample @c projectfile + for Source_Dirs use ("/system/sources/**"); + @end smallexample + + @noindent + Here the directory @code{/system/sources} and all of its subdirectories + (recursively) are source directories. + + To specify that the source directories are the directory of the project file + and all of its subdirectories, you can declare @code{Source_Dirs} as follows: + @smallexample @c projectfile + for Source_Dirs use ("./**"); + @end smallexample + + @noindent + Each of the source directories must exist and be readable. + + @node Source File Names + @subsection Source File Names + + @noindent + In a project that contains source files, their names may be specified by the + attributes @code{Source_Files} (a string list) or @code{Source_List_File} + (a string). Source file names never include any directory information. + + If the attribute @code{Source_Files} is given an explicit value, then each + element of the list is a source file name. + + @smallexample @c projectfile + for Source_Files use ("main.adb"); + for Source_Files use ("main.adb", "pack1.ads", "pack2.adb"); + @end smallexample + + @noindent + If the attribute @code{Source_Files} is not given an explicit value, + but the attribute @code{Source_List_File} is given a string value, + then the source file names are contained in the text file whose path name + (absolute or relative to the directory of the project file) is the + value of the attribute @code{Source_List_File}. + + Each line in the file that is not empty or is not a comment + contains a source file name. + + @smallexample @c projectfile + for Source_List_File use "source_list.txt"; + @end smallexample + + @noindent + By default, if neither the attribute @code{Source_Files} nor the attribute + @code{Source_List_File} is given an explicit value, then each file in the + source directories that conforms to the project's naming scheme + (see @ref{Naming Schemes}) is an immediate source of the project. + + A warning is issued if both attributes @code{Source_Files} and + @code{Source_List_File} are given explicit values. In this case, the attribute + @code{Source_Files} prevails. + + Each source file name must be the name of one existing source file + in one of the source directories. + + A @code{Source_Files} attribute whose value is an empty list + indicates that there are no source files in the project. + + If the order of the source directories is known statically, that is if + @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may + be several files with the same source file name. In this case, only the file + in the first directory is considered as an immediate source of the project + file. If the order of the source directories is not known statically, it is + an error to have several files with the same source file name. + + Projects can be specified to have no Ada source + files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty + list, or the @code{"Ada"} may be absent from @code{Languages}: + + @smallexample @c projectfile + for Source_Dirs use (); + for Source_Files use (); + for Languages use ("C", "C++"); + @end smallexample + + @noindent + Otherwise, a project must contain at least one immediate source. + + Projects with no source files are useful as template packages + (see @ref{Packages in Project Files}) for other projects; in particular to + define a package @code{Naming} (see @ref{Naming Schemes}). + + @c **************************** + @c * Importing Projects * + @c **************************** + + @node Importing Projects + @section Importing Projects + + @noindent + An immediate source of a project P may depend on source files that + are neither immediate sources of P nor in the predefined library. + To get this effect, P must @emph{import} the projects that contain the needed + source files. + + @smallexample @c projectfile + @group + with "project1", "utilities.gpr"; + with "/namings/apex.gpr"; + project Main is + ... + @end group + @end smallexample + + @noindent + As can be seen in this example, the syntax for importing projects is similar + to the syntax for importing compilation units in Ada. However, project files + use literal strings instead of names, and the @code{with} clause identifies + project files rather than packages. + + Each literal string is the file name or path name (absolute or relative) of a + project file. If a string is simply a file name, with no path, then its + location is determined by the @emph{project path}: + + @itemize @bullet + @item + If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists, + then the project path includes all the directories in this + ^environment variable^logical name^, plus the directory of the project file. + + @item + If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not + exist, then the project path contains only one directory, namely the one where + the project file is located. + @end itemize + + @noindent + If a relative pathname is used, as in + + @smallexample @c projectfile + with "tests/proj"; + @end smallexample + + @noindent + then the path is relative to the directory where the importing project file is + located. Any symbolic link will be fully resolved in the directory + of the importing project file before the imported project file is examined. + + If the @code{with}'ed project file name does not have an extension, + the default is @file{^.gpr^.GPR^}. If a file with this extension is not found, + then the file name as specified in the @code{with} clause (no extension) will + be used. In the above example, if a file @code{project1.gpr} is found, then it + will be used; otherwise, if a file @code{^project1^PROJECT1^} exists + then it will be used; if neither file exists, this is an error. + + A warning is issued if the name of the project file does not match the + name of the project; this check is case insensitive. + + Any source file that is an immediate source of the imported project can be + used by the immediate sources of the importing project, transitively. Thus + if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate + sources of @code{A} may depend on the immediate sources of @code{C}, even if + @code{A} does not import @code{C} explicitly. However, this is not recommended, + because if and when @code{B} ceases to import @code{C}, some sources in + @code{A} will no longer compile. + + A side effect of this capability is that normally cyclic dependencies are not + permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B} + is not allowed to import @code{A}. However, there are cases when cyclic + dependencies would be beneficial. For these cases, another form of import + between projects exists, the @code{limited with}: a project @code{A} that + imports a project @code{B} with a straigh @code{with} may also be imported, + directly or indirectly, by @code{B} on the condition that imports from @code{B} + to @code{A} include at least one @code{limited with}. + + @smallexample @c 0projectfile + with "../b/b.gpr"; + with "../c/c.gpr"; + project A is + end A; + + limited with "../a/a.gpr"; + project B is + end B; + + with "../d/d.gpr"; + project C is + end C; + + limited with "../a/a.gpr"; + project D is + end D; + @end smallexample + + @noindent + In the above legal example, there are two project cycles: + @itemize @bullet + @item A-> B-> A + @item A -> C -> D -> A + @end itemize + + @noindent + In each of these cycle there is one @code{limited with}: import of @code{A} + from @code{B} and import of @code{A} from @code{D}. + + The difference between straight @code{with} and @code{limited with} is that + the name of a project imported with a @code{limited with} cannot be used in the + project that imports it. In particular, its packages cannot be renamed and + its variables cannot be referred to. + + An exception to the above rules for @code{limited with} is that for the main + project specified to @command{gnatmake} or to the @command{GNAT} driver a + @code{limited with} is equivalent to a straight @code{with}. For example, + in the example above, projects @code{B} and @code{D} could not be main + projects for @command{gnatmake} or to the @command{GNAT} driver, because they + each have a @code{limited with} that is the only one in a cycle of importing + projects. + + @c ********************* + @c * Project Extension * + @c ********************* + + @node Project Extension + @section Project Extension + + @noindent + During development of a large system, it is sometimes necessary to use + modified versions of some of the source files, without changing the original + sources. This can be achieved through the @emph{project extension} facility. + + @smallexample @c projectfile + project Modified_Utilities extends "/baseline/utilities.gpr" is ... + @end smallexample + + @noindent + A project extension declaration introduces an extending project + (the @emph{child}) and a project being extended (the @emph{parent}). + + By default, a child project inherits all the sources of its parent. + However, inherited sources can be overridden: a unit in a parent is hidden + by a unit of the same name in the child. + + Inherited sources are considered to be sources (but not immediate sources) + of the child project; see @ref{Project File Syntax}. + + An inherited source file retains any switches specified in the parent project. + + For example if the project @code{Utilities} contains the specification and the + body of an Ada package @code{Util_IO}, then the project + @code{Modified_Utilities} can contain a new body for package @code{Util_IO}. + The original body of @code{Util_IO} will not be considered in program builds. + However, the package specification will still be found in the project + @code{Utilities}. + + A child project can have only one parent but it may import any number of other + projects. + + A project is not allowed to import directly or indirectly at the same time a + child project and any of its ancestors. + + @c **************************************** + @c * External References in Project Files * + @c **************************************** + + @node External References in Project Files + @section External References in Project Files + + @noindent + A project file may contain references to external variables; such references + are called @emph{external references}. + + An external variable is either defined as part of the environment (an + environment variable in Unix, for example) or else specified on the command + line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch. + If both, then the command line value is used. + + The value of an external reference is obtained by means of the built-in + function @code{external}, which returns a string value. + This function has two forms: + @itemize @bullet + @item @code{external (external_variable_name)} + @item @code{external (external_variable_name, default_value)} + @end itemize + + @noindent + Each parameter must be a string literal. For example: + + @smallexample @c projectfile + external ("USER") + external ("OS", "GNU/Linux") + @end smallexample + + @noindent + In the form with one parameter, the function returns the value of + the external variable given as parameter. If this name is not present in the + environment, the function returns an empty string. + + In the form with two string parameters, the second argument is + the value returned when the variable given as the first argument is not + present in the environment. In the example above, if @code{"OS"} is not + the name of ^an environment variable^a logical name^ and is not passed on + the command line, then the returned value is @code{"GNU/Linux"}. + + An external reference may be part of a string expression or of a string + list expression, and can therefore appear in a variable declaration or + an attribute declaration. + + @smallexample @c projectfile + @group + type Mode_Type is ("Debug", "Release"); + Mode : Mode_Type := external ("MODE"); + case Mode is + when "Debug" => + ... + @end group + @end smallexample + + @c ***************************** + @c * Packages in Project Files * + @c ***************************** + + @node Packages in Project Files + @section Packages in Project Files + + @noindent + A @emph{package} defines the settings for project-aware tools within a + project. + For each such tool one can declare a package; the names for these + packages are preset (see @ref{Packages}). + A package may contain variable declarations, attribute declarations, and case + constructions. + + @smallexample @c projectfile + @group + project Proj is + package Builder is -- used by gnatmake + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-v^-v^", + "^-g^-g^"); + end Builder; + end Proj; + @end group + @end smallexample + + @noindent + The syntax of package declarations mimics that of package in Ada. + + Most of the packages have an attribute + @code{^Default_Switches^Default_Switches^}. + This attribute is an associative array, and its value is a string list. + The index of the associative array is the name of a programming language (case + insensitive). This attribute indicates the ^switch^switch^ + or ^switches^switches^ to be used + with the corresponding tool. + + Some packages also have another attribute, @code{^Switches^Switches^}, + an associative array whose value is a string list. + The index is the name of a source file. + This attribute indicates the ^switch^switch^ + or ^switches^switches^ to be used by the corresponding + tool when dealing with this specific file. + + Further information on these ^switch^switch^-related attributes is found in + @ref{^Switches^Switches^ and Project Files}. + + A package may be declared as a @emph{renaming} of another package; e.g., from + the project file for an imported project. + + @smallexample @c projectfile + @group + with "/global/apex.gpr"; + project Example is + package Naming renames Apex.Naming; + ... + end Example; + @end group + @end smallexample + + @noindent + Packages that are renamed in other project files often come from project files + that have no sources: they are just used as templates. Any modification in the + template will be reflected automatically in all the project files that rename + a package from the template. + + In addition to the tool-oriented packages, you can also declare a package + named @code{Naming} to establish specialized source file naming conventions + (see @ref{Naming Schemes}). + + @c ************************************ + @c * Variables from Imported Projects * + @c ************************************ + + @node Variables from Imported Projects + @section Variables from Imported Projects + + @noindent + An attribute or variable defined in an imported or parent project can + be used in expressions in the importing / extending project. + Such an attribute or variable is denoted by an expanded name whose prefix + is either the name of the project or the expanded name of a package within + a project. + + @smallexample @c projectfile + @group + with "imported"; + project Main extends "base" is + Var1 := Imported.Var; + Var2 := Base.Var & ".new"; + @end group + + @group + package Builder is + for ^Default_Switches^Default_Switches^ ("Ada") + use Imported.Builder.Ada_^Switches^Switches^ & + "^-gnatg^-gnatg^" & + "^-v^-v^"; + end Builder; + @end group + + @group + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use Base.Compiler.Ada_^Switches^Switches^; + end Compiler; + end Main; + @end group + @end smallexample + + @noindent + In this example: + + @itemize @bullet + @item + The value of @code{Var1} is a copy of the variable @code{Var} defined + in the project file @file{"imported.gpr"} + @item + the value of @code{Var2} is a copy of the value of variable @code{Var} + defined in the project file @file{base.gpr}, concatenated with @code{".new"} + @item + attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package + @code{Builder} is a string list that includes in its value a copy of the value + of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package + in project file @file{imported.gpr} plus two new elements: + @option{"^-gnatg^-gnatg^"} + and @option{"^-v^-v^"}; + @item + attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package + @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^} + defined in the @code{Compiler} package in project file @file{base.gpr}, + the project being extended. + @end itemize + + @c ****************** + @c * Naming Schemes * + @c ****************** + + @node Naming Schemes + @section Naming Schemes + + @noindent + Sometimes an Ada software system is ported from a foreign compilation + environment to GNAT, and the file names do not use the default GNAT + conventions. Instead of changing all the file names (which for a variety + of reasons might not be possible), you can define the relevant file + naming scheme in the @code{Naming} package in your project file. + + @noindent + Note that the use of pragmas described in @ref{Alternative + File Naming Schemes} by mean of a configuration pragmas file is not + supported when using project files. You must use the features described + in this paragraph. You can however use specify other configuration + pragmas (see @ref{Specifying Configuration Pragmas}). + + @ifclear vms + For example, the following + package models the Apex file naming rules: + + @smallexample @c projectfile + @group + package Naming is + for Casing use "lowercase"; + for Dot_Replacement use "."; + for Spec_Suffix ("Ada") use ".1.ada"; + for Body_Suffix ("Ada") use ".2.ada"; + end Naming; + @end group + @end smallexample + @end ifclear + + @ifset vms + For example, the following package models the DEC Ada file naming rules: + + @smallexample @c projectfile + @group + package Naming is + for Casing use "lowercase"; + for Dot_Replacement use "__"; + for Spec_Suffix ("Ada") use "_.^ada^ada^"; + for Body_Suffix ("Ada") use ".^ada^ada^"; + end Naming; + @end group + @end smallexample + + @noindent + (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file + names in lower case) + @end ifset + + @noindent + You can define the following attributes in package @code{Naming}: + + @table @code + + @item @var{Casing} + This must be a string with one of the three values @code{"lowercase"}, + @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive. + + @noindent + If @var{Casing} is not specified, then the default is @code{"lowercase"}. + + @item @var{Dot_Replacement} + This must be a string whose value satisfies the following conditions: + + @itemize @bullet + @item It must not be empty + @item It cannot start or end with an alphanumeric character + @item It cannot be a single underscore + @item It cannot start with an underscore followed by an alphanumeric + @item It cannot contain a dot @code{'.'} except if the entire string + is @code{"."} + @end itemize + + @noindent + If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. + + @item @var{Spec_Suffix} + This is an associative array (indexed by the programming language name, case + insensitive) whose value is a string that must satisfy the following + conditions: + + @itemize @bullet + @item It must not be empty + @item It must include at least one dot + @end itemize + @noindent + If @code{Spec_Suffix ("Ada")} is not specified, then the default is + @code{"^.ads^.ADS^"}. + + @item @var{Body_Suffix} + This is an associative array (indexed by the programming language name, case + insensitive) whose value is a string that must satisfy the following + conditions: + + @itemize @bullet + @item It must not be empty + @item It must include at least one dot + @item It cannot end with the same string as @code{Spec_Suffix ("Ada")} + @end itemize + @noindent + If @code{Body_Suffix ("Ada")} is not specified, then the default is + @code{"^.adb^.ADB^"}. + + @item @var{Separate_Suffix} + This must be a string whose value satisfies the same conditions as + @code{Body_Suffix}. + + @noindent + If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same + value as @code{Body_Suffix ("Ada")}. + + @item @var{Spec} + @noindent + You can use the associative array attribute @code{Spec} to define + the source file name for an individual Ada compilation unit's spec. The array + index must be a string literal that identifies the Ada unit (case insensitive). + The value of this attribute must be a string that identifies the file that + contains this unit's spec (case sensitive or insensitive depending on the + operating system). + + @smallexample @c projectfile + for Spec ("MyPack.MyChild") use "mypack.mychild.spec"; + @end smallexample + + @item @var{Body} + + You can use the associative array attribute @code{Body} to + define the source file name for an individual Ada compilation unit's body + (possibly a subunit). The array index must be a string literal that identifies + the Ada unit (case insensitive). The value of this attribute must be a string + that identifies the file that contains this unit's body or subunit (case + sensitive or insensitive depending on the operating system). + + @smallexample @c projectfile + for Body ("MyPack.MyChild") use "mypack.mychild.body"; + @end smallexample + @end table + + @c ******************** + @c * Library Projects * + @c ******************** + + @node Library Projects + @section Library Projects + + @noindent + @emph{Library projects} are projects whose object code is placed in a library. + (Note that this facility is not yet supported on all platforms) + + To create a library project, you need to define in its project file + two project-level attributes: @code{Library_Name} and @code{Library_Dir}. + Additionally, you may define the library-related attributes + @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface}, + @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}. + + The @code{Library_Name} attribute has a string value. There is no restriction + on the name of a library. It is the responsability of the developer to + choose a name that will be accepted by the platform. It is recommanded to + choose names that could be Ada identifiers; such names are almost guaranteed + to be acceptable on all platforms. + + The @code{Library_Dir} attribute has a string value that designates the path + (absolute or relative) of the directory where the library will reside. + It must designate an existing directory, and this directory must be + different from the project's object directory. It also needs to be writable. + + If both @code{Library_Name} and @code{Library_Dir} are specified and + are legal, then the project file defines a library project. The optional + library-related attributes are checked only for such project files. + + The @code{Library_Kind} attribute has a string value that must be one of the + following (case insensitive): @code{"static"}, @code{"dynamic"} or + @code{"relocatable"}. If this attribute is not specified, the library is a + static library, that is an archive of object files that can be potentially + linked into an static executable. Otherwise, the library may be dynamic or + relocatable, that is a library that is loaded only at the start of execution. + Depending on the operating system, there may or may not be a distinction + between dynamic and relocatable libraries. For Unix and VMS Unix there is no + such distinction. + + If you need to build both a static and a dynamic library, you should use two + different object directories, since in some cases some extra code needs to + be generated for the latter. For such cases, it is recommended to either use + two different project files, or a single one which uses external variables + to indicate what kind of library should be build. + + The @code{Library_Version} attribute has a string value whose interpretation + is platform dependent. It has no effect on VMS and Windows. On Unix, it is + used only for dynamic/relocatable libraries as the internal name of the + library (the @code{"soname"}). If the library file name (built from the + @code{Library_Name}) is different from the @code{Library_Version}, then the + library file will be a symbolic link to the actual file whose name will be + @code{Library_Version}. + + Example (on Unix): + + @smallexample @c projectfile + @group + project Plib is + + Version := "1"; + + for Library_Dir use "lib_dir"; + for Library_Name use "dummy"; + for Library_Kind use "relocatable"; + for Library_Version use "libdummy.so." & Version; + + end Plib; + @end group + @end smallexample + + @noindent + Directory @file{lib_dir} will contain the internal library file whose name + will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to + @file{libdummy.so.1}. + + When @command{gnatmake} detects that a project file + is a library project file, it will check all immediate sources of the project + and rebuild the library if any of the sources have been recompiled. + + When a library is built or rebuilt, an attempt is made to delete all + files in the library directory. + All @file{ALI} files will also be copied from the object directory to the + library directory. To build executables, @command{gnatmake} will use the + library rather than the individual object files. The copy of the @file{ALI} + files are made read-only. + + + @c ********************************************** + @c * Using Third-Party Libraries through Projects + @c ********************************************** + @node Using Third-Party Libraries through Projects + @section Using Third-Party Libraries through Projects + + Whether you are exporting your own library to make it available to + clients, or you are using a library provided by a third party, it is + convenient to have project files that automatically set the correct + command line switches for the compiler and linker. + + Such project files are very similar to the library project files; + @xref{Library Projects}. The only difference is that you set the + @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the + directories where, respectively, the sources and the read-only ALI files have + been installed. + + If you need to interface with a set of libraries, as opposed to a + single one, you need to create one library project for each of the + libraries. In addition, a top-level project that imports all these + library projects should be provided, so that the user of your library + has a single @code{with} clause to add to his own projects. + + For instance, let's assume you are providing two static libraries + @file{liba.a} and @file{libb.a}. The user needs to link with + both of these libraries. Each of these is associated with its + own set of header files. Let's assume furthermore that all the + header files for the two libraries have been installed in the same + directory @file{headers}. The @file{ALI} files are found in the same + @file{headers} directory. + + In this case, you should provide the following three projects: + + @smallexample @c projectfile + @group + with "liba", "libb"; + project My_Library is + for Source_Dirs use ("headers"); + for Object_Dir use "headers"; + end My_Library; + @end group + + @group + project Liba is + for Source_Dirs use (); + for Library_Dir use "lib"; + for Library_Name use "a"; + for Library_Kind use "static"; + end Liba; + @end group + + @group + project Libb is + for Source_Dirs use (); + for Library_Dir use "lib"; + for Library_Name use "b"; + for Library_Kind use "static"; + end Libb; + @end group + @end smallexample + + @c ******************************* + @c * Stand-alone Library Projects * + @c ******************************* + + @node Stand-alone Library Projects + @section Stand-alone Library Projects + + @noindent + A Stand-alone Library is a library that contains the necessary code to + elaborate the Ada units that are included in the library. A Stand-alone + Library is suitable to be used in an executable when the main is not + in Ada. However, Stand-alone Libraries may also be used with an Ada main + subprogram. + + A Stand-alone Library Project is a Library Project where the library is + a Stand-alone Library. + + To be a Stand-alone Library Project, in addition to the two attributes + that make a project a Library Project (@code{Library_Name} and + @code{Library_Dir}, see @ref{Library Projects}), the attribute + @code{Library_Interface} must be defined. + + @smallexample @c projectfile + @group + for Library_Dir use "lib_dir"; + for Library_Name use "dummy"; + for Library_Interface use ("int1", "int1.child"); + @end group + @end smallexample + + Attribute @code{Library_Interface} has a non empty string list value, + each string in the list designating a unit contained in an immediate source + of the project file. + + When a Stand-alone Library is built, first the binder is invoked to build + a package whose name depends on the library name + (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above). + This binder-generated package includes initialization and + finalization procedures whose + names depend on the library name (dummyinit and dummyfinal in the example + above). The object corresponding to this package is included in the library. + + A dynamic or relocatable Stand-alone Library is automatically initialized + if automatic initialization of Stand-alone Libraries is supported on the + platform and if attribute @code{Library_Auto_Init} is not specified or + is specified with the value "true". A static Stand-alone Library is never + automatically initialized. + + Single string attribute @code{Library_Auto_Init} may be specified with only + two possible values: "false" or "true" (case-insensitive). Specifying + "false" for attribute @code{Library_Auto_Init} will prevent automatic + initialization of dynamic or relocatable libraries. + + When a non automatically initialized Stand-alone Library is used + in an executable, its initialization procedure must be called before + any service of the library is used. + When the main subprogram is in Ada, it may mean that the initialization + procedure has to be called during elaboration of another package. + + For a Stand-Alone Library, only the @file{ALI} files of the Interface Units + (those that are listed in attribute @code{Library_Interface}) are copied to + the Library Directory. As a consequence, only the Interface Units may be + imported from Ada units outside of the library. If other units are imported, + the binding phase will fail. + + When a Stand-Alone Library is bound, the switches that are specified in + the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are + used in the call to @command{gnatbind}. + + The string list attribute @code{Library_Options} may be used to specified + additional switches to the call to @command{gcc} to link the library. + + The attribute @code{Library_Src_Dir}, may be specified for a + Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a + single string value. Its value must be the path (absolute or relative to the + project directory) of an existing directory. This directory cannot be the + object directory or one of the source directories, but it can be the same as + the library directory. The sources of the Interface + Units of the library, necessary to an Ada client of the library, will be + copied to the designated directory, called Interface Copy directory. + These sources includes the specs of the Interface Units, but they may also + include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always} + are used, or when there is a generic units in the spec. Before the sources + are copied to the Interface Copy directory, an attempt is made to delete all + files in the Interface Copy directory. + + @c ************************************* + @c * Switches Related to Project Files * + @c ************************************* + @node Switches Related to Project Files + @section Switches Related to Project Files + + @noindent + The following switches are used by GNAT tools that support project files: + + @table @option + + @item ^-P^/PROJECT_FILE=^@var{project} + @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files) + Indicates the name of a project file. This project file will be parsed with + the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}}, + if any, and using the external references indicated + by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any. + @ifclear vms + There may zero, one or more spaces between @option{-P} and @var{project}. + @end ifclear + + @noindent + There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line. + + @noindent + Since the Project Manager parses the project file only after all the switches + on the command line are checked, the order of the switches + @option{^-P^/PROJECT_FILE^}, + @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} + or @option{^-X^/EXTERNAL_REFERENCE^} is not significant. + + @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value} + @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files) + Indicates that external variable @var{name} has the value @var{value}. + The Project Manager will use this value for occurrences of + @code{external(name)} when parsing the project file. + + @ifclear vms + @noindent + If @var{name} or @var{value} includes a space, then @var{name=value} should be + put between quotes. + @smallexample + -XOS=NT + -X"user=John Doe" + @end smallexample + @end ifclear + + @noindent + Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously. + If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same + @var{name}, only the last one is used. + + @noindent + An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch + takes precedence over the value of the same name in the environment. + + @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x} + @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files) + @c Previous line uses code vs option command, to stay less than 80 chars + Indicates the verbosity of the parsing of GNAT project files. + + @ifclear vms + @option{-vP0} means Default; + @option{-vP1} means Medium; + @option{-vP2} means High. + @end ifclear + + @ifset vms + There are three possible options for this qualifier: DEFAULT, MEDIUM and + HIGH. + @end ifset + + @noindent + The default is ^Default^DEFAULT^: no output for syntactically correct + project files. + @noindent + If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present, + only the last one is used. + + @end table + + @c ********************************** + @c * Tools Supporting Project Files * + @c ********************************** + + @node Tools Supporting Project Files + @section Tools Supporting Project Files + + @menu + * gnatmake and Project Files:: + * The GNAT Driver and Project Files:: + @ifclear vms + * Glide and Project Files:: + @end ifclear + @end menu + + @node gnatmake and Project Files + @subsection gnatmake and Project Files + + @noindent + This section covers several topics related to @command{gnatmake} and + project files: defining ^switches^switches^ for @command{gnatmake} + and for the tools that it invokes; specifying configuration pragmas; + the use of the @code{Main} attribute; building and rebuilding library project + files. + + @menu + * ^Switches^Switches^ and Project Files:: + * Specifying Configuration Pragmas:: + * Project Files and Main Subprograms:: + * Library Project Files:: + @end menu + + @node ^Switches^Switches^ and Project Files + @subsubsection ^Switches^Switches^ and Project Files + + @ifset vms + It is not currently possible to specify VMS style qualifiers in the project + files; only Unix style ^switches^switches^ may be specified. + @end ifset + + @noindent + For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and + @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^} + attribute, a @code{^Switches^Switches^} attribute, or both; + as their names imply, these ^switch^switch^-related + attributes affect the ^switches^switches^ that are used for each of these GNAT + components when + @command{gnatmake} is invoked. As will be explained below, these + component-specific ^switches^switches^ precede + the ^switches^switches^ provided on the @command{gnatmake} command line. + + The @code{^Default_Switches^Default_Switches^} attribute is an associative + array indexed by language name (case insensitive) whose value is a string list. + For example: + + @smallexample @c projectfile + @group + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-gnaty^-gnaty^", + "^-v^-v^"); + end Compiler; + @end group + @end smallexample + + @noindent + The @code{^Switches^Switches^} attribute is also an associative array, + indexed by a file name (which may or may not be case sensitive, depending + on the operating system) whose value is a string list. For example: + + @smallexample @c projectfile + @group + package Builder is + for ^Switches^Switches^ ("main1.adb") + use ("^-O2^-O2^"); + for ^Switches^Switches^ ("main2.adb") + use ("^-g^-g^"); + end Builder; + @end group + @end smallexample + + @noindent + For the @code{Builder} package, the file names must designate source files + for main subprograms. For the @code{Binder} and @code{Linker} packages, the + file names must designate @file{ALI} or source files for main subprograms. + In each case just the file name without an explicit extension is acceptable. + + For each tool used in a program build (@command{gnatmake}, the compiler, the + binder, and the linker), the corresponding package @dfn{contributes} a set of + ^switches^switches^ for each file on which the tool is invoked, based on the + ^switch^switch^-related attributes defined in the package. + In particular, the ^switches^switches^ + that each of these packages contributes for a given file @var{f} comprise: + + @itemize @bullet + @item + the value of attribute @code{^Switches^Switches^ (@var{f})}, + if it is specified in the package for the given file, + @item + otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")}, + if it is specified in the package. + @end itemize + + @noindent + If neither of these attributes is defined in the package, then the package does + not contribute any ^switches^switches^ for the given file. + + When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise + two sets, in the following order: those contributed for the file + by the @code{Builder} package; + and the switches passed on the command line. + + When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file, + the ^switches^switches^ passed to the tool comprise three sets, + in the following order: + + @enumerate + @item + the applicable ^switches^switches^ contributed for the file + by the @code{Builder} package in the project file supplied on the command line; + + @item + those contributed for the file by the package (in the relevant project file -- + see below) corresponding to the tool; and + + @item + the applicable switches passed on the command line. + @end enumerate + + @noindent + The term @emph{applicable ^switches^switches^} reflects the fact that + @command{gnatmake} ^switches^switches^ may or may not be passed to individual + tools, depending on the individual ^switch^switch^. + + @command{gnatmake} may invoke the compiler on source files from different + projects. The Project Manager will use the appropriate project file to + determine the @code{Compiler} package for each source file being compiled. + Likewise for the @code{Binder} and @code{Linker} packages. + + As an example, consider the following package in a project file: + + @smallexample @c projectfile + @group + project Proj1 is + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-g^-g^"); + for ^Switches^Switches^ ("a.adb") + use ("^-O1^-O1^"); + for ^Switches^Switches^ ("b.adb") + use ("^-O2^-O2^", + "^-gnaty^-gnaty^"); + end Compiler; + end Proj1; + @end group + @end smallexample + + @noindent + If @command{gnatmake} is invoked with this project file, and it needs to + compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then + @file{a.adb} will be compiled with the ^switch^switch^ + @option{^-O1^-O1^}, + @file{b.adb} with ^switches^switches^ + @option{^-O2^-O2^} + and @option{^-gnaty^-gnaty^}, + and @file{c.adb} with @option{^-g^-g^}. + + The following example illustrates the ordering of the ^switches^switches^ + contributed by different packages: + + @smallexample @c projectfile + @group + project Proj2 is + package Builder is + for ^Switches^Switches^ ("main.adb") + use ("^-g^-g^", + "^-O1^-)1^", + "^-f^-f^"); + end Builder; + @end group + + @group + package Compiler is + for ^Switches^Switches^ ("main.adb") + use ("^-O2^-O2^"); + end Compiler; + end Proj2; + @end group + @end smallexample + + @noindent + If you issue the command: + + @smallexample + gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main + @end smallexample + + @noindent + then the compiler will be invoked on @file{main.adb} with the following + sequence of ^switches^switches^ + + @smallexample + ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^ + @end smallexample + + with the last @option{^-O^-O^} + ^switch^switch^ having precedence over the earlier ones; + several other ^switches^switches^ + (such as @option{^-c^-c^}) are added implicitly. + + The ^switches^switches^ + @option{^-g^-g^} + and @option{^-O1^-O1^} are contributed by package + @code{Builder}, @option{^-O2^-O2^} is contributed + by the package @code{Compiler} + and @option{^-O0^-O0^} comes from the command line. + + The @option{^-g^-g^} + ^switch^switch^ will also be passed in the invocation of + @command{Gnatlink.} + + A final example illustrates switch contributions from packages in different + project files: + + @smallexample @c projectfile + @group + project Proj3 is + for Source_Files use ("pack.ads", "pack.adb"); + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-gnata^-gnata^"); + end Compiler; + end Proj3; + @end group + + @group + with "Proj3"; + project Proj4 is + for Source_Files use ("foo_main.adb", "bar_main.adb"); + package Builder is + for ^Switches^Switches^ ("foo_main.adb") + use ("^-s^-s^", + "^-g^-g^"); + end Builder; + end Proj4; + @end group + + @group + -- Ada source file: + with Pack; + procedure Foo_Main is + ... + end Foo_Main; + @end group + @end smallexample + + If the command is + @smallexample + gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato + @end smallexample + + @noindent + then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are + @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and + @option{^-gnato^-gnato^} (passed on the command line). + When the imported package @code{Pack} is compiled, the ^switches^switches^ used + are @option{^-g^-g^} from @code{Proj4.Builder}, + @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler}, + and @option{^-gnato^-gnato^} from the command line. + + @noindent + When using @command{gnatmake} with project files, some ^switches^switches^ or + arguments may be expressed as relative paths. As the working directory where + compilation occurs may change, these relative paths are converted to absolute + paths. For the ^switches^switches^ found in a project file, the relative paths + are relative to the project file directory, for the switches on the command + line, they are relative to the directory where @command{gnatmake} is invoked. + The ^switches^switches^ for which this occurs are: + ^-I^-I^, + ^-A^-A^, + ^-L^-L^, + ^-aO^-aO^, + ^-aL^-aL^, + ^-aI^-aI^, as well as all arguments that are not switches (arguments to + ^switch^switch^ + ^-o^-o^, object files specified in package @code{Linker} or after + -largs on the command line). The exception to this rule is the ^switch^switch^ + ^--RTS=^--RTS=^ for which a relative path argument is never converted. + + @node Specifying Configuration Pragmas + @subsubsection Specifying Configuration Pragmas + + When using @command{gnatmake} with project files, if there exists a file + @file{gnat.adc} that contains configuration pragmas, this file will be + ignored. + + Configuration pragmas can be defined by means of the following attributes in + project files: @code{Global_Configuration_Pragmas} in package @code{Builder} + and @code{Local_Configuration_Pragmas} in package @code{Compiler}. + + Both these attributes are single string attributes. Their values is the path + name of a file containing configuration pragmas. If a path name is relative, + then it is relative to the project directory of the project file where the + attribute is defined. + + When compiling a source, the configuration pragmas used are, in order, + those listed in the file designated by attribute + @code{Global_Configuration_Pragmas} in package @code{Builder} of the main + project file, if it is specified, and those listed in the file designated by + attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of + the project file of the source, if it exists. + + @node Project Files and Main Subprograms + @subsubsection Project Files and Main Subprograms + + @noindent + When using a project file, you can invoke @command{gnatmake} + with one or several main subprograms, by specifying their source files on the + command line. + + @smallexample + gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3 + @end smallexample + + @noindent + Each of these needs to be a source file of the same project, except + when the switch ^-u^/UNIQUE^ is used. + + @noindent + When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the + same project, one of the project in the tree rooted at the project specified + on the command line. The package @code{Builder} of this common project, the + "main project" is the one that is considered by @command{gnatmake}. + + @noindent + When ^-u^/UNIQUE^ is used, the specified source files may be in projects + imported directly or indirectly by the project specified on the command line. + Note that if such a source file is not part of the project specified on the + command line, the ^switches^switches^ found in package @code{Builder} of the + project specified on the command line, if any, that are transmitted + to the compiler will still be used, not those found in the project file of + the source file. + + @noindent + When using a project file, you can also invoke @command{gnatmake} without + explicitly specifying any main, and the effect depends on whether you have + defined the @code{Main} attribute. This attribute has a string list value, + where each element in the list is the name of a source file (the file + extension is optional) that contains a unit that can be a main subprogram. + + If the @code{Main} attribute is defined in a project file as a non-empty + string list and the switch @option{^-u^/UNIQUE^} is not used on the command + line, then invoking @command{gnatmake} with this project file but without any + main on the command line is equivalent to invoking @command{gnatmake} with all + the file names in the @code{Main} attribute on the command line. + + Example: + @smallexample @c projectfile + @group + project Prj is + for Main use ("main1", "main2", "main3"); + end Prj; + @end group + @end smallexample + + @noindent + With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"} + is equivalent to + @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}. + + When the project attribute @code{Main} is not specified, or is specified + as an empty string list, or when the switch @option{-u} is used on the command + line, then invoking @command{gnatmake} with no main on the command line will + result in all immediate sources of the project file being checked, and + potentially recompiled. Depending on the presence of the switch @option{-u}, + sources from other project files on which the immediate sources of the main + project file depend are also checked and potentially recompiled. In other + words, the @option{-u} switch is applied to all of the immediate sources of the + main project file. + + When no main is specified on the command line and attribute @code{Main} exists + and includes several mains, or when several mains are specified on the + command line, the default ^switches^switches^ in package @code{Builder} will + be used for all mains, even if there are specific ^switches^switches^ + specified for one or several mains. + + But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be + the specific ^switches^switches^ for each main, if they are specified. + + @node Library Project Files + @subsubsection Library Project Files + + @noindent + When @command{gnatmake} is invoked with a main project file that is a library + project file, it is not allowed to specify one or more mains on the command + line. + + @noindent + When a library project file is specified, switches ^-b^/ACTION=BIND^ and + ^-l^/ACTION=LINK^ have special meanings. + + @itemize @bullet + @item ^-b^/ACTION=BIND^ is only allwed for stand-alone libraries. It indicates + to @command{gnatmake} that @command{gnatbind} should be invoked for the + library. + + @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates + to @command{gnatmake} that the binder generated file should be compiled + (in the case of a stand-alone library) and that the library should be built. + + @end itemize + + @node The GNAT Driver and Project Files + @subsection The GNAT Driver and Project Files + + @noindent + A number of GNAT tools, other than @command{^gnatmake^gnatmake^} + are project-aware: + @command{^gnatbind^gnatbind^}, + @command{^gnatfind^gnatfind^}, + @command{^gnatlink^gnatlink^}, + @command{^gnatls^gnatls^}, + @command{^gnatelim^gnatelim^}, + and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked + directly with a project file switch (@option{^-P^"-P"^}). + They must be invoked through the @command{gnat} driver. + + The @command{gnat} driver is a front-end that accepts a number of commands and + call the corresponding tool. It has been designed initially for VMS to convert + VMS style qualifiers to Unix style switches, but it is now available to all + the GNAT supported platforms. + + On non VMS platforms, the @command{gnat} driver accepts the following commands + (case insensitive): + + @itemize @bullet + @item + BIND to invoke @command{^gnatbind^gnatbind^} + @item + CHOP to invoke @command{^gnatchop^gnatchop^} + @item + CLEAN to invoke @command{^gnatclean^gnatclean^} + @item + COMP or COMPILE to invoke the compiler + @item + ELIM to invoke @command{^gnatelim^gnatelim^} + @item + FIND to invoke @command{^gnatfind^gnatfind^} + @item + KR or KRUNCH to invoke @command{^gnatkr^gnatkr^} + @item + LINK to invoke @command{^gnatlink^gnatlink^} + @item + LS or LIST to invoke @command{^gnatls^gnatls^} + @item + MAKE to invoke @command{^gnatmake^gnatmake^} + @item + NAME to invoke @command{^gnatname^gnatname^} + @item + PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^} + @item + PP or PRETTY to invoke @command{^gnatpp^gnatpp^} + @item + STUB to invoke @command{^gnatstub^gnatstub^} + @item + XREF to invoke @command{^gnatxref^gnatxref^} + @end itemize + + @noindent + Note that the compiler is invoked using the command + @command{^gnatmake -f -u -c^gnatmake -f -u -c^}. + + @noindent + The command may be followed by switches and arguments for the invoked + tool. + + @smallexample + gnat bind -C main.ali + gnat ls -a main + gnat chop foo.txt + @end smallexample + + @noindent + In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK, + PP or PRETTY and XREF, the project file related switches + (@option{^-P^/PROJECT_FILE^}, + @option{^-X^/EXTERNAL_REFERENCE^} and + @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to + the switches of the invoking tool. + + @noindent + For each of these commands, there is optionally a corresponding package + in the main project. + + @itemize @bullet + @item + package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^}) + + @item + package @code{Compiler} for command COMP or COMPILE (invoking the compiler) + + @item + package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^}) + + @item + package @code{Eliminate} for command ELIM (invoking + @code{^gnatelim^gnatelim^}) + + @item + package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^}) + + @item + package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^}) + + @item + package @code{Pretty_Printer} for command PP or PRETTY + (invoking @code{^gnatpp^gnatpp^}) + + @item + package @code{Cross_Reference} for command XREF (invoking + @code{^gnatxref^gnatxref^}) + + @end itemize + + @noindent + Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^}, + a simple variable with a string list value. It contains ^switches^switches^ + for the invocation of @code{^gnatls^gnatls^}. + + @smallexample @c projectfile + @group + project Proj1 is + package gnatls is + for ^Switches^Switches^ + use ("^-a^-a^", + "^-v^-v^"); + end gnatls; + end Proj1; + @end group + @end smallexample + + @noindent + All other packages have two attribute @code{^Switches^Switches^} and + @code{^Default_Switches^Default_Switches^}. + + @noindent + @code{^Switches^Switches^} is an associated array attribute, indexed by the + source file name, that has a string list value: the ^switches^switches^ to be + used when the tool corresponding to the package is invoked for the specific + source file. + + @noindent + @code{^Default_Switches^Default_Switches^} is an associative array attribute, + indexed by the programming language that has a string list value. + @code{^Default_Switches^Default_Switches^ ("Ada")} contains the + ^switches^switches^ for the invocation of the tool corresponding + to the package, except if a specific @code{^Switches^Switches^} attribute + is specified for the source file. + + @smallexample @c projectfile + @group + project Proj is + + for Source_Dirs use ("./**"); + + package gnatls is + for ^Switches^Switches^ use + ("^-a^-a^", + "^-v^-v^"); + end gnatls; + @end group + @group + + package Compiler is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-gnatv^-gnatv^", + "^-gnatwa^-gnatwa^"); + end Binder; + @end group + @group + + package Binder is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-C^-C^", + "^-e^-e^"); + end Binder; + @end group + @group + + package Linker is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-C^-C^"); + for ^Switches^Switches^ ("main.adb") + use ("^-C^-C^", + "^-v^-v^", + "^-v^-v^"); + end Linker; + @end group + @group + + package Finder is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-a^-a^", + "^-f^-f^"); + end Finder; + @end group + @group + + package Cross_Reference is + for ^Default_Switches^Default_Switches^ ("Ada") + use ("^-a^-a^", + "^-f^-f^", + "^-d^-d^", + "^-u^-u^"); + end Cross_Reference; + end Proj; + @end group + @end smallexample + + @noindent + With the above project file, commands such as + + @smallexample + ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^ + ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^ + ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^ + ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^ + ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^ + @end smallexample + + @noindent + will set up the environment properly and invoke the tool with the switches + found in the package corresponding to the tool: + @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools, + except @code{^Switches^Switches^ ("main.adb")} + for @code{^gnatlink^gnatlink^}. + + @ifclear vms + @node Glide and Project Files + @subsection Glide and Project Files + + @noindent + Glide will automatically recognize the @file{.gpr} extension for + project files, and will + convert them to its own internal format automatically. However, it + doesn't provide a syntax-oriented editor for modifying these + files. + The project file will be loaded as text when you select the menu item + @code{Ada} @result{} @code{Project} @result{} @code{Edit}. + You can edit this text and save the @file{gpr} file; + when you next select this project file in Glide it + will be automatically reloaded. + @end ifclear + + @c ********************** + @node An Extended Example + @section An Extended Example + + @noindent + Suppose that we have two programs, @var{prog1} and @var{prog2}, + whose sources are in corresponding directories. We would like + to build them with a single @command{gnatmake} command, and we want to place + their object files into @file{build} subdirectories of the source directories. + Furthermore, we want to have to have two separate subdirectories + in @file{build} -- @file{release} and @file{debug} -- which will contain + the object files compiled with different set of compilation flags. + + In other words, we have the following structure: + + @smallexample + @group + main + |- prog1 + | |- build + | | debug + | | release + |- prog2 + |- build + | debug + | release + @end group + @end smallexample + + @noindent + Here are the project files that we must place in a directory @file{main} + to maintain this structure: + + @enumerate + + @item We create a @code{Common} project with a package @code{Compiler} that + specifies the compilation ^switches^switches^: + + @smallexample + File "common.gpr": + @group + @b{project} Common @b{is} + + @b{for} Source_Dirs @b{use} (); -- No source files + @end group + + @group + @b{type} Build_Type @b{is} ("release", "debug"); + Build : Build_Type := External ("BUILD", "debug"); + @end group + @group + @b{package} Compiler @b{is} + @b{case} Build @b{is} + @b{when} "release" => + @b{for} ^Default_Switches^Default_Switches^ ("Ada") + @b{use} ("^-O2^-O2^"); + @b{when} "debug" => + @b{for} ^Default_Switches^Default_Switches^ ("Ada") + @b{use} ("^-g^-g^"); + @b{end case}; + @b{end} Compiler; + + @b{end} Common; + @end group + @end smallexample + + @item We create separate projects for the two programs: + + @smallexample + @group + File "prog1.gpr": + + @b{with} "common"; + @b{project} Prog1 @b{is} + + @b{for} Source_Dirs @b{use} ("prog1"); + @b{for} Object_Dir @b{use} "prog1/build/" & Common.Build; + + @b{package} Compiler @b{renames} Common.Compiler; + + @b{end} Prog1; + @end group + @end smallexample + + @smallexample + @group + File "prog2.gpr": + + @b{with} "common"; + @b{project} Prog2 @b{is} + + @b{for} Source_Dirs @b{use} ("prog2"); + @b{for} Object_Dir @b{use} "prog2/build/" & Common.Build; + + @b{package} Compiler @b{renames} Common.Compiler; + + @end group + @b{end} Prog2; + @end smallexample + + @item We create a wrapping project @code{Main}: + + @smallexample + @group + File "main.gpr": + + @b{with} "common"; + @b{with} "prog1"; + @b{with} "prog2"; + @b{project} Main @b{is} + + @b{package} Compiler @b{renames} Common.Compiler; + + @b{end} Main; + @end group + @end smallexample + + @item Finally we need to create a dummy procedure that @code{with}s (either + explicitly or implicitly) all the sources of our two programs. + + @end enumerate + + @noindent + Now we can build the programs using the command + + @smallexample + gnatmake ^-P^/PROJECT_FILE=^main dummy + @end smallexample + + @noindent + for the Debug mode, or + + @ifclear vms + @smallexample + gnatmake -Pmain -XBUILD=release + @end smallexample + @end ifclear + + @ifset vms + @smallexample + GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release + @end smallexample + @end ifset + + @noindent + for the Release mode. + + @c ******************************** + @c * Project File Complete Syntax * + @c ******************************** + + @node Project File Complete Syntax + @section Project File Complete Syntax + + @smallexample + project ::= + context_clause project_declaration + + context_clause ::= + @{with_clause@} + + with_clause ::= + @b{with} path_name @{ , path_name @} ; + + path_name ::= + string_literal + + project_declaration ::= + simple_project_declaration | project_extension + + simple_project_declaration ::= + @b{project} simple_name @b{is} + @{declarative_item@} + @b{end} simple_name; + + project_extension ::= + @b{project} simple_name @b{extends} path_name @b{is} + @{declarative_item@} + @b{end} simple_name; + + declarative_item ::= + package_declaration | + typed_string_declaration | + other_declarative_item + + package_declaration ::= + package_specification | package_renaming + + package_specification ::= + @b{package} package_identifier @b{is} + @{simple_declarative_item@} + @b{end} package_identifier ; + + package_identifier ::= + @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} | + @code{Linker} | @code{Finder} | @code{Cross_Reference} | + @code{^gnatls^gnatls^} | @code{IDE} | @code{Pretty_Printer} + + package_renaming ::== + @b{package} package_identifier @b{renames} + simple_name.package_identifier ; + + typed_string_declaration ::= + @b{type} _simple_name @b{is} + ( string_literal @{, string_literal@} ); + + other_declarative_item ::= + attribute_declaration | + typed_variable_declaration | + variable_declaration | + case_construction + + attribute_declaration ::= + full_associative_array_declaration | + @b{for} attribute_designator @b{use} expression ; + + full_associative_array_declaration ::= + @b{for} simple_name @b{use} + simple_name [ . simple_Name ] ' simple_name ; + + attribute_designator ::= + simple_name | + simple_name ( string_literal ) + + typed_variable_declaration ::= + simple_name : name := string_expression ; + + variable_declaration ::= + simple_name := expression; + + expression ::= + term @{& term@} + + term ::= + literal_string | + string_list | + name | + external_value | + attribute_reference + + string_literal ::= + (same as Ada) + + string_list ::= + ( expression @{ , expression @} ) + + external_value ::= + @b{external} ( string_literal [, string_literal] ) + + attribute_reference ::= + attribute_prefix ' simple_name [ ( literal_string ) ] + + attribute_prefix ::= + @b{project} | + simple_name | package_identifier | + simple_name . package_identifier + + case_construction ::= + @b{case} name @b{is} + @{case_item@} + @b{end case} ; + + case_item ::= + @b{when} discrete_choice_list => + @{case_construction | attribute_declaration@} + + discrete_choice_list ::= + string_literal @{| string_literal@} | + @b{others} + + name ::= + simple_name @{. simple_name@} + + simple_name ::= + identifier (same as Ada) + + @end smallexample + + + @node The Cross-Referencing Tools gnatxref and gnatfind + @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind} + @findex gnatxref + @findex gnatfind + + @noindent + The compiler generates cross-referencing information (unless + you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files. + This information indicates where in the source each entity is declared and + referenced. Note that entities in package Standard are not included, but + entities in all other predefined units are included in the output. + + Before using any of these two tools, you need to compile successfully your + application, so that GNAT gets a chance to generate the cross-referencing + information. + + The two tools @code{gnatxref} and @code{gnatfind} take advantage of this + information to provide the user with the capability to easily locate the + declaration and references to an entity. These tools are quite similar, + the difference being that @code{gnatfind} is intended for locating + definitions and/or references to a specified entity or entities, whereas + @code{gnatxref} is oriented to generating a full report of all + cross-references. + + To use these tools, you must not compile your application using the + @option{-gnatx} switch on the @file{gnatmake} command line + (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing + information will not be generated. + + @menu + * gnatxref Switches:: + * gnatfind Switches:: + * Project Files for gnatxref and gnatfind:: + * Regular Expressions in gnatfind and gnatxref:: + * Examples of gnatxref Usage:: + * Examples of gnatfind Usage:: + @end menu + + @node gnatxref Switches + @section @code{gnatxref} Switches + + @noindent + The command invocation for @code{gnatxref} is: + @smallexample + $ gnatxref [switches] sourcefile1 [sourcefile2 ...] + @end smallexample + + @noindent + where + + @table @code + @item sourcefile1, sourcefile2 + identifies the source files for which a report is to be generated. The + ``with''ed units will be processed too. You must provide at least one file. + + These file names are considered to be regular expressions, so for instance + specifying @file{source*.adb} is the same as giving every file in the current + directory whose name starts with @file{source} and whose extension is + @file{adb}. + + @end table + + @noindent + The switches can be : + @table @option + @c !sort! + @item ^-a^/ALL_FILES^ + @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref}) + If this switch is present, @code{gnatfind} and @code{gnatxref} will parse + the read-only files found in the library search path. Otherwise, these files + will be ignored. This option can be used to protect Gnat sources or your own + libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} + much faster, and their output much smaller. Read-only here refers to access + or permissions status in the file system for the current user. + + @item -aIDIR + @cindex @option{-aIDIR} (@command{gnatxref}) + When looking for source files also look in directory DIR. The order in which + source file search is undertaken is the same as for @file{gnatmake}. + + @item -aODIR + @cindex @option{-aODIR} (@command{gnatxref}) + When searching for library and object files, look in directory + DIR. The order in which library files are searched is the same as for + @file{gnatmake}. + + @item -nostdinc + @cindex @option{-nostdinc} (@command{gnatxref}) + Do not look for sources in the system default directory. + + @item -nostdlib + @cindex @option{-nostdlib} (@command{gnatxref}) + Do not look for library files in the system default directory. + + @item --RTS=@var{rts-path} + @cindex @option{--RTS} (@command{gnatxref}) + Specifies the default location of the runtime library. Same meaning as the + equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). + + @item ^-d^/DERIVED_TYPES^ + @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref}) + If this switch is set @code{gnatxref} will output the parent type + reference for each matching derived types. + + @item ^-f^/FULL_PATHNAME^ + @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref}) + If this switch is set, the output file names will be preceded by their + directory (if the file was found in the search path). If this switch is + not set, the directory will not be printed. + + @item ^-g^/IGNORE_LOCALS^ + @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref}) + If this switch is set, information is output only for library-level + entities, ignoring local entities. The use of this switch may accelerate + @code{gnatfind} and @code{gnatxref}. + + @item -IDIR + @cindex @option{-IDIR} (@command{gnatxref}) + Equivalent to @samp{-aODIR -aIDIR}. + + @item -pFILE + @cindex @option{-pFILE} (@command{gnatxref}) + Specify a project file to use @xref{Project Files}. These project files are + the @file{.adp} files used by Glide. If you need to use the @file{.gpr} + project files, you should use gnatxref through the GNAT driver + (@command{gnat xref -Pproject}). + + By default, @code{gnatxref} and @code{gnatfind} will try to locate a + project file in the current directory. + + If a project file is either specified or found by the tools, then the content + of the source directory and object directory lines are added as if they + had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} + and @samp{^-aO^OBJECT_SEARCH^}. + @item ^-u^/UNUSED^ + Output only unused symbols. This may be really useful if you give your + main compilation unit on the command line, as @code{gnatxref} will then + display every unused entity and 'with'ed package. + + @ifclear vms + @item -v + Instead of producing the default output, @code{gnatxref} will generate a + @file{tags} file that can be used by vi. For examples how to use this + feature, see @xref{Examples of gnatxref Usage}. The tags file is output + to the standard output, thus you will have to redirect it to a file. + @end ifclear + + @end table + + @noindent + All these switches may be in any order on the command line, and may even + appear after the file names. They need not be separated by spaces, thus + you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of + @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}. + + @node gnatfind Switches + @section @code{gnatfind} Switches + + @noindent + The command line for @code{gnatfind} is: + + @smallexample + $ gnatfind [switches] pattern[:sourcefile[:line[:column]]] + [file1 file2 ...] + @end smallexample + + @noindent + where + + @table @code + @item pattern + An entity will be output only if it matches the regular expression found + in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}. + + Omitting the pattern is equivalent to specifying @samp{*}, which + will match any entity. Note that if you do not provide a pattern, you + have to provide both a sourcefile and a line. + + Entity names are given in Latin-1, with uppercase/lowercase equivalence + for matching purposes. At the current time there is no support for + 8-bit codes other than Latin-1, or for wide characters in identifiers. + + @item sourcefile + @code{gnatfind} will look for references, bodies or declarations + of symbols referenced in @file{sourcefile}, at line @samp{line} + and column @samp{column}. See @pxref{Examples of gnatfind Usage} + for syntax examples. + + @item line + is a decimal integer identifying the line number containing + the reference to the entity (or entities) to be located. + + @item column + is a decimal integer identifying the exact location on the + line of the first character of the identifier for the + entity reference. Columns are numbered from 1. + + @item file1 file2 ... + The search will be restricted to these source files. If none are given, then + the search will be done for every library file in the search path. + These file must appear only after the pattern or sourcefile. + + These file names are considered to be regular expressions, so for instance + specifying 'source*.adb' is the same as giving every file in the current + directory whose name starts with 'source' and whose extension is 'adb'. + + The location of the spec of the entity will always be displayed, even if it + isn't in one of file1, file2,... The occurrences of the entity in the + separate units of the ones given on the command line will also be displayed. + + Note that if you specify at least one file in this part, @code{gnatfind} may + sometimes not be able to find the body of the subprograms... + + @end table + + @noindent + At least one of 'sourcefile' or 'pattern' has to be present on + the command line. + + The following switches are available: + @table @option + @c !sort! + + @item ^-a^/ALL_FILES^ + @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind}) + If this switch is present, @code{gnatfind} and @code{gnatxref} will parse + the read-only files found in the library search path. Otherwise, these files + will be ignored. This option can be used to protect Gnat sources or your own + libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} + much faster, and their output much smaller. Read-only here refers to access + or permission status in the file system for the current user. + + @item -aIDIR + @cindex @option{-aIDIR} (@command{gnatfind}) + When looking for source files also look in directory DIR. The order in which + source file search is undertaken is the same as for @file{gnatmake}. + + @item -aODIR + @cindex @option{-aODIR} (@command{gnatfind}) + When searching for library and object files, look in directory + DIR. The order in which library files are searched is the same as for + @file{gnatmake}. + + @item -nostdinc + @cindex @option{-nostdinc} (@command{gnatfind}) + Do not look for sources in the system default directory. + + @item -nostdlib + @cindex @option{-nostdlib} (@command{gnatfind}) + Do not look for library files in the system default directory. + + @item --RTS=@var{rts-path} + @cindex @option{--RTS} (@command{gnatfind}) + Specifies the default location of the runtime library. Same meaning as the + equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). + + @item ^-d^/DERIVED_TYPE_INFORMATION^ + @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind}) + If this switch is set, then @code{gnatfind} will output the parent type + reference for each matching derived types. + + @item ^-e^/EXPRESSIONS^ + @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind}) + By default, @code{gnatfind} accept the simple regular expression set for + @samp{pattern}. If this switch is set, then the pattern will be + considered as full Unix-style regular expression. + + @item ^-f^/FULL_PATHNAME^ + @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind}) + If this switch is set, the output file names will be preceded by their + directory (if the file was found in the search path). If this switch is + not set, the directory will not be printed. + + @item ^-g^/IGNORE_LOCALS^ + @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind}) + If this switch is set, information is output only for library-level + entities, ignoring local entities. The use of this switch may accelerate + @code{gnatfind} and @code{gnatxref}. + + @item -IDIR + @cindex @option{-IDIR} (@command{gnatfind}) + Equivalent to @samp{-aODIR -aIDIR}. + + @item -pFILE + @cindex @option{-pFILE} (@command{gnatfind}) + Specify a project file (@pxref{Project Files}) to use. + By default, @code{gnatxref} and @code{gnatfind} will try to locate a + project file in the current directory. + + If a project file is either specified or found by the tools, then the content + of the source directory and object directory lines are added as if they + had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and + @samp{^-aO^/OBJECT_SEARCH^}. + + @item ^-r^/REFERENCES^ + @cindex @option{^-r^/REFERENCES^} (@command{gnatfind}) + By default, @code{gnatfind} will output only the information about the + declaration, body or type completion of the entities. If this switch is + set, the @code{gnatfind} will locate every reference to the entities in + the files specified on the command line (or in every file in the search + path if no file is given on the command line). + + @item ^-s^/PRINT_LINES^ + @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind}) + If this switch is set, then @code{gnatfind} will output the content + of the Ada source file lines were the entity was found. + + @item ^-t^/TYPE_HIERARCHY^ + @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind}) + If this switch is set, then @code{gnatfind} will output the type hierarchy for + the specified type. It act like -d option but recursively from parent + type to parent type. When this switch is set it is not possible to + specify more than one file. + + @end table + + @noindent + All these switches may be in any order on the command line, and may even + appear after the file names. They need not be separated by spaces, thus + you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of + @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}. + + As stated previously, gnatfind will search in every directory in the + search path. You can force it to look only in the current directory if + you specify @code{*} at the end of the command line. + + @node Project Files for gnatxref and gnatfind + @section Project Files for @command{gnatxref} and @command{gnatfind} + + @noindent + Project files allow a programmer to specify how to compile its + application, where to find sources, etc. These files are used + @ifclear vms + primarily by the Glide Ada mode, but they can also be used + @end ifclear + by the two tools + @code{gnatxref} and @code{gnatfind}. + + A project file name must end with @file{.gpr}. If a single one is + present in the current directory, then @code{gnatxref} and @code{gnatfind} will + extract the information from it. If multiple project files are found, none of + them is read, and you have to use the @samp{-p} switch to specify the one + you want to use. + + The following lines can be included, even though most of them have default + values which can be used in most cases. + The lines can be entered in any order in the file. + Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of + each line. If you have multiple instances, only the last one is taken into + account. + + @table @code + @item src_dir=DIR + [default: @code{"^./^[]^"}] + specifies a directory where to look for source files. Multiple @code{src_dir} + lines can be specified and they will be searched in the order they + are specified. + + @item obj_dir=DIR + [default: @code{"^./^[]^"}] + specifies a directory where to look for object and library files. Multiple + @code{obj_dir} lines can be specified, and they will be searched in the order + they are specified + + @item comp_opt=SWITCHES + [default: @code{""}] + creates a variable which can be referred to subsequently by using + the @code{$@{comp_opt@}} notation. This is intended to store the default + switches given to @command{gnatmake} and @command{gcc}. + + @item bind_opt=SWITCHES + [default: @code{""}] + creates a variable which can be referred to subsequently by using + the @samp{$@{bind_opt@}} notation. This is intended to store the default + switches given to @command{gnatbind}. + + @item link_opt=SWITCHES + [default: @code{""}] + creates a variable which can be referred to subsequently by using + the @samp{$@{link_opt@}} notation. This is intended to store the default + switches given to @command{gnatlink}. + + @item main=EXECUTABLE + [default: @code{""}] + specifies the name of the executable for the application. This variable can + be referred to in the following lines by using the @samp{$@{main@}} notation. + + @ifset vms + @item comp_cmd=COMMAND + [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}] + @end ifset + @ifclear vms + @item comp_cmd=COMMAND + [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}] + @end ifclear + specifies the command used to compile a single file in the application. + + @ifset vms + @item make_cmd=COMMAND + [default: @code{"GNAT MAKE $@{main@} + /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@} + /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@} + /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}] + @end ifset + @ifclear vms + @item make_cmd=COMMAND + [default: @code{"gnatmake $@{main@} -aI$@{src_dir@} + -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} + -bargs $@{bind_opt@} -largs $@{link_opt@}"}] + @end ifclear + specifies the command used to recompile the whole application. + + @item run_cmd=COMMAND + [default: @code{"$@{main@}"}] + specifies the command used to run the application. + + @item debug_cmd=COMMAND + [default: @code{"gdb $@{main@}"}] + specifies the command used to debug the application + + @end table + + @noindent + @command{gnatxref} and @command{gnatfind} only take into account the + @code{src_dir} and @code{obj_dir} lines, and ignore the others. + + @node Regular Expressions in gnatfind and gnatxref + @section Regular Expressions in @code{gnatfind} and @code{gnatxref} + + @noindent + As specified in the section about @command{gnatfind}, the pattern can be a + regular expression. Actually, there are to set of regular expressions + which are recognized by the program : + + @table @code + @item globbing patterns + These are the most usual regular expression. They are the same that you + generally used in a Unix shell command line, or in a DOS session. + + Here is a more formal grammar : + @smallexample + @group + @iftex + @leftskip=.5cm + @end iftex + regexp ::= term + term ::= elmt -- matches elmt + term ::= elmt elmt -- concatenation (elmt then elmt) + term ::= * -- any string of 0 or more characters + term ::= ? -- matches any character + term ::= [char @{char@}] -- matches any character listed + term ::= [char - char] -- matches any character in range + @end group + @end smallexample + + @item full regular expression + The second set of regular expressions is much more powerful. This is the + type of regular expressions recognized by utilities such a @file{grep}. + + The following is the form of a regular expression, expressed in Ada + reference manual style BNF is as follows + + @smallexample + @iftex + @leftskip=.5cm + @end iftex + @group + regexp ::= term @{| term@} -- alternation (term or term ...) + + term ::= item @{item@} -- concatenation (item then item) + + item ::= elmt -- match elmt + item ::= elmt * -- zero or more elmt's + item ::= elmt + -- one or more elmt's + item ::= elmt ? -- matches elmt or nothing + @end group + @group + elmt ::= nschar -- matches given character + elmt ::= [nschar @{nschar@}] -- matches any character listed + elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed + elmt ::= [char - char] -- matches chars in given range + elmt ::= \ char -- matches given character + elmt ::= . -- matches any single character + elmt ::= ( regexp ) -- parens used for grouping + + char ::= any character, including special characters + nschar ::= any character except ()[].*+?^^^ + @end group + @end smallexample + + Following are a few examples : + + @table @samp + @item abcde|fghi + will match any of the two strings 'abcde' and 'fghi'. + + @item abc*d + will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on + + @item [a-z]+ + will match any string which has only lowercase characters in it (and at + least one character + + @end table + @end table + + @node Examples of gnatxref Usage + @section Examples of @code{gnatxref} Usage + + @subsection General Usage + + @noindent + For the following examples, we will consider the following units : + + @smallexample @c ada + @group + @cartouche + main.ads: + 1: with Bar; + 2: package Main is + 3: procedure Foo (B : in Integer); + 4: C : Integer; + 5: private + 6: D : Integer; + 7: end Main; + + main.adb: + 1: package body Main is + 2: procedure Foo (B : in Integer) is + 3: begin + 4: C := B; + 5: D := B; + 6: Bar.Print (B); + 7: Bar.Print (C); + 8: end Foo; + 9: end Main; + + bar.ads: + 1: package Bar is + 2: procedure Print (B : Integer); + 3: end bar; + @end cartouche + @end group + @end smallexample + + @table @code + + @noindent + The first thing to do is to recompile your application (for instance, in + that case just by doing a @samp{gnatmake main}, so that GNAT generates + the cross-referencing information. + You can then issue any of the following commands: + + @item gnatxref main.adb + @code{gnatxref} generates cross-reference information for main.adb + and every unit 'with'ed by main.adb. + + The output would be: + @smallexample + @iftex + @leftskip=0cm + @end iftex + B Type: Integer + Decl: bar.ads 2:22 + B Type: Integer + Decl: main.ads 3:20 + Body: main.adb 2:20 + Ref: main.adb 4:13 5:13 6:19 + Bar Type: Unit + Decl: bar.ads 1:9 + Ref: main.adb 6:8 7:8 + main.ads 1:6 + C Type: Integer + Decl: main.ads 4:5 + Modi: main.adb 4:8 + Ref: main.adb 7:19 + D Type: Integer + Decl: main.ads 6:5 + Modi: main.adb 5:8 + Foo Type: Unit + Decl: main.ads 3:15 + Body: main.adb 2:15 + Main Type: Unit + Decl: main.ads 2:9 + Body: main.adb 1:14 + Print Type: Unit + Decl: bar.ads 2:15 + Ref: main.adb 6:12 7:12 + @end smallexample + + @noindent + that is the entity @code{Main} is declared in main.ads, line 2, column 9, + its body is in main.adb, line 1, column 14 and is not referenced any where. + + The entity @code{Print} is declared in bar.ads, line 2, column 15 and it + it referenced in main.adb, line 6 column 12 and line 7 column 12. + + @item gnatxref package1.adb package2.ads + @code{gnatxref} will generates cross-reference information for + package1.adb, package2.ads and any other package 'with'ed by any + of these. + + @end table + + @ifclear vms + @subsection Using gnatxref with vi + + @code{gnatxref} can generate a tags file output, which can be used + directly from @file{vi}. Note that the standard version of @file{vi} + will not work properly with overloaded symbols. Consider using another + free implementation of @file{vi}, such as @file{vim}. + + @smallexample + $ gnatxref -v gnatfind.adb > tags + @end smallexample + + @noindent + will generate the tags file for @code{gnatfind} itself (if the sources + are in the search path!). + + From @file{vi}, you can then use the command @samp{:tag @i{entity}} + (replacing @i{entity} by whatever you are looking for), and vi will + display a new file with the corresponding declaration of entity. + @end ifclear + + @node Examples of gnatfind Usage + @section Examples of @code{gnatfind} Usage + + @table @code + + @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb + Find declarations for all entities xyz referenced at least once in + main.adb. The references are search in every library file in the search + path. + + The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^} + switch is set) + + The output will look like: + @smallexample + ^directory/^[directory]^main.ads:106:14: xyz <= declaration + ^directory/^[directory]^main.adb:24:10: xyz <= body + ^directory/^[directory]^foo.ads:45:23: xyz <= declaration + @end smallexample + + @noindent + that is to say, one of the entities xyz found in main.adb is declared at + line 12 of main.ads (and its body is in main.adb), and another one is + declared at line 45 of foo.ads + + @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb + This is the same command as the previous one, instead @code{gnatfind} will + display the content of the Ada source file lines. + + The output will look like: + + @smallexample + ^directory/^[directory]^main.ads:106:14: xyz <= declaration + procedure xyz; + ^directory/^[directory]^main.adb:24:10: xyz <= body + procedure xyz is + ^directory/^[directory]^foo.ads:45:23: xyz <= declaration + xyz : Integer; + @end smallexample + + @noindent + This can make it easier to find exactly the location your are looking + for. + + @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb + Find references to all entities containing an x that are + referenced on line 123 of main.ads. + The references will be searched only in main.ads and foo.adb. + + @item gnatfind main.ads:123 + Find declarations and bodies for all entities that are referenced on + line 123 of main.ads. + + This is the same as @code{gnatfind "*":main.adb:123}. + + @item gnatfind ^mydir/^[mydir]^main.adb:123:45 + Find the declaration for the entity referenced at column 45 in + line 123 of file main.adb in directory mydir. Note that it + is usual to omit the identifier name when the column is given, + since the column position identifies a unique reference. + + The column has to be the beginning of the identifier, and should not + point to any character in the middle of the identifier. + + @end table + + + @c ********************************* + @node The GNAT Pretty-Printer gnatpp + @chapter The GNAT Pretty-Printer @command{gnatpp} + @findex gnatpp + @cindex Pretty-Printer + + @noindent + ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility + for source reformatting / pretty-printing. + It takes an Ada source file as input and generates a reformatted + version as output. + You can specify various style directives via switches; e.g., + identifier case conventions, rules of indentation, and comment layout. + + To produce a reformatted file, @command{gnatpp} generates and uses the ASIS + tree for the input source and thus requires the input to be syntactically and + semantically legal. + If this condition is not met, @command{gnatpp} will terminate with an + error message; no output file will be generated. + + If the compilation unit + contained in the input source depends semantically upon units located + outside the current directory, you have to provide the source search path + when invoking @command{gnatpp}; see the description of the @command{gnatpp} + switches below. + + The @command{gnatpp} command has the form + + @smallexample + $ gnatpp [@var{switches}] @var{filename} + @end smallexample + + @noindent + where + @itemize @bullet + @item + @var{switches} is an optional sequence of switches defining such properties as + the formatting rules, the source search path, and the destination for the + output source file + + @item + @var{filename} is the name (including the extension) of the source file to + reformat; ``wildcards'' are not permitted. The file name may contain path + information; it does not have to follow the GNAT file naming rules + @end itemize + + + @menu + * Switches for gnatpp:: + * Formatting Rules:: + @end menu + + @node Switches for gnatpp + @section Switches for @command{gnatpp} + + @noindent + The following subsections describe the various switches accepted by + @command{gnatpp}, organized by category. + + @ifclear vms + You specify a switch by supplying a name and generally also a value. + In many cases the values for a switch with a given name are incompatible with + each other + (for example the switch that controls the casing of a reserved word may have + exactly one value: upper case, lower case, or + mixed case) and thus exactly one such switch can be in effect for an + invocation of @command{gnatpp}. + If more than one is supplied, the last one is used. + However, some values for the same switch are mutually compatible. + You may supply several such switches to @command{gnatpp}, but then + each must be specified in full, with both the name and the value. + Abbreviated forms (the name appearing once, followed by each value) are + not permitted. + For example, to set + the alignment of the assignment delimiter both in declarations and in + assignment statements, you must write @option{-A2A3} + (or @option{-A2 -A3}), but not @option{-A23}. + @end ifclear + + @ifset vms + In many cases the set of options for a given qualifier are incompatible with + each other (for example the qualifier that controls the casing of a reserved + word may have exactly one option, which specifies either upper case, lower + case, or mixed case), and thus exactly one such option can be in effect for + an invocation of @command{gnatpp}. + If more than one is supplied, the last one is used. + However, some qualifiers have options that are mutually compatible, + and then you may then supply several such options when invoking + @command{gnatpp}. + @end ifset + + In most cases, it is obvious whether or not the + ^values for a switch with a given name^options for a given qualifier^ + are compatible with each other. + When the semantics might not be evident, the summaries below explicitly + indicate the effect. + + @menu + * Alignment Control:: + * Casing Control:: + * Construct Layout Control:: + * General Text Layout Control:: + * Other Formatting Options:: + * Setting the Source Search Path:: + * Output File Control:: + * Other gnatpp Switches:: + @end menu + + + @node Alignment Control + @subsection Alignment Control + @cindex Alignment control in @command{gnatpp} + + @noindent + Programs can be easier to read if certain constructs are vertically aligned. + By default all alignments are set ON. + Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to + OFF, and then use one or more of the other + ^@option{-A@var{n}} switches^@option{/ALIGN} options^ + to activate alignment for specific constructs. + + @table @option + @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp}) + + @ifset vms + @item /ALIGN=ON + Set all alignments to ON + @end ifset + + @item ^-A0^/ALIGN=OFF^ + Set all alignments to OFF + + @item ^-A1^/ALIGN=COLONS^ + Align @code{:} in declarations + + @item ^-A2^/ALIGN=DECLARATIONS^ + Align @code{:=} in initializations in declarations + + @item ^-A3^/ALIGN=STATEMENTS^ + Align @code{:=} in assignment statements + + @item ^-A4^/ALIGN=ARROWS^ + Align @code{=>} in associations + @end table + + @noindent + The @option{^-A^/ALIGN^} switches are mutually compatible; any combination + is allowed. + + + @node Casing Control + @subsection Casing Control + @cindex Casing control in @command{gnatpp} + + @noindent + @command{gnatpp} allows you to specify the casing for reserved words, + pragma names, attribute designators and identifiers. + For identifiers you may define a + general rule for name casing but also override this rule + via a set of dictionary files. + + Three types of casing are supported: lower case, upper case, and mixed case. + Lower and upper case are self-explanatory (but since some letters in + Latin1 and other GNAT-supported character sets + exist only in lower-case form, an upper case conversion will have no + effect on them.) + ``Mixed case'' means that the first letter, and also each letter immediately + following an underscore, are converted to their uppercase forms; + all the other letters are converted to their lowercase forms. + + @table @option + @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp}) + @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^ + Attribute designators are lower case + + @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^ + Attribute designators are upper case + + @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^ + Attribute designators are mixed case (this is the default) + + @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp}) + @item ^-kL^/KEYWORD_CASING=LOWER_CASE^ + Keywords (technically, these are known in Ada as @emph{reserved words}) are + lower case (this is the default) + + @item ^-kU^/KEYWORD_CASING=UPPER_CASE^ + Keywords are upper case + + @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp}) + @item ^-nD^/NAME_CASING=AS_DECLARED^ + Name casing for defining occurrences are as they appear in the source file + (this is the default) + + @item ^-nU^/NAME_CASING=UPPER_CASE^ + Names are in upper case + + @item ^-nL^/NAME_CASING=LOWER_CASE^ + Names are in lower case + + @item ^-nM^/NAME_CASING=MIXED_CASE^ + Names are in mixed case + + @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp}) + @item ^-pL^/PRAGMA_CASING=LOWER_CASE^ + Pragma names are lower case + + @item ^-pU^/PRAGMA_CASING=UPPER_CASE^ + Pragma names are upper case + + @item ^-pM^/PRAGMA_CASING=MIXED_CASE^ + Pragma names are mixed case (this is the default) + + @item ^-D@var{file}^/DICTIONARY=@var{file}^ + @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp}) + Use @var{file} as a @emph{dictionary file} that defines + the casing for a set of specified names, + thereby overriding the effect on these names by + any explicit or implicit + ^-n^/NAME_CASING^ switch. + To supply more than one dictionary file, + use ^several @option{-D} switches^a list of files as options^. + + @noindent + @option{gnatpp} implicitly uses a @emph{default dictionary file} + to define the casing for the Ada predefined names and + the names declared in the GNAT libraries. + + @item ^-D-^/SPECIFIC_CASING^ + @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp}) + Do not use the default dictionary file; + instead, use the casing + defined by a @option{^-n^/NAME_CASING^} switch and any explicit + dictionary file(s) + @end table + + @noindent + The structure of a dictionary file, and details on the conventions + used in the default dictionary file, are defined in @ref{Name Casing}. + + The @option{^-D-^/SPECIFIC_CASING^} and + @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually + compatible. + + + @node Construct Layout Control + @subsection Construct Layout Control + @cindex Layout control in @command{gnatpp} + + @noindent + This group of @command{gnatpp} switches controls the layout of comments and + complex syntactic constructs. See @ref{Formatting Comments}, for details + on their effect. + + @table @option + @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp}) + @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^ + GNAT-style comment line indentation (this is the default). + + @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^ + Reference-manual comment line indentation. + + @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^ + GNAT-style comment beginning + + @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^ + Reformat comment blocks + + @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp}) + @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^ + GNAT-style layout (this is the default) + + @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^ + Compact layout + + @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^ + Uncompact layout + @end table + + @ifclear vms + @noindent + The @option{-c1} and @option{-c2} switches are incompatible. + The @option{-c3} and @option{-c4} switches are compatible with each other and + also with @option{-c1} and @option{-c2}. + + The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible. + @end ifclear + + @ifset vms + @noindent + For the @option{/COMMENTS_LAYOUT} qualifier: + @itemize @bullet + @item + The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible. + @item + The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with + each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}. + @end itemize + + @noindent + The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the + @option{/CONSTRUCT_LAYOUT} qualifier are incompatible. + @end ifset + + @node General Text Layout Control + @subsection General Text Layout Control + + @noindent + These switches allow control over line length and indentation. + + @table @option + @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^ + @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp}) + Maximum line length, @i{nnn} from 32 ..256, the default value is 79 + + @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^ + @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp}) + Indentation level, @i{nnn} from 1 .. 9, the default value is 3 + + @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^ + @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp}) + Indentation level for continuation lines (relative to the line being + continued), @i{nnn} from 1 .. 9. + The default + value is one less then the (normal) indentation level, unless the + indentation is set to 1 (in which case the default value for continuation + line indentation is also 1) + @end table + + + @node Other Formatting Options + @subsection Other Formatting Options + + @noindent + These switches control the inclusion of missing end/exit labels, and + the indentation level in @b{case} statements. + + @table @option + @item ^-e^/NO_MISSED_LABELS^ + @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp}) + Do not insert missing end/exit labels. An end label is the name of + a construct that may optionally be repeated at the end of the + construct's declaration; + e.g., the names of packages, subprograms, and tasks. + An exit label is the name of a loop that may appear as target + of an exit statement within the loop. + By default, @command{gnatpp} inserts these end/exit labels when + they are absent from the original source. This option suppresses such + insertion, so that the formatted source reflects the original. + + @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^ + @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp}) + Insert a Form Feed character after a pragma Page. + + @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^ + @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp}) + Do not use an additional indentation level for @b{case} alternatives + and variants if there are @i{nnn} or more (the default + value is 10). + If @i{nnn} is 0, an additional indentation level is + used for @b{case} alternatives and variants regardless of their number. + @end table + + @node Setting the Source Search Path + @subsection Setting the Source Search Path + + @noindent + To define the search path for the input source file, @command{gnatpp} + uses the same switches as the GNAT compiler, with the same effects. + + @table @option + @item ^-I^/SEARCH=^@var{dir} + @cindex @option{^-I^/SEARCH^} (@code{gnatpp}) + The same as the corresponding gcc switch + + @item ^-I-^/NOCURRENT_DIRECTORY^ + @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp}) + The same as the corresponding gcc switch + + @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path} + @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp}) + The same as the corresponding gcc switch + @end table + + + @node Output File Control + @subsection Output File Control + + @noindent + By default the output is sent to the file whose name is obtained by appending + the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file + (if the file with this name already exists, it is unconditionally overwritten). + Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then + @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^} + as output file. + The output may be redirected by the following switches: + + @table @option + @item ^-pipe^/STANDARD_OUTPUT^ + @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp}) + Send the output to @code{Standard_Output} + + @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^ + @cindex @option{^-o^/OUTPUT^} (@code{gnatpp}) + Write the output into @var{output_file}. + If @var{output_file} already exists, @command{gnatpp} terminates without + reading or processing the input file. + + @item ^-of ^/FORCED_OUTPUT=^@var{output_file} + @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp}) + Write the output into @var{output_file}, overwriting the existing file + (if one is present). + + @item ^-r^/REPLACE^ + @cindex @option{^-r^/REPLACE^} (@code{gnatpp}) + Replace the input source file with the reformatted output, and copy the + original input source into the file whose name is obtained by appending the + ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file. + If a file with this name already exists, @command{gnatpp} terminates without + reading or processing the input file. + + @item ^-rf^/OVERRIDING_REPLACE^ + @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp}) + Like @option{^-r^/REPLACE^} except that if the file with the specified name + already exists, it is overwritten. + @end table + + + @node Other gnatpp Switches + @subsection Other @code{gnatpp} Switches + + @noindent + The additional @command{gnatpp} switches are defined in this subsection. + + @table @option + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@code{gnatpp}) + Verbose mode; + @command{gnatpp} generates version information and then + a trace of the actions it takes to produce or obtain the ASIS tree. + + @item ^-w^/WARNINGS^ + @cindex @option{^-w^/WARNINGS^} (@code{gnatpp}) + Warning mode; + @command{gnatpp} generates a warning whenever it can not provide + a required layout in the result source. + @end table + + + @node Formatting Rules + @section Formatting Rules + + @noindent + The following subsections show how @command{gnatpp} treats ``white space'', + comments, program layout, and name casing. + They provide the detailed descriptions of the switches shown above. + + @menu + * White Space and Empty Lines:: + * Formatting Comments:: + * Construct Layout:: + * Name Casing:: + @end menu + + + @node White Space and Empty Lines + @subsection White Space and Empty Lines + + @noindent + @command{gnatpp} does not have an option to control space characters. + It will add or remove spaces according to the style illustrated by the + examples in the @cite{Ada Reference Manual}. + + The only format effectors + (see @cite{Ada Reference Manual}, paragraph 2.1(13)) + that will appear in the output file are platform-specific line breaks, + and also format effectors within (but not at the end of) comments. + In particular, each horizontal tab character that is not inside + a comment will be treated as a space and thus will appear in the + output file as zero or more spaces depending on + the reformatting of the line in which it appears. + The only exception is a Form Feed character, which is inserted after a + pragma @code{Page} when @option{-ff} is set. + + The output file will contain no lines with trailing ``white space'' (spaces, + format effectors). + + Empty lines in the original source are preserved + only if they separate declarations or statements. + In such contexts, a + sequence of two or more empty lines is replaced by exactly one empty line. + Note that a blank line will be removed if it separates two ``comment blocks'' + (a comment block is a sequence of whole-line comments). + In order to preserve a visual separation between comment blocks, use an + ``empty comment'' (a line comprising only hyphens) rather than an empty line. + Likewise, if for some reason you wish to have a sequence of empty lines, + use a sequence of empty comments instead. + + + @node Formatting Comments + @subsection Formatting Comments + + @noindent + Comments in Ada code are of two kinds: + @itemize @bullet + @item + a @emph{whole-line comment}, which appears by itself (possibly preceded by + ``white space'') on a line + + @item + an @emph{end-of-line comment}, which follows some other Ada lexical element + on the same line. + @end itemize + + @noindent + The indentation of a whole-line comment is that of either + the preceding or following line in + the formatted source, depending on switch settings as will be described below. + + For an end-of-line comment, @command{gnatpp} leaves the same number of spaces + between the end of the preceding Ada lexical element and the beginning + of the comment as appear in the original source, + unless either the comment has to be split to + satisfy the line length limitation, or else the next line contains a + whole line comment that is considered a continuation of this end-of-line + comment (because it starts at the same position). + In the latter two + cases, the start of the end-of-line comment is moved right to the nearest + multiple of the indentation level. + This may result in a ``line overflow'' (the right-shifted comment extending + beyond the maximum line length), in which case the comment is split as + described below. + + There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^} + (GNAT-style comment line indentation) + and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^} + (reference-manual comment line indentation). + With reference-manual style, a whole-line comment is indented as if it + were a declaration or statement at the same place + (i.e., according to the indentation of the preceding line(s)). + With GNAT style, a whole-line comment that is immediately followed by an + @b{if} or @b{case} statement alternative, a record variant, or the reserved + word @b{begin}, is indented based on the construct that follows it. + + For example: + @smallexample @c ada + @cartouche + if A then + null; + -- some comment + else + null; + end if; + @end cartouche + @end smallexample + + @noindent + Reference-manual indentation produces: + + @smallexample @c ada + @cartouche + if A then + null; + -- some comment + else + null; + end if; + @end cartouche + @end smallexample + + @noindent + while GNAT-style indentation produces: + + @smallexample @c ada + @cartouche + if A then + null; + -- some comment + else + null; + end if; + @end cartouche + @end smallexample + + @noindent + The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch + (GNAT style comment beginning) has the following + effect: + + @itemize @bullet + @item + For each whole-line comment that does not end with two hyphens, + @command{gnatpp} inserts spaces if necessary after the starting two hyphens + to ensure that there are at least two spaces between these hyphens and the + first non-blank character of the comment. + @end itemize + + @noindent + For an end-of-line comment, if in the original source the next line is a + whole-line comment that starts at the same position + as the end-of-line comment, + then the whole-line comment (and all whole-line comments + that follow it and that start at the same position) + will start at this position in the output file. + + @noindent + That is, if in the original source we have: + + @smallexample @c ada + @cartouche + begin + A := B + C; -- B must be in the range Low1..High1 + -- C must be in the range Low2..High2 + --B+C will be in the range Low1+Low2..High1+High2 + X := X + 1; + @end cartouche + @end smallexample + + @noindent + Then in the formatted source we get + + @smallexample @c ada + @cartouche + begin + A := B + C; -- B must be in the range Low1..High1 + -- C must be in the range Low2..High2 + -- B+C will be in the range Low1+Low2..High1+High2 + X := X + 1; + @end cartouche + @end smallexample + + @noindent + A comment that exceeds the line length limit will be split. + Unless switch + @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and + the line belongs to a reformattable block, splitting the line generates a + @command{gnatpp} warning. + The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line + comments may be reformatted in typical + word processor style (that is, moving words between lines and putting as + many words in a line as possible). + + + @node Construct Layout + @subsection Construct Layout + + @noindent + The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^} + and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} + layout on the one hand, and uncompact layout + @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand, + can be illustrated by the following examples: + + @iftex + @cartouche + @multitable @columnfractions .5 .5 + @item @i{GNAT style, compact layout} @tab @i{Uncompact layout} + + @item + @smallexample @c ada + type q is record + a : integer; + b : integer; + end record; + @end smallexample + @tab + @smallexample @c ada + type q is + record + a : integer; + b : integer; + end record; + @end smallexample + + @item + @smallexample @c ada + Block : declare + A : Integer := 3; + begin + Proc (A, A); + end Block; + @end smallexample + @tab + @smallexample @c ada + Block : + declare + A : Integer := 3; + begin + Proc (A, A); + end Block; + @end smallexample + + @item + @smallexample @c ada + Clear : for J in 1 .. 10 loop + A (J) := 0; + end loop Clear; + @end smallexample + @tab + @smallexample @c ada + Clear : + for J in 1 .. 10 loop + A (J) := 0; + end loop Clear; + @end smallexample + @end multitable + @end cartouche + @end iftex + + @ifnottex + @smallexample + @cartouche + GNAT style, compact layout Uncompact layout + + type q is record type q is + a : integer; record + b : integer; a : integer; + end record; b : integer; + end record; + + + Block : declare Block : + A : Integer := 3; declare + begin A : Integer := 3; + Proc (A, A); begin + end Block; Proc (A, A); + end Block; + + Clear : for J in 1 .. 10 loop Clear : + A (J) := 0; for J in 1 .. 10 loop + end loop Clear; A (J) := 0; + end loop Clear; + @end cartouche + @end smallexample + @end ifnottex + + @noindent + A further difference between GNAT style layout and compact layout is that + GNAT style layout inserts empty lines as separation for + compound statements, return statements and bodies. + + + @node Name Casing + @subsection Name Casing + + @noindent + @command{gnatpp} always converts the usage occurrence of a (simple) name to + the same casing as the corresponding defining identifier. + + You control the casing for defining occurrences via the + @option{^-n^/NAME_CASING^} switch. + @ifclear vms + With @option{-nD} (``as declared'', which is the default), + @end ifclear + @ifset vms + With @option{/NAME_CASING=AS_DECLARED}, which is the default, + @end ifset + defining occurrences appear exactly as in the source file + where they are declared. + The other ^values for this switch^options for this qualifier^ --- + @option{^-nU^UPPER_CASE^}, + @option{^-nL^LOWER_CASE^}, + @option{^-nM^MIXED_CASE^} --- + result in + ^upper, lower, or mixed case, respectively^the corresponding casing^. + If @command{gnatpp} changes the casing of a defining + occurrence, it analogously changes the casing of all the + usage occurrences of this name. + + If the defining occurrence of a name is not in the source compilation unit + currently being processed by @command{gnatpp}, the casing of each reference to + this name is changed according to the value of the @option{^-n^/NAME_CASING^} + switch (subject to the dictionary file mechanism described below). + Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch + had affected the + casing for the defining occurrence of the name. + + Some names may need to be spelled with casing conventions that are not + covered by the upper-, lower-, and mixed-case transformations. + You can arrange correct casing by placing such names in a + @emph{dictionary file}, + and then supplying a @option{^-D^/DICTIONARY^} switch. + The casing of names from dictionary files overrides + any @option{^-n^/NAME_CASING^} switch. + + To handle the casing of Ada predefined names and the names from GNAT libraries, + @command{gnatpp} assumes a default dictionary file. + The name of each predefined entity is spelled with the same casing as is used + for the entity in the @cite{Ada Reference Manual}. + The name of each entity in the GNAT libraries is spelled with the same casing + as is used in the declaration of that entity. + + The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the + default dictionary file. + Instead, the casing for predefined and GNAT-defined names will be established + by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files. + For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib} + will appear as just shown, + even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch. + To ensure that even such names are rendered in uppercase, + additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch + (or else, less conveniently, place these names in upper case in a dictionary + file). + + A dictionary file is + a plain text file; each line in this file can be either a blank line + (containing only space characters and ASCII.HT characters), an Ada comment + line, or the specification of exactly one @emph{casing schema}. + + A casing schema is a string that has the following syntax: + + @smallexample + @cartouche + @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*] + + @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@} + @end cartouche + @end smallexample + + @noindent + (The @code{[]} metanotation stands for an optional part; + see @cite{Ada Reference Manual}, Section 2.3) for the definition of the + @var{identifier} lexical element and the @var{letter_or_digit} category). + + The casing schema string can be followed by white space and/or an Ada-style + comment; any amount of white space is allowed before the string. + + If a dictionary file is passed as + @ifclear vms + the value of a @option{-D@var{file}} switch + @end ifclear + @ifset vms + an option to the @option{/DICTIONARY} qualifier + @end ifset + then for every + simple name and every identifier, @command{gnatpp} checks if the dictionary + defines the casing for the name or for some of its parts (the term ``subword'' + is used below to denote the part of a name which is delimited by ``_'' or by + the beginning or end of the word and which does not contain any ``_'' inside): + + @itemize @bullet + @item + if the whole name is in the dictionary, @command{gnatpp} uses for this name + the casing defined by the dictionary; no subwords are checked for this word + + @item + for the first subword (that is, for the subword preceding the leftmost + ``_''), @command{gnatpp} checks if the dictionary contains the corresponding + string of the form @code{@var{simple_identifier}*}, and if it does, the + casing of this @var{simple_identifier} is used for this subword + + @item + for the last subword (following the rightmost ``_'') @command{gnatpp} + checks if the dictionary contains the corresponding string of the form + @code{*@var{simple_identifier}}, and if it does, the casing of this + @var{simple_identifier} is used for this subword + + @item + for every intermediate subword (surrounded by two'_') @command{gnatpp} checks + if the dictionary contains the corresponding string of the form + @code{*@var{simple_identifier}*}, and if it does, the casing of this + simple_identifier is used for this subword + + @item + if more than one dictionary file is passed as @command{gnatpp} switches, each + dictionary adds new casing exceptions and overrides all the existing casing + exceptions set by the previous dictionaries + + @item + when @command{gnatpp} checks if the word or subword is in the dictionary, + this check is not case sensitive + @end itemize + + @noindent + For example, suppose we have the following source to reformat: + + @smallexample @c ada + @cartouche + procedure test is + name1 : integer := 1; + name4_name3_name2 : integer := 2; + name2_name3_name4 : Boolean; + name1_var : Float; + begin + name2_name3_name4 := name4_name3_name2 > name1; + end; + @end cartouche + @end smallexample + + @noindent + And suppose we have two dictionaries: + + @smallexample + @cartouche + @i{dict1:} + NAME1 + *NaMe3* + *NAME2 + @end cartouche + + @cartouche + @i{dict2:} + *NAME3* + @end cartouche + @end smallexample + + @noindent + If @command{gnatpp} is called with the following switches: + + @smallexample + @ifclear vms + @command{gnatpp -nM -D dict1 -D dict2 test.adb} + @end ifclear + @ifset vms + @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)} + @end ifset + @end smallexample + + @noindent + then we will get the following name casing in the @command{gnatpp} output: + + @smallexample @c ada + @cartouche + procedure Test is + NAME1 : Integer := 1; + Name4_NAME3_NAME2 : integer := 2; + Name2_NAME3_Name4 : Boolean; + Name1_Var : Float; + begin + Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1; + end Test; + @end cartouche + @end smallexample + + + + @c *********************************** + @node File Name Krunching Using gnatkr + @chapter File Name Krunching Using @code{gnatkr} + @findex gnatkr + + @noindent + This chapter discusses the method used by the compiler to shorten + the default file names chosen for Ada units so that they do not + exceed the maximum length permitted. It also describes the + @code{gnatkr} utility that can be used to determine the result of + applying this shortening. + @menu + * About gnatkr:: + * Using gnatkr:: + * Krunching Method:: + * Examples of gnatkr Usage:: + @end menu + + @node About gnatkr + @section About @code{gnatkr} + + @noindent + The default file naming rule in GNAT + is that the file name must be derived from + the unit name. The exact default rule is as follows: + @itemize @bullet + @item + Take the unit name and replace all dots by hyphens. + @item + If such a replacement occurs in the + second character position of a name, and the first character is + ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character + ^~ (tilde)^$ (dollar sign)^ + instead of a minus. + @end itemize + The reason for this exception is to avoid clashes + with the standard names for children of System, Ada, Interfaces, + and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^ + respectively. + + The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}} + switch of the compiler activates a ``krunching'' + circuit that limits file names to nn characters (where nn is a decimal + integer). For example, using OpenVMS, + where the maximum file name length is + 39, the value of nn is usually set to 39, but if you want to generate + a set of files that would be usable if ported to a system with some + different maximum file length, then a different value can be specified. + The default value of 39 for OpenVMS need not be specified. + + The @code{gnatkr} utility can be used to determine the krunched name for + a given file, when krunched to a specified maximum length. + + @node Using gnatkr + @section Using @code{gnatkr} + + @noindent + The @code{gnatkr} command has the form + + @ifclear vms + @smallexample + $ gnatkr @var{name} [@var{length}] + @end smallexample + @end ifclear + + @ifset vms + @smallexample + $ gnatkr @var{name} /COUNT=nn + @end smallexample + @end ifset + + @noindent + @var{name} is the uncrunched file name, derived from the name of the unit + in the standard manner described in the previous section (i.e. in particular + all dots are replaced by hyphens). The file name may or may not have an + extension (defined as a suffix of the form period followed by arbitrary + characters other than period). If an extension is present then it will + be preserved in the output. For example, when krunching @file{hellofile.ads} + to eight characters, the result will be hellofil.ads. + + Note: for compatibility with previous versions of @code{gnatkr} dots may + appear in the name instead of hyphens, but the last dot will always be + taken as the start of an extension. So if @code{gnatkr} is given an argument + such as @file{Hello.World.adb} it will be treated exactly as if the first + period had been a hyphen, and for example krunching to eight characters + gives the result @file{hellworl.adb}. + + Note that the result is always all lower case (except on OpenVMS where it is + all upper case). Characters of the other case are folded as required. + + @var{length} represents the length of the krunched name. The default + when no argument is given is ^8^39^ characters. A length of zero stands for + unlimited, in other words do not chop except for system files where the + impled crunching length is always eight characters. + + @noindent + The output is the krunched name. The output has an extension only if the + original argument was a file name with an extension. + + @node Krunching Method + @section Krunching Method + + @noindent + The initial file name is determined by the name of the unit that the file + contains. The name is formed by taking the full expanded name of the + unit and replacing the separating dots with hyphens and + using ^lowercase^uppercase^ + for all letters, except that a hyphen in the second character position is + replaced by a ^tilde^dollar sign^ if the first character is + ^a, i, g, or s^A, I, G, or S^. + The extension is @code{.ads} for a + specification and @code{.adb} for a body. + Krunching does not affect the extension, but the file name is shortened to + the specified length by following these rules: + + @itemize @bullet + @item + The name is divided into segments separated by hyphens, tildes or + underscores and all hyphens, tildes, and underscores are + eliminated. If this leaves the name short enough, we are done. + + @item + If the name is too long, the longest segment is located (left-most + if there are two of equal length), and shortened by dropping + its last character. This is repeated until the name is short enough. + + As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb} + to fit the name into 8 characters as required by some operating systems. + + @smallexample + our-strings-wide_fixed 22 + our strings wide fixed 19 + our string wide fixed 18 + our strin wide fixed 17 + our stri wide fixed 16 + our stri wide fixe 15 + our str wide fixe 14 + our str wid fixe 13 + our str wid fix 12 + ou str wid fix 11 + ou st wid fix 10 + ou st wi fix 9 + ou st wi fi 8 + Final file name: oustwifi.adb + @end smallexample + + @item + The file names for all predefined units are always krunched to eight + characters. The krunching of these predefined units uses the following + special prefix replacements: + + @table @file + @item ada- + replaced by @file{^a^A^-} + + @item gnat- + replaced by @file{^g^G^-} + + @item interfaces- + replaced by @file{^i^I^-} + + @item system- + replaced by @file{^s^S^-} + @end table + + These system files have a hyphen in the second character position. That + is why normal user files replace such a character with a + ^tilde^dollar sign^, to + avoid confusion with system file names. + + As an example of this special rule, consider + @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows: + + @smallexample + ada-strings-wide_fixed 22 + a- strings wide fixed 18 + a- string wide fixed 17 + a- strin wide fixed 16 + a- stri wide fixed 15 + a- stri wide fixe 14 + a- str wide fixe 13 + a- str wid fixe 12 + a- str wid fix 11 + a- st wid fix 10 + a- st wi fix 9 + a- st wi fi 8 + Final file name: a-stwifi.adb + @end smallexample + @end itemize + + Of course no file shortening algorithm can guarantee uniqueness over all + possible unit names, and if file name krunching is used then it is your + responsibility to ensure that no name clashes occur. The utility + program @code{gnatkr} is supplied for conveniently determining the + krunched name of a file. + + @node Examples of gnatkr Usage + @section Examples of @code{gnatkr} Usage + + @smallexample + @iftex + @leftskip=0cm + @end iftex + @ifclear vms + $ gnatkr very_long_unit_name.ads --> velounna.ads + $ gnatkr grandparent-parent-child.ads --> grparchi.ads + $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads + $ gnatkr grandparent-parent-child --> grparchi + @end ifclear + $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads + $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads + @end smallexample + + @node Preprocessing Using gnatprep + @chapter Preprocessing Using @code{gnatprep} + @findex gnatprep + + @noindent + The @code{gnatprep} utility provides + a simple preprocessing capability for Ada programs. + It is designed for use with GNAT, but is not dependent on any special + features of GNAT. + + @menu + * Using gnatprep:: + * Switches for gnatprep:: + * Form of Definitions File:: + * Form of Input Text for gnatprep:: + @end menu + + @node Using gnatprep + @section Using @code{gnatprep} + + @noindent + To call @code{gnatprep} use + + @smallexample + $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile] + @end smallexample + + @noindent + where + @table @code + @item infile + is the full name of the input file, which is an Ada source + file containing preprocessor directives. + + @item outfile + is the full name of the output file, which is an Ada source + in standard Ada form. When used with GNAT, this file name will + normally have an ads or adb suffix. + + @item deffile + is the full name of a text file containing definitions of + symbols to be referenced by the preprocessor. This argument is + optional, and can be replaced by the use of the @option{-D} switch. + + @item switches + is an optional sequence of switches as described in the next section. + @end table + + @node Switches for gnatprep + @section Switches for @code{gnatprep} + + @table @option + @c !sort! + + @item ^-b^/BLANK_LINES^ + @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep}) + Causes both preprocessor lines and the lines deleted by + preprocessing to be replaced by blank lines in the output source file, + preserving line numbers in the output file. + + @item ^-c^/COMMENTS^ + @cindex @option{^-c^/COMMENTS^} (@command{gnatprep}) + Causes both preprocessor lines and the lines deleted + by preprocessing to be retained in the output source as comments marked + with the special string @code{"--! "}. This option will result in line numbers + being preserved in the output file. + + @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^ + @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep}) + Defines a new symbol, associated with value. If no value is given on the + command line, then symbol is considered to be @code{True}. This switch + can be used in place of a definition file. + + @ifset vms + @item /REMOVE + @cindex @option{/REMOVE} (@command{gnatprep}) + This is the default setting which causes lines deleted by preprocessing + to be entirely removed from the output file. + @end ifset + + @item ^-r^/REFERENCE^ + @cindex @option{^-r^/REFERENCE^} (@command{gnatprep}) + Causes a @code{Source_Reference} pragma to be generated that + references the original input file, so that error messages will use + the file name of this original file. The use of this switch implies + that preprocessor lines are not to be removed from the file, so its + use will force @option{^-b^/BLANK_LINES^} mode if + @option{^-c^/COMMENTS^} + has not been specified explicitly. + + Note that if the file to be preprocessed contains multiple units, then + it will be necessary to @code{gnatchop} the output file from + @code{gnatprep}. If a @code{Source_Reference} pragma is present + in the preprocessed file, it will be respected by + @code{gnatchop ^-r^/REFERENCE^} + so that the final chopped files will correctly refer to the original + input source file for @code{gnatprep}. + + @item ^-s^/SYMBOLS^ + @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep}) + Causes a sorted list of symbol names and values to be + listed on the standard output file. + + @item ^-u^/UNDEFINED^ + @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep}) + Causes undefined symbols to be treated as having the value FALSE in the context + of a preprocessor test. In the absence of this option, an undefined symbol in + a @code{#if} or @code{#elsif} test will be treated as an error. + + @end table + + @ifclear vms + @noindent + Note: if neither @option{-b} nor @option{-c} is present, + then preprocessor lines and + deleted lines are completely removed from the output, unless -r is + specified, in which case -b is assumed. + @end ifclear + + @node Form of Definitions File + @section Form of Definitions File + + @noindent + The definitions file contains lines of the form + + @smallexample + symbol := value + @end smallexample + + @noindent + where symbol is an identifier, following normal Ada (case-insensitive) + rules for its syntax, and value is one of the following: + + @itemize @bullet + @item + Empty, corresponding to a null substitution + @item + A string literal using normal Ada syntax + @item + Any sequence of characters from the set + (letters, digits, period, underline). + @end itemize + + @noindent + Comment lines may also appear in the definitions file, starting with + the usual @code{--}, + and comments may be added to the definitions lines. + + @node Form of Input Text for gnatprep + @section Form of Input Text for @code{gnatprep} + + @noindent + The input text may contain preprocessor conditional inclusion lines, + as well as general symbol substitution sequences. + + The preprocessor conditional inclusion commands have the form + + @smallexample + @group + @cartouche + #if @i{expression} [then] + lines + #elsif @i{expression} [then] + lines + #elsif @i{expression} [then] + lines + ... + #else + lines + #end if; + @end cartouche + @end group + @end smallexample + + @noindent + In this example, @i{expression} is defined by the following grammar: + @smallexample + @i{expression} ::= + @i{expression} ::= = "" + @i{expression} ::= = + @i{expression} ::= 'Defined + @i{expression} ::= not @i{expression} + @i{expression} ::= @i{expression} and @i{expression} + @i{expression} ::= @i{expression} or @i{expression} + @i{expression} ::= @i{expression} and then @i{expression} + @i{expression} ::= @i{expression} or else @i{expression} + @i{expression} ::= ( @i{expression} ) + @end smallexample + + @noindent + For the first test (@i{expression} ::= ) the symbol must have + either the value true or false, that is to say the right-hand of the + symbol definition must be one of the (case-insensitive) literals + @code{True} or @code{False}. If the value is true, then the + corresponding lines are included, and if the value is false, they are + excluded. + + The test (@i{expression} ::= @code{'Defined}) is true only if + the symbol has been defined in the definition file or by a @option{-D} + switch on the command line. Otherwise, the test is false. + + The equality tests are case insensitive, as are all the preprocessor lines. + + If the symbol referenced is not defined in the symbol definitions file, + then the effect depends on whether or not switch @option{-u} + is specified. If so, then the symbol is treated as if it had the value + false and the test fails. If this switch is not specified, then + it is an error to reference an undefined symbol. It is also an error to + reference a symbol that is defined with a value other than @code{True} + or @code{False}. + + The use of the @code{not} operator inverts the sense of this logical test, so + that the lines are included only if the symbol is not defined. + The @code{then} keyword is optional as shown + + The @code{#} must be the first non-blank character on a line, but + otherwise the format is free form. Spaces or tabs may appear between + the @code{#} and the keyword. The keywords and the symbols are case + insensitive as in normal Ada code. Comments may be used on a + preprocessor line, but other than that, no other tokens may appear on a + preprocessor line. Any number of @code{elsif} clauses can be present, + including none at all. The @code{else} is optional, as in Ada. + + The @code{#} marking the start of a preprocessor line must be the first + non-blank character on the line, i.e. it must be preceded only by + spaces or horizontal tabs. + + Symbol substitution outside of preprocessor lines is obtained by using + the sequence + + @smallexample + $symbol + @end smallexample + + @noindent + anywhere within a source line, except in a comment or within a + string literal. The identifier + following the @code{$} must match one of the symbols defined in the symbol + definition file, and the result is to substitute the value of the + symbol in place of @code{$symbol} in the output file. + + Note that although the substitution of strings within a string literal + is not possible, it is possible to have a symbol whose defined value is + a string literal. So instead of setting XYZ to @code{hello} and writing: + + @smallexample + Header : String := "$XYZ"; + @end smallexample + + @noindent + you should set XYZ to @code{"hello"} and write: + + @smallexample + Header : String := $XYZ; + @end smallexample + + @noindent + and then the substitution will occur as desired. + + @ifset vms + @node The GNAT Run-Time Library Builder gnatlbr + @chapter The GNAT Run-Time Library Builder @code{gnatlbr} + @findex gnatlbr + @cindex Library builder + + @noindent + @code{gnatlbr} is a tool for rebuilding the GNAT run time with user + supplied configuration pragmas. + + @menu + * Running gnatlbr:: + * Switches for gnatlbr:: + * Examples of gnatlbr Usage:: + @end menu + + @node Running gnatlbr + @section Running @code{gnatlbr} + + @noindent + The @code{gnatlbr} command has the form + + @smallexample + $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file] + @end smallexample + + @node Switches for gnatlbr + @section Switches for @code{gnatlbr} + + @noindent + @code{gnatlbr} recognizes the following switches: + + @table @option + @c !sort! + @item /CREATE=directory + @cindex @code{/CREATE} (@code{gnatlbr}) + Create the new run-time library in the specified directory. + + @item /SET=directory + @cindex @code{/SET} (@code{gnatlbr}) + Make the library in the specified directory the current run-time + library. + + @item /DELETE=directory + @cindex @code{/DELETE} (@code{gnatlbr}) + Delete the run-time library in the specified directory. + + @item /CONFIG=file + @cindex @code{/CONFIG} (@code{gnatlbr}) + With /CREATE: + Use the configuration pragmas in the specified file when building + the library. + + With /SET: + Use the configuration pragmas in the specified file when compiling. + + @end table + + @node Examples of gnatlbr Usage + @section Example of @code{gnatlbr} Usage + + @smallexample + Contents of VAXFLOAT.ADC: + pragma Float_Representation (VAX_Float); + + $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC + + GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT] + + @end smallexample + @end ifset + + @node The GNAT Library Browser gnatls + @chapter The GNAT Library Browser @code{gnatls} + @findex gnatls + @cindex Library browser + + @noindent + @code{gnatls} is a tool that outputs information about compiled + units. It gives the relationship between objects, unit names and source + files. It can also be used to check the source dependencies of a unit + as well as various characteristics. + + @menu + * Running gnatls:: + * Switches for gnatls:: + * Examples of gnatls Usage:: + @end menu + + @node Running gnatls + @section Running @code{gnatls} + + @noindent + The @code{gnatls} command has the form + + @smallexample + $ gnatls switches @var{object_or_ali_file} + @end smallexample + + @noindent + The main argument is the list of object or @file{ali} files + (@pxref{The Ada Library Information Files}) + for which information is requested. + + In normal mode, without additional option, @code{gnatls} produces a + four-column listing. Each line represents information for a specific + object. The first column gives the full path of the object, the second + column gives the name of the principal unit in this object, the third + column gives the status of the source and the fourth column gives the + full path of the source representing this unit. + Here is a simple example of use: + + @smallexample + $ gnatls *.o + ^./^[]^demo1.o demo1 DIF demo1.adb + ^./^[]^demo2.o demo2 OK demo2.adb + ^./^[]^hello.o h1 OK hello.adb + ^./^[]^instr-child.o instr.child MOK instr-child.adb + ^./^[]^instr.o instr OK instr.adb + ^./^[]^tef.o tef DIF tef.adb + ^./^[]^text_io_example.o text_io_example OK text_io_example.adb + ^./^[]^tgef.o tgef DIF tgef.adb + @end smallexample + + @noindent + The first line can be interpreted as follows: the main unit which is + contained in + object file @file{demo1.o} is demo1, whose main source is in + @file{demo1.adb}. Furthermore, the version of the source used for the + compilation of demo1 has been modified (DIF). Each source file has a status + qualifier which can be: + + @table @code + @item OK (unchanged) + The version of the source file used for the compilation of the + specified unit corresponds exactly to the actual source file. + + @item MOK (slightly modified) + The version of the source file used for the compilation of the + specified unit differs from the actual source file but not enough to + require recompilation. If you use gnatmake with the qualifier + @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked + MOK will not be recompiled. + + @item DIF (modified) + No version of the source found on the path corresponds to the source + used to build this object. + + @item ??? (file not found) + No source file was found for this unit. + + @item HID (hidden, unchanged version not first on PATH) + The version of the source that corresponds exactly to the source used + for compilation has been found on the path but it is hidden by another + version of the same source that has been modified. + + @end table + + @node Switches for gnatls + @section Switches for @code{gnatls} + + @noindent + @code{gnatls} recognizes the following switches: + + @table @option + @c !sort! + @item ^-a^/ALL_UNITS^ + @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls}) + Consider all units, including those of the predefined Ada library. + Especially useful with @option{^-d^/DEPENDENCIES^}. + + @item ^-d^/DEPENDENCIES^ + @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls}) + List sources from which specified units depend on. + + @item ^-h^/OUTPUT=OPTIONS^ + @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls}) + Output the list of options. + + @item ^-o^/OUTPUT=OBJECTS^ + @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls}) + Only output information about object files. + + @item ^-s^/OUTPUT=SOURCES^ + @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls}) + Only output information about source files. + + @item ^-u^/OUTPUT=UNITS^ + @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls}) + Only output information about compilation units. + + @item ^-aO^/OBJECT_SEARCH=^@var{dir} + @itemx ^-aI^/SOURCE_SEARCH=^@var{dir} + @itemx ^-I^/SEARCH=^@var{dir} + @itemx ^-I-^/NOCURRENT_DIRECTORY^ + @itemx -nostdinc + @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls}) + @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls}) + @cindex @option{^-I^/SEARCH^} (@code{gnatls}) + @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls}) + Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags + (see @ref{Switches for gnatmake}). + + @item --RTS=@var{rts-path} + @cindex @option{--RTS} (@code{gnatls}) + Specifies the default location of the runtime library. Same meaning as the + equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). + + @item ^-v^/OUTPUT=VERBOSE^ + @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls}) + Verbose mode. Output the complete source and object paths. Do not use + the default column layout but instead use long format giving as much as + information possible on each requested units, including special + characteristics such as: + + @table @code + @item Preelaborable + The unit is preelaborable in the Ada 95 sense. + + @item No_Elab_Code + No elaboration code has been produced by the compiler for this unit. + + @item Pure + The unit is pure in the Ada 95 sense. + + @item Elaborate_Body + The unit contains a pragma Elaborate_Body. + + @item Remote_Types + The unit contains a pragma Remote_Types. + + @item Shared_Passive + The unit contains a pragma Shared_Passive. + + @item Predefined + This unit is part of the predefined environment and cannot be modified + by the user. + + @item Remote_Call_Interface + The unit contains a pragma Remote_Call_Interface. + + @end table + + @end table + + @node Examples of gnatls Usage + @section Example of @code{gnatls} Usage + @ifclear vms + + @noindent + Example of using the verbose switch. Note how the source and + object paths are affected by the -I switch. + + @smallexample + $ gnatls -v -I.. demo1.o + + GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc. + + Source Search Path: + + ../ + /home/comar/local/adainclude/ + + Object Search Path: + + ../ + /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/ + + ./demo1.o + Unit => + Name => demo1 + Kind => subprogram body + Flags => No_Elab_Code + Source => demo1.adb modified + @end smallexample + + @noindent + The following is an example of use of the dependency list. + Note the use of the -s switch + which gives a straight list of source files. This can be useful for + building specialized scripts. + + @smallexample + $ gnatls -d demo2.o + ./demo2.o demo2 OK demo2.adb + OK gen_list.ads + OK gen_list.adb + OK instr.ads + OK instr-child.ads + + $ gnatls -d -s -a demo1.o + demo1.adb + /home/comar/local/adainclude/ada.ads + /home/comar/local/adainclude/a-finali.ads + /home/comar/local/adainclude/a-filico.ads + /home/comar/local/adainclude/a-stream.ads + /home/comar/local/adainclude/a-tags.ads + gen_list.ads + gen_list.adb + /home/comar/local/adainclude/gnat.ads + /home/comar/local/adainclude/g-io.ads + instr.ads + /home/comar/local/adainclude/system.ads + /home/comar/local/adainclude/s-exctab.ads + /home/comar/local/adainclude/s-finimp.ads + /home/comar/local/adainclude/s-finroo.ads + /home/comar/local/adainclude/s-secsta.ads + /home/comar/local/adainclude/s-stalib.ads + /home/comar/local/adainclude/s-stoele.ads + /home/comar/local/adainclude/s-stratt.ads + /home/comar/local/adainclude/s-tasoli.ads + /home/comar/local/adainclude/s-unstyp.ads + /home/comar/local/adainclude/unchconv.ads + @end smallexample + @end ifclear + + @ifset vms + @smallexample + GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB + + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads + demo1.adb + gen_list.ads + gen_list.adb + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads + instr.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads + GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads + @end smallexample + @end ifset + + @node Cleaning Up Using gnatclean + @chapter Cleaning Up Using @code{gnatclean} + @findex gnatclean + @cindex Cleaning tool + + @noindent + @code{gnatclean} is a tool that allows the deletion of files produced by the + compiler, binder and linker, including ALI files, object files, tree files, + expanded source files, library files, interface copy source files, binder + generated files and executable files. + + @menu + * Running gnatclean:: + * Switches for gnatclean:: + * Examples of gnatclean Usage:: + @end menu + + @node Running gnatclean + @section Running @code{gnatclean} + + @noindent + The @code{gnatclean} command has the form: + + @smallexample + $ gnatclean switches @var{names} + @end smallexample + + @noindent + @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and + @code{^adb^ADB^} may be omitted. If a project file is specified using switch + @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted. + + @noindent + In normal mode, @code{gnatclean} delete the files produced by the compiler and, + if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and + the linker. In informative-only mode, specified by switch + @code{^-n^/NODELETE^}, the list of files that would have been deleted in + normal mode is listed, but no file is actually deleted. + + @node Switches for gnatclean + @section Switches for @code{gnatclean} + + @noindent + @code{gnatclean} recognizes the following switches: + + @table @option + @c !sort! + @item ^-c^/COMPILER_FILES_ONLY^ + @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean}) + Only attempt to delete the files produced by the compiler, not those produced + by the binder or the linker. The files that are not to be deleted are library + files, interface copy files, binder generated files and executable files. + + @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir} + @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean}) + Indicate that ALI and object files should normally be found in directory + @var{dir}. + + @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^ + @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean}) + When using project files, if some errors or warnings are detected during + parsing and verbose mode is not in effect (no use of switch + ^-v^/VERBOSE^), then error lines start with the full path name of the project + file, rather than its simple file name. + + @item ^-h^/HELP^ + @cindex @option{^-h^/HELP^} (@code{gnatclean}) + Output a message explaining the usage of @code{^gnatclean^gnatclean^}. + + @item ^-n^/NODELETE^ + @cindex @option{^-n^/NODELETE^} (@code{gnatclean}) + Informative-only mode. Do not delete any files. Output the list of the files + that would have been deleted if this switch was not specified. + + @item ^-P^/PROJECT_FILE=^@var{project} + @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean}) + Use project file @var{project}. Only one such switch can be used. + When cleaning a project file, the files produced by the compilation of the + immediate sources or inherited sources of the project files are to be + deleted. This is not depending on the presence or not of executable names + on the command line. + + @item ^-q^/QUIET^ + @cindex @option{^-q^/QUIET^} (@code{gnatclean}) + Quiet output. If there are no error, do not ouuput anything, except in + verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode + (switch ^-n^/NODELETE^). + + @item ^-r^/RECURSIVE^ + @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean}) + When a project file is specified (using switch ^-P^/PROJECT_FILE=^), + clean all imported and extended project files, recursively. If this switch + is not specified, only the files related to the main project file are to be + deleted. This switch has no effect if no project file is specified. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@code{gnatclean}) + Verbose mode. + + @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x} + @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean}) + Indicates the verbosity of the parsing of GNAT project files. + See @ref{Switches Related to Project Files}. + + @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value} + @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean}) + Indicates that external variable @var{name} has the value @var{value}. + The Project Manager will use this value for occurrences of + @code{external(name)} when parsing the project file. + See @ref{Switches Related to Project Files}. + + @item ^-aO^/OBJECT_SEARCH=^@var{dir} + @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean}) + When searching for ALI and object files, look in directory + @var{dir}. + + @item ^-I^/SEARCH=^@var{dir} + @cindex @option{^-I^/SEARCH^} (@code{gnatclean}) + Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}. + + @item ^-I-^/NOCURRENT_DIRECTORY^ + @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean}) + @cindex Source files, suppressing search + Do not look for ALI or object files in the directory + where @code{gnatclean} was invoked. + + @end table + + @node Examples of gnatclean Usage + @section Examples of @code{gnatclean} Usage + + @ifclear vms + @node GNAT and Libraries + @chapter GNAT and Libraries + @cindex Library, building, installing + + @noindent + This chapter addresses some of the issues related to building and using + a library with GNAT. It also shows how the GNAT run-time library can be + recompiled. + + @menu + * Creating an Ada Library:: + * Installing an Ada Library:: + * Using an Ada Library:: + * Creating an Ada Library to be Used in a Non-Ada Context:: + * Rebuilding the GNAT Run-Time Library:: + @end menu + + @node Creating an Ada Library + @section Creating an Ada Library + + @noindent + In the GNAT environment, a library has two components: + @itemize @bullet + @item + Source files. + @item + Compiled code and Ali files. See @ref{The Ada Library Information Files}. + @end itemize + + @noindent + In order to use other packages @ref{The GNAT Compilation Model} + requires a certain number of sources to be available to the compiler. + The minimal set of + sources required includes the specs of all the packages that make up the + visible part of the library as well as all the sources upon which they + depend. The bodies of all visible generic units must also be provided. + @noindent + Although it is not strictly mandatory, it is recommended that all sources + needed to recompile the library be provided, so that the user can make + full use of inter-unit inlining and source-level debugging. This can also + make the situation easier for users that need to upgrade their compilation + toolchain and thus need to recompile the library from sources. + + @noindent + The compiled code can be provided in different ways. The simplest way is + to provide directly the set of objects produced by the compiler during + the compilation of the library. It is also possible to group the objects + into an archive using whatever commands are provided by the operating + system. Finally, it is also possible to create a shared library (see + option -shared in the GCC manual). + + @noindent + There are various possibilities for compiling the units that make up the + library: for example with a Makefile @ref{Using the GNU make Utility}, + or with a conventional script. + For simple libraries, it is also possible to create a + dummy main program which depends upon all the packages that comprise the + interface of the library. This dummy main program can then be given to + gnatmake, in order to build all the necessary objects. Here is an example + of such a dummy program and the generic commands used to build an + archive or a shared library. + + @smallexample @c ada + @iftex + @leftskip=.7cm + @end iftex + with My_Lib.Service1; + with My_Lib.Service2; + with My_Lib.Service3; + procedure My_Lib_Dummy is + begin + null; + end; + @end smallexample + + @smallexample + # compiling the library + $ gnatmake -c my_lib_dummy.adb + + # we don't need the dummy object itself + $ rm my_lib_dummy.o my_lib_dummy.ali + + # create an archive with the remaining objects + $ ar rc libmy_lib.a *.o + # some systems may require "ranlib" to be run as well + + # or create a shared library + $ gcc -shared -o libmy_lib.so *.o + # some systems may require the code to have been compiled with -fPIC + + # remove the object files that are now in the library + $ rm *.o + + # Make the ALI files read-only so that gnatmake will not try to + # regenerate the objects that are in the library + $ chmod -w *.ali + + @end smallexample + + @noindent + When the objects are grouped in an archive or a shared library, the user + needs to specify the desired library at link time, unless a pragma + linker_options has been used in one of the sources: + @smallexample @c ada + pragma Linker_Options ("-lmy_lib"); + @end smallexample + + @noindent + Please note that the library must have a name of the form libxxx.a or + libxxx.so in order to be accessed by the directive -lxxx at link + time. + + @node Installing an Ada Library + @section Installing an Ada Library + + @noindent + In the GNAT model, installing a library consists in copying into a specific + location the files that make up this library. It is possible to install + the sources in a different directory from the other files (ALI, objects, + archives) since the source path and the object path can easily be + specified separately. + + @noindent + For general purpose libraries, it is possible for the system + administrator to put those libraries in the default compiler paths. To + achieve this, he must specify their location in the configuration files + @file{ada_source_path} and @file{ada_object_path} that must be located in + the GNAT + installation tree at the same place as the gcc spec file. The location of + the gcc spec file can be determined as follows: + @smallexample + $ gcc -v + @end smallexample + + @noindent + The configuration files mentioned above have simple format: each line in them + must contain one unique + directory name. Those names are added to the corresponding path + in their order of appearance in the file. The names can be either absolute + or relative, in the latter case, they are relative to where theses files + are located. + + @noindent + @file{ada_source_path} and @file{ada_object_path} might actually not be + present in a + GNAT installation, in which case, GNAT will look for its run-time library in + he directories @file{adainclude} for the sources and @file{adalib} for the + objects and @file{ALI} files. When the files exist, the compiler does not + look in @file{adainclude} and @file{adalib} at all, and thus the + @file{ada_source_path} file + must contain the location for the GNAT run-time sources (which can simply + be @file{adainclude}). In the same way, the @file{ada_object_path} file must + contain the location for the GNAT run-time objects (which can simply + be @file{adalib}). + + @noindent + You can also specify a new default path to the runtime library at compilation + time with the switch @option{--RTS=rts-path}. You can easily choose and change + the runtime you want your program to be compiled with. This switch is + recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref. + + @noindent + It is possible to install a library before or after the standard GNAT + library, by reordering the lines in the configuration files. In general, a + library must be installed before the GNAT library if it redefines + any part of it. + + @node Using an Ada Library + @section Using an Ada Library + + @noindent + In order to use a Ada library, you need to make sure that this + library is on both your source and object path + @ref{Search Paths and the Run-Time Library (RTL)} + and @ref{Search Paths for gnatbind}. For + instance, you can use the library @file{mylib} installed in + @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands: + + @smallexample + $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \ + -largs -lmy_lib + @end smallexample + + @noindent + This can be simplified down to the following: + @smallexample + $ gnatmake my_appl + @end smallexample + when the following conditions are met: + @itemize @bullet + @item + @file{/dir/my_lib_src} has been added by the user to the environment + variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file + @file{ada_source_path} + @item + @file{/dir/my_lib_obj} has been added by the user to the environment + variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file + @file{ada_object_path} + @item + a pragma @code{Linker_Options}, as mentioned in @ref{Creating an Ada Library}, + has been added to the sources. + @end itemize + @noindent + + @node Creating an Ada Library to be Used in a Non-Ada Context + @section Creating an Ada Library to be Used in a Non-Ada Context + + @noindent + The previous sections detailed how to create and install a library that + was usable from an Ada main program. Using this library in a non-Ada + context is not possible, because the elaboration of the library is + automatically done as part of the main program elaboration. + + GNAT also provides the ability to build libraries that can be used both + in an Ada and non-Ada context. This section describes how to build such + a library, and then how to use it from a C program. The method for + interfacing with the library from other languages such as Fortran for + instance remains the same. + + @subsection Creating the Library + + @itemize @bullet + @item Identify the units representing the interface of the library. + + Here is an example of simple library interface: + + @smallexample @c ada + package Interface is + + procedure Do_Something; + + procedure Do_Something_Else; + + end Interface; + @end smallexample + + @item Use @code{pragma Export} or @code{pragma Convention} for the + exported entities. + + Our package @code{Interface} is then updated as follow: + @smallexample @c ada + package Interface is + + procedure Do_Something; + pragma Export (C, Do_Something, "do_something"); + + procedure Do_Something_Else; + pragma Export (C, Do_Something_Else, "do_something_else"); + + end Interface; + @end smallexample + + @item Compile all the units composing the library. + + @item Bind the library objects. + + This step is performed by invoking gnatbind with the @option{-L} + switch. @code{gnatbind} will then generate the library elaboration + procedure (named @code{init}) and the run-time finalization + procedure (named @code{final}). + + @smallexample + # generate the binder file in Ada + $ gnatbind -Lmylib interface + + # generate the binder file in C + $ gnatbind -C -Lmylib interface + @end smallexample + + @item Compile the files generated by the binder + + @smallexample + $ gcc -c b~interface.adb + @end smallexample + + @item Create the library; + + The procedure is identical to the procedure explained in + @ref{Creating an Ada Library}, + except that @file{b~interface.o} needs to be added to + the list of objects. + + @smallexample + # create an archive file + $ ar cr libmylib.a b~interface.o + + # create a shared library + $ gcc -shared -o libmylib.so b~interface.o + @end smallexample + + @item Provide a ``foreign'' view of the library interface; + + The example below shows the content of @code{mylib_interface.h} (note + that there is no rule for the naming of this file, any name can be used) + @smallexample + /* the library elaboration procedure */ + extern void mylibinit (void); + + /* the library finalization procedure */ + extern void mylibfinal (void); + + /* the interface exported by the library */ + extern void do_something (void); + extern void do_something_else (void); + @end smallexample + @end itemize + + @subsection Using the Library + + @noindent + Libraries built as explained above can be used from any program, provided + that the elaboration procedures (named @code{mylibinit} in the previous + example) are called before the library services are used. Any number of + libraries can be used simultaneously, as long as the elaboration + procedure of each library is called. + + Below is an example of C program that uses our @code{mylib} library. + + @smallexample + #include "mylib_interface.h" + + int + main (void) + @{ + /* First, elaborate the library before using it */ + mylibinit (); + + /* Main program, using the library exported entities */ + do_something (); + do_something_else (); + + /* Library finalization at the end of the program */ + mylibfinal (); + return 0; + @} + @end smallexample + + @noindent + Note that this same library can be used from an equivalent Ada main + program. In addition, if the libraries are installed as detailed in + @ref{Installing an Ada Library}, it is not necessary to invoke the + library elaboration and finalization routines. The binder will ensure + that this is done as part of the main program elaboration and + finalization phases. + + @subsection The Finalization Phase + + @noindent + Invoking any library finalization procedure generated by @code{gnatbind} + shuts down the Ada run time permanently. Consequently, the finalization + of all Ada libraries must be performed at the end of the program. No + call to these libraries nor the Ada run time should be made past the + finalization phase. + + @subsection Restrictions in Libraries + + @noindent + The pragmas listed below should be used with caution inside libraries, + as they can create incompatibilities with other Ada libraries: + @itemize @bullet + @item pragma @code{Locking_Policy} + @item pragma @code{Queuing_Policy} + @item pragma @code{Task_Dispatching_Policy} + @item pragma @code{Unreserve_All_Interrupts} + @end itemize + When using a library that contains such pragmas, the user must make sure + that all libraries use the same pragmas with the same values. Otherwise, + a @code{Program_Error} will + be raised during the elaboration of the conflicting + libraries. The usage of these pragmas and its consequences for the user + should therefore be well documented. + + Similarly, the traceback in exception occurrences mechanism should be + enabled or disabled in a consistent manner across all libraries. + Otherwise, a Program_Error will be raised during the elaboration of the + conflicting libraries. + + If the @code{'Version} and @code{'Body_Version} + attributes are used inside a library, then it is necessary to + perform a @code{gnatbind} step that mentions all @file{ALI} files in all + libraries, so that version identifiers can be properly computed. + In practice these attributes are rarely used, so this is unlikely + to be a consideration. + + @node Rebuilding the GNAT Run-Time Library + @section Rebuilding the GNAT Run-Time Library + + @noindent + It may be useful to recompile the GNAT library in various contexts, the + most important one being the use of partition-wide configuration pragmas + such as Normalize_Scalar. A special Makefile called + @code{Makefile.adalib} is provided to that effect and can be found in + the directory containing the GNAT library. The location of this + directory depends on the way the GNAT environment has been installed and can + be determined by means of the command: + + @smallexample + $ gnatls -v + @end smallexample + + @noindent + The last entry in the object search path usually contains the + gnat library. This Makefile contains its own documentation and in + particular the set of instructions needed to rebuild a new library and + to use it. + + @node Using the GNU make Utility + @chapter Using the GNU @code{make} Utility + @findex make + + @noindent + This chapter offers some examples of makefiles that solve specific + problems. It does not explain how to write a makefile (see the GNU make + documentation), nor does it try to replace the @code{gnatmake} utility + (@pxref{The GNAT Make Program gnatmake}). + + All the examples in this section are specific to the GNU version of + make. Although @code{make} is a standard utility, and the basic language + is the same, these examples use some advanced features found only in + @code{GNU make}. + + @menu + * Using gnatmake in a Makefile:: + * Automatically Creating a List of Directories:: + * Generating the Command Line Switches:: + * Overcoming Command Line Length Limits:: + @end menu + + @node Using gnatmake in a Makefile + @section Using gnatmake in a Makefile + @findex makefile + @cindex GNU make + + @noindent + Complex project organizations can be handled in a very powerful way by + using GNU make combined with gnatmake. For instance, here is a Makefile + which allows you to build each subsystem of a big project into a separate + shared library. Such a makefile allows you to significantly reduce the link + time of very big applications while maintaining full coherence at + each step of the build process. + + The list of dependencies are handled automatically by + @code{gnatmake}. The Makefile is simply used to call gnatmake in each of + the appropriate directories. + + Note that you should also read the example on how to automatically + create the list of directories + (@pxref{Automatically Creating a List of Directories}) + which might help you in case your project has a lot of subdirectories. + + @smallexample + @iftex + @leftskip=0cm + @font@heightrm=cmr8 + @heightrm + @end iftex + ## This Makefile is intended to be used with the following directory + ## configuration: + ## - The sources are split into a series of csc (computer software components) + ## Each of these csc is put in its own directory. + ## Their name are referenced by the directory names. + ## They will be compiled into shared library (although this would also work + ## with static libraries + ## - The main program (and possibly other packages that do not belong to any + ## csc is put in the top level directory (where the Makefile is). + ## toplevel_dir __ first_csc (sources) __ lib (will contain the library) + ## \_ second_csc (sources) __ lib (will contain the library) + ## \_ ... + ## Although this Makefile is build for shared library, it is easy to modify + ## to build partial link objects instead (modify the lines with -shared and + ## gnatlink below) + ## + ## With this makefile, you can change any file in the system or add any new + ## file, and everything will be recompiled correctly (only the relevant shared + ## objects will be recompiled, and the main program will be re-linked). + + # The list of computer software component for your project. This might be + # generated automatically. + CSC_LIST=aa bb cc + + # Name of the main program (no extension) + MAIN=main + + # If we need to build objects with -fPIC, uncomment the following line + #NEED_FPIC=-fPIC + + # The following variable should give the directory containing libgnat.so + # You can get this directory through 'gnatls -v'. This is usually the last + # directory in the Object_Path. + GLIB=... + + # The directories for the libraries + # (This macro expands the list of CSC to the list of shared libraries, you + # could simply use the expanded form : + # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so + LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@} + + $@{MAIN@}: objects $@{LIB_DIR@} + gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared + gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@} + + objects:: + # recompile the sources + gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@} + + # Note: In a future version of GNAT, the following commands will be simplified + # by a new tool, gnatmlib + $@{LIB_DIR@}: + mkdir -p $@{dir $@@ @} + cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat + cd $@{dir $@@ @}; cp -f ../*.ali . + + # The dependencies for the modules + # Note that we have to force the expansion of *.o, since in some cases + # make won't be able to do it itself. + aa/lib/libaa.so: $@{wildcard aa/*.o@} + bb/lib/libbb.so: $@{wildcard bb/*.o@} + cc/lib/libcc.so: $@{wildcard cc/*.o@} + + # Make sure all of the shared libraries are in the path before starting the + # program + run:: + LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@} + + clean:: + $@{RM@} -rf $@{CSC_LIST:%=%/lib@} + $@{RM@} $@{CSC_LIST:%=%/*.ali@} + $@{RM@} $@{CSC_LIST:%=%/*.o@} + $@{RM@} *.o *.ali $@{MAIN@} + @end smallexample + + @node Automatically Creating a List of Directories + @section Automatically Creating a List of Directories + + @noindent + In most makefiles, you will have to specify a list of directories, and + store it in a variable. For small projects, it is often easier to + specify each of them by hand, since you then have full control over what + is the proper order for these directories, which ones should be + included... + + However, in larger projects, which might involve hundreds of + subdirectories, it might be more convenient to generate this list + automatically. + + The example below presents two methods. The first one, although less + general, gives you more control over the list. It involves wildcard + characters, that are automatically expanded by @code{make}. Its + shortcoming is that you need to explicitly specify some of the + organization of your project, such as for instance the directory tree + depth, whether some directories are found in a separate tree,... + + The second method is the most general one. It requires an external + program, called @code{find}, which is standard on all Unix systems. All + the directories found under a given root directory will be added to the + list. + + @smallexample + @iftex + @leftskip=0cm + @font@heightrm=cmr8 + @heightrm + @end iftex + # The examples below are based on the following directory hierarchy: + # All the directories can contain any number of files + # ROOT_DIRECTORY -> a -> aa -> aaa + # -> ab + # -> ac + # -> b -> ba -> baa + # -> bb + # -> bc + # This Makefile creates a variable called DIRS, that can be reused any time + # you need this list (see the other examples in this section) + + # The root of your project's directory hierarchy + ROOT_DIRECTORY=. + + #### + # First method: specify explicitly the list of directories + # This allows you to specify any subset of all the directories you need. + #### + + DIRS := a/aa/ a/ab/ b/ba/ + + #### + # Second method: use wildcards + # Note that the argument(s) to wildcard below should end with a '/'. + # Since wildcards also return file names, we have to filter them out + # to avoid duplicate directory names. + # We thus use make's @code{dir} and @code{sort} functions. + # It sets DIRs to the following value (note that the directories aaa and baa + # are not given, unless you change the arguments to wildcard). + # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/ + #### + + DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ + $@{ROOT_DIRECTORY@}/*/*/@}@}@} + + #### + # Third method: use an external program + # This command is much faster if run on local disks, avoiding NFS slowdowns. + # This is the most complete command: it sets DIRs to the following value: + # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc + #### + + DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@} + + @end smallexample + + @node Generating the Command Line Switches + @section Generating the Command Line Switches + + @noindent + Once you have created the list of directories as explained in the + previous section (@pxref{Automatically Creating a List of Directories}), + you can easily generate the command line arguments to pass to gnatmake. + + For the sake of completeness, this example assumes that the source path + is not the same as the object path, and that you have two separate lists + of directories. + + @smallexample + # see "Automatically creating a list of directories" to create + # these variables + SOURCE_DIRS= + OBJECT_DIRS= + + GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@} + GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@} + + all: + gnatmake $@{GNATMAKE_SWITCHES@} main_unit + @end smallexample + + @node Overcoming Command Line Length Limits + @section Overcoming Command Line Length Limits + + @noindent + One problem that might be encountered on big projects is that many + operating systems limit the length of the command line. It is thus hard to give + gnatmake the list of source and object directories. + + This example shows how you can set up environment variables, which will + make @code{gnatmake} behave exactly as if the directories had been + specified on the command line, but have a much higher length limit (or + even none on most systems). + + It assumes that you have created a list of directories in your Makefile, + using one of the methods presented in + @ref{Automatically Creating a List of Directories}. + For the sake of completeness, we assume that the object + path (where the ALI files are found) is different from the sources patch. + + Note a small trick in the Makefile below: for efficiency reasons, we + create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are + expanded immediately by @code{make}. This way we overcome the standard + make behavior which is to expand the variables only when they are + actually used. + + On Windows, if you are using the standard Windows command shell, you must + replace colons with semicolons in the assignments to these variables. + + @smallexample + @iftex + @leftskip=0cm + @font@heightrm=cmr8 + @heightrm + @end iftex + # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH. + # This is the same thing as putting the -I arguments on the command line. + # (the equivalent of using -aI on the command line would be to define + # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH). + # You can of course have different values for these variables. + # + # Note also that we need to keep the previous values of these variables, since + # they might have been set before running 'make' to specify where the GNAT + # library is installed. + + # see "Automatically creating a list of directories" to create these + # variables + SOURCE_DIRS= + OBJECT_DIRS= + + empty:= + space:=$@{empty@} $@{empty@} + SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@} + OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@} + ADA_INCLUDE_PATH += $@{SOURCE_LIST@} + ADA_OBJECT_PATH += $@{OBJECT_LIST@} + export ADA_INCLUDE_PATH + export ADA_OBJECT_PATH + + all: + gnatmake main_unit + @end smallexample + @end ifclear + + + @node Finding Memory Problems + @chapter Finding Memory Problems + + @noindent + This chapter describes + @ifclear vms + the @command{gnatmem} tool, which can be used to track down + ``memory leaks'', and + @end ifclear + the GNAT Debug Pool facility, which can be used to detect incorrect uses of + access values (including ``dangling references''). + + @menu + @ifclear vms + * The gnatmem Tool:: + @end ifclear + * The GNAT Debug Pool Facility:: + @end menu + + + @ifclear vms + @node The gnatmem Tool + @section The @command{gnatmem} Tool + @findex gnatmem + + @noindent + The @code{gnatmem} utility monitors dynamic allocation and + deallocation activity in a program, and displays information about + incorrect deallocations and possible sources of memory leaks. + It provides three type of information: + @itemize @bullet + @item + General information concerning memory management, such as the total + number of allocations and deallocations, the amount of allocated + memory and the high water mark, i.e. the largest amount of allocated + memory in the course of program execution. + + @item + Backtraces for all incorrect deallocations, that is to say deallocations + which do not correspond to a valid allocation. + + @item + Information on each allocation that is potentially the origin of a memory + leak. + @end itemize + + @menu + * Running gnatmem:: + * Switches for gnatmem:: + * Example of gnatmem Usage:: + @end menu + + @node Running gnatmem + @subsection Running @code{gnatmem} + + @noindent + @code{gnatmem} makes use of the output created by the special version of + allocation and deallocation routines that record call information. This + allows to obtain accurate dynamic memory usage history at a minimal cost to + the execution speed. Note however, that @code{gnatmem} is not supported on + all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86, + Solaris (sparc and x86) and Windows NT/2000/XP (x86). + + @noindent + The @code{gnatmem} command has the form + + @smallexample + $ gnatmem [switches] user_program + @end smallexample + + @noindent + The program must have been linked with the instrumented version of the + allocation and deallocation routines. This is done by linking with the + @file{libgmem.a} library. For correct symbolic backtrace information, + the user program should be compiled with debugging options + @ref{Switches for gcc}. For example to build @file{my_program}: + + @smallexample + $ gnatmake -g my_program -largs -lgmem + @end smallexample + + @noindent + When running @file{my_program} the file @file{gmem.out} is produced. This file + contains information about all allocations and deallocations done by the + program. It is produced by the instrumented allocations and + deallocations routines and will be used by @code{gnatmem}. + + @noindent + Gnatmem must be supplied with the @file{gmem.out} file and the executable to + examine. If the location of @file{gmem.out} file was not explicitly supplied by + @code{-i} switch, gnatmem will assume that this file can be found in the + current directory. For example, after you have executed @file{my_program}, + @file{gmem.out} can be analyzed by @code{gnatmem} using the command: + + @smallexample + $ gnatmem my_program + @end smallexample + + @noindent + This will produce the output with the following format: + + *************** debut cc + @smallexample + $ gnatmem my_program + + Global information + ------------------ + Total number of allocations : 45 + Total number of deallocations : 6 + Final Water Mark (non freed mem) : 11.29 Kilobytes + High Water Mark : 11.40 Kilobytes + + . + . + . + Allocation Root # 2 + ------------------- + Number of non freed allocations : 11 + Final Water Mark (non freed mem) : 1.16 Kilobytes + High Water Mark : 1.27 Kilobytes + Backtrace : + my_program.adb:23 my_program.alloc + . + . + . + @end smallexample + + The first block of output gives general information. In this case, the + Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an + Unchecked_Deallocation routine occurred. + + @noindent + Subsequent paragraphs display information on all allocation roots. + An allocation root is a specific point in the execution of the program + that generates some dynamic allocation, such as a ``@code{@b{new}}'' + construct. This root is represented by an execution backtrace (or subprogram + call stack). By default the backtrace depth for allocations roots is 1, so + that a root corresponds exactly to a source location. The backtrace can + be made deeper, to make the root more specific. + + @node Switches for gnatmem + @subsection Switches for @code{gnatmem} + + @noindent + @code{gnatmem} recognizes the following switches: + + @table @option + + @item -q + @cindex @option{-q} (@code{gnatmem}) + Quiet. Gives the minimum output needed to identify the origin of the + memory leaks. Omits statistical information. + + @item @var{N} + @cindex @var{N} (@code{gnatmem}) + N is an integer literal (usually between 1 and 10) which controls the + depth of the backtraces defining allocation root. The default value for + N is 1. The deeper the backtrace, the more precise the localization of + the root. Note that the total number of roots can depend on this + parameter. This parameter must be specified @emph{before} the name of the + executable to be analyzed, to avoid ambiguity. + + @item -b n + @cindex @option{-b} (@code{gnatmem}) + This switch has the same effect as just depth parameter. + + @item -i @var{file} + @cindex @option{-i} (@code{gnatmem}) + Do the @code{gnatmem} processing starting from @file{file}, rather than + @file{gmem.out} in the current directory. + + @item -m n + @cindex @option{-m} (@code{gnatmem}) + This switch causes @code{gnatmem} to mask the allocation roots that have less + than n leaks. The default value is 1. Specifying the value of 0 will allow to + examine even the roots that didn't result in leaks. + + @item -s order + @cindex @option{-s} (@code{gnatmem}) + This switch causes @code{gnatmem} to sort the allocation roots according to the + specified order of sort criteria, each identified by a single letter. The + currently supported criteria are @code{n, h, w} standing respectively for + number of unfreed allocations, high watermark, and final watermark + corresponding to a specific root. The default order is @code{nwh}. + + @end table + + @node Example of gnatmem Usage + @subsection Example of @code{gnatmem} Usage + + @noindent + The following example shows the use of @code{gnatmem} + on a simple memory-leaking program. + Suppose that we have the following Ada program: + + @smallexample @c ada + @group + @cartouche + with Unchecked_Deallocation; + procedure Test_Gm is + + type T is array (1..1000) of Integer; + type Ptr is access T; + procedure Free is new Unchecked_Deallocation (T, Ptr); + A : Ptr; + + procedure My_Alloc is + begin + A := new T; + end My_Alloc; + + procedure My_DeAlloc is + B : Ptr := A; + begin + Free (B); + end My_DeAlloc; + + begin + My_Alloc; + for I in 1 .. 5 loop + for J in I .. 5 loop + My_Alloc; + end loop; + My_Dealloc; + end loop; + end; + @end cartouche + @end group + @end smallexample + + @noindent + The program needs to be compiled with debugging option and linked with + @code{gmem} library: + + @smallexample + $ gnatmake -g test_gm -largs -lgmem + @end smallexample + + @noindent + Then we execute the program as usual: + + @smallexample + $ test_gm + @end smallexample + + @noindent + Then @code{gnatmem} is invoked simply with + @smallexample + $ gnatmem test_gm + @end smallexample + + @noindent + which produces the following output (result may vary on different platforms): + + @smallexample + Global information + ------------------ + Total number of allocations : 18 + Total number of deallocations : 5 + Final Water Mark (non freed mem) : 53.00 Kilobytes + High Water Mark : 56.90 Kilobytes + + Allocation Root # 1 + ------------------- + Number of non freed allocations : 11 + Final Water Mark (non freed mem) : 42.97 Kilobytes + High Water Mark : 46.88 Kilobytes + Backtrace : + test_gm.adb:11 test_gm.my_alloc + + Allocation Root # 2 + ------------------- + Number of non freed allocations : 1 + Final Water Mark (non freed mem) : 10.02 Kilobytes + High Water Mark : 10.02 Kilobytes + Backtrace : + s-secsta.adb:81 system.secondary_stack.ss_init + + Allocation Root # 3 + ------------------- + Number of non freed allocations : 1 + Final Water Mark (non freed mem) : 12 Bytes + High Water Mark : 12 Bytes + Backtrace : + s-secsta.adb:181 system.secondary_stack.ss_init + @end smallexample + + @noindent + Note that the GNAT run time contains itself a certain number of + allocations that have no corresponding deallocation, + as shown here for root #2 and root + #3. This is a normal behavior when the number of non freed allocations + is one, it allocates dynamic data structures that the run time needs for + the complete lifetime of the program. Note also that there is only one + allocation root in the user program with a single line back trace: + test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the + program shows that 'My_Alloc' is called at 2 different points in the + source (line 21 and line 24). If those two allocation roots need to be + distinguished, the backtrace depth parameter can be used: + + @smallexample + $ gnatmem 3 test_gm + @end smallexample + + @noindent + which will give the following output: + + @smallexample + Global information + ------------------ + Total number of allocations : 18 + Total number of deallocations : 5 + Final Water Mark (non freed mem) : 53.00 Kilobytes + High Water Mark : 56.90 Kilobytes + + Allocation Root # 1 + ------------------- + Number of non freed allocations : 10 + Final Water Mark (non freed mem) : 39.06 Kilobytes + High Water Mark : 42.97 Kilobytes + Backtrace : + test_gm.adb:11 test_gm.my_alloc + test_gm.adb:24 test_gm + b_test_gm.c:52 main + + Allocation Root # 2 + ------------------- + Number of non freed allocations : 1 + Final Water Mark (non freed mem) : 10.02 Kilobytes + High Water Mark : 10.02 Kilobytes + Backtrace : + s-secsta.adb:81 system.secondary_stack.ss_init + s-secsta.adb:283 + b_test_gm.c:33 adainit + + Allocation Root # 3 + ------------------- + Number of non freed allocations : 1 + Final Water Mark (non freed mem) : 3.91 Kilobytes + High Water Mark : 3.91 Kilobytes + Backtrace : + test_gm.adb:11 test_gm.my_alloc + test_gm.adb:21 test_gm + b_test_gm.c:52 main + + Allocation Root # 4 + ------------------- + Number of non freed allocations : 1 + Final Water Mark (non freed mem) : 12 Bytes + High Water Mark : 12 Bytes + Backtrace : + s-secsta.adb:181 system.secondary_stack.ss_init + s-secsta.adb:283 + b_test_gm.c:33 adainit + @end smallexample + + @noindent + The allocation root #1 of the first example has been split in 2 roots #1 + and #3 thanks to the more precise associated backtrace. + + @end ifclear + + + @node The GNAT Debug Pool Facility + @section The GNAT Debug Pool Facility + @findex Debug Pool + @cindex storage, pool, memory corruption + + @noindent + The use of unchecked deallocation and unchecked conversion can easily + lead to incorrect memory references. The problems generated by such + references are usually difficult to tackle because the symptoms can be + very remote from the origin of the problem. In such cases, it is + very helpful to detect the problem as early as possible. This is the + purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. + + In order to use the GNAT specific debugging pool, the user must + associate a debug pool object with each of the access types that may be + related to suspected memory problems. See Ada Reference Manual 13.11. + @smallexample @c ada + type Ptr is access Some_Type; + Pool : GNAT.Debug_Pools.Debug_Pool; + for Ptr'Storage_Pool use Pool; + @end smallexample + + @noindent + @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of + pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools, + allow the user to redefine allocation and deallocation strategies. They + also provide a checkpoint for each dereference, through the use of + the primitive operation @code{Dereference} which is implicitly called at + each dereference of an access value. + + Once an access type has been associated with a debug pool, operations on + values of the type may raise four distinct exceptions, + which correspond to four potential kinds of memory corruption: + @itemize @bullet + @item + @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} + @item + @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} + @item + @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} + @item + @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } + @end itemize + + @noindent + For types associated with a Debug_Pool, dynamic allocation is performed using + the standard + GNAT allocation routine. References to all allocated chunks of memory + are kept in an internal dictionary. + Several deallocation strategies are provided, whereupon the user can choose + to release the memory to the system, keep it allocated for further invalid + access checks, or fill it with an easily recognizable pattern for debug + sessions. + The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}. + + See the documentation in the file g-debpoo.ads for more information on the + various strategies. + + Upon each dereference, a check is made that the access value denotes a + properly allocated memory location. Here is a complete example of use of + @code{Debug_Pools}, that includes typical instances of memory corruption: + @smallexample @c ada + @iftex + @leftskip=0cm + @end iftex + with Gnat.Io; use Gnat.Io; + with Unchecked_Deallocation; + with Unchecked_Conversion; + with GNAT.Debug_Pools; + with System.Storage_Elements; + with Ada.Exceptions; use Ada.Exceptions; + procedure Debug_Pool_Test is + + type T is access Integer; + type U is access all T; + + P : GNAT.Debug_Pools.Debug_Pool; + for T'Storage_Pool use P; + + procedure Free is new Unchecked_Deallocation (Integer, T); + function UC is new Unchecked_Conversion (U, T); + A, B : aliased T; + + procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line); + + begin + Info (P); + A := new Integer; + B := new Integer; + B := A; + Info (P); + Free (A); + begin + Put_Line (Integer'Image(B.all)); + exception + when E : others => Put_Line ("raised: " & Exception_Name (E)); + end; + begin + Free (B); + exception + when E : others => Put_Line ("raised: " & Exception_Name (E)); + end; + B := UC(A'Access); + begin + Put_Line (Integer'Image(B.all)); + exception + when E : others => Put_Line ("raised: " & Exception_Name (E)); + end; + begin + Free (B); + exception + when E : others => Put_Line ("raised: " & Exception_Name (E)); + end; + Info (P); + end Debug_Pool_Test; + @end smallexample + + @noindent + The debug pool mechanism provides the following precise diagnostics on the + execution of this erroneous program: + @smallexample + Debug Pool info: + Total allocated bytes : 0 + Total deallocated bytes : 0 + Current Water Mark: 0 + High Water Mark: 0 + + Debug Pool info: + Total allocated bytes : 8 + Total deallocated bytes : 0 + Current Water Mark: 8 + High Water Mark: 8 + + raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE + raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE + raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE + raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE + Debug Pool info: + Total allocated bytes : 8 + Total deallocated bytes : 4 + Current Water Mark: 4 + High Water Mark: 8 + @end smallexample + + + @node Creating Sample Bodies Using gnatstub + @chapter Creating Sample Bodies Using @command{gnatstub} + @findex gnatstub + + @noindent + @command{gnatstub} creates body stubs, that is, empty but compilable bodies + for library unit declarations. + + To create a body stub, @command{gnatstub} has to compile the library + unit declaration. Therefore, bodies can be created only for legal + library units. Moreover, if a library unit depends semantically upon + units located outside the current directory, you have to provide + the source search path when calling @command{gnatstub}, see the description + of @command{gnatstub} switches below. + + @menu + * Running gnatstub:: + * Switches for gnatstub:: + @end menu + + @node Running gnatstub + @section Running @command{gnatstub} + + @noindent + @command{gnatstub} has the command-line interface of the form + + @smallexample + $ gnatstub [switches] filename [directory] + @end smallexample + + @noindent + where + @table @emph + @item filename + is the name of the source file that contains a library unit declaration + for which a body must be created. The file name may contain the path + information. + The file name does not have to follow the GNAT file name conventions. If the + name + does not follow GNAT file naming conventions, the name of the body file must + be provided + explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option. + If the file name follows the GNAT file naming + conventions and the name of the body file is not provided, + @command{gnatstub} + creates the name + of the body file from the argument file name by replacing the @file{.ads} + suffix + with the @file{.adb} suffix. + + @item directory + indicates the directory in which the body stub is to be placed (the default + is the + current directory) + + @item switches + is an optional sequence of switches as described in the next section + @end table + + @node Switches for gnatstub + @section Switches for @command{gnatstub} + + @table @option + @c !sort! + + @item ^-f^/FULL^ + @cindex @option{^-f^/FULL^} (@command{gnatstub}) + If the destination directory already contains a file with the name of the + body file + for the argument spec file, replace it with the generated body stub. + + @item ^-hs^/HEADER=SPEC^ + @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub}) + Put the comment header (i.e., all the comments preceding the + compilation unit) from the source of the library unit declaration + into the body stub. + + @item ^-hg^/HEADER=GENERAL^ + @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub}) + Put a sample comment header into the body stub. + + @ifclear vms + @item -IDIR + @cindex @option{-IDIR} (@command{gnatstub}) + @itemx -I- + @cindex @option{-I-} (@command{gnatstub}) + @end ifclear + @ifset vms + @item /NOCURRENT_DIRECTORY + @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub}) + @end ifset + ^These switches have ^This switch has^ the same meaning as in calls to + @command{gcc}. + ^They define ^It defines ^ the source search path in the call to + @command{gcc} issued + by @command{gnatstub} to compile an argument source file. + + @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH} + @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub}) + This switch has the same meaning as in calls to @command{gcc}. + It defines the additional configuration file to be passed to the call to + @command{gcc} issued + by @command{gnatstub} to compile an argument source file. + + @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n} + @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub}) + (@var{n} is a non-negative integer). Set the maximum line length in the + body stub to @var{n}; the default is 79. The maximum value that can be + specified is 32767. + + @item ^-gnaty^/STYLE_CHECKS=^@var{n} + @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub}) + (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in + the generated body sample to @var{n}. + The default indentation is 3. + + @item ^-gnatyo^/ORDERED_SUBPROGRAMS^ + @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub}) + Order local bodies alphabetically. (By default local bodies are ordered + in the same way as the corresponding local specs in the argument spec file.) + + @item ^-i^/INDENTATION=^@var{n} + @cindex @option{^-i^/INDENTATION^} (@command{gnatstub}) + Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}} + + @item ^-k^/TREE_FILE=SAVE^ + @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub}) + Do not remove the tree file (i.e., the snapshot of the compiler internal + structures used by @command{gnatstub}) after creating the body stub. + + @item ^-l^/LINE_LENGTH=^@var{n} + @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub}) + Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}} + + @item ^-o^/BODY=^@var{body-name} + @cindex @option{^-o^/BODY^} (@command{gnatstub}) + Body file name. This should be set if the argument file name does not + follow + the GNAT file naming + conventions. If this switch is omitted the default name for the body will be + obtained + from the argument file name according to the GNAT file naming conventions. + + @item ^-q^/QUIET^ + @cindex @option{^-q^/QUIET^} (@command{gnatstub}) + Quiet mode: do not generate a confirmation when a body is + successfully created, and do not generate a message when a body is not + required for an + argument unit. + + @item ^-r^/TREE_FILE=REUSE^ + @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub}) + Reuse the tree file (if it exists) instead of creating it. Instead of + creating the tree file for the library unit declaration, @command{gnatstub} + tries to find it in the current directory and use it for creating + a body. If the tree file is not found, no body is created. This option + also implies @option{^-k^/SAVE^}, whether or not + the latter is set explicitly. + + @item ^-t^/TREE_FILE=OVERWRITE^ + @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub}) + Overwrite the existing tree file. If the current directory already + contains the file which, according to the GNAT file naming rules should + be considered as a tree file for the argument source file, + @command{gnatstub} + will refuse to create the tree file needed to create a sample body + unless this option is set. + + @item ^-v^/VERBOSE^ + @cindex @option{^-v^/VERBOSE^} (@command{gnatstub}) + Verbose mode: generate version information. + + @end table + + + @node Other Utility Programs + @chapter Other Utility Programs + + @noindent + This chapter discusses some other utility programs available in the Ada + environment. + + @menu + * Using Other Utility Programs with GNAT:: + * The External Symbol Naming Scheme of GNAT:: + @ifclear vms + * Ada Mode for Glide:: + @end ifclear + * Converting Ada Files to html with gnathtml:: + * Installing gnathtml:: + @ifset vms + * LSE:: + * Profiling:: + @end ifset + @end menu + + @node Using Other Utility Programs with GNAT + @section Using Other Utility Programs with GNAT + + @noindent + The object files generated by GNAT are in standard system format and in + particular the debugging information uses this format. This means + programs generated by GNAT can be used with existing utilities that + depend on these formats. + + @ifclear vms + In general, any utility program that works with C will also often work with + Ada programs generated by GNAT. This includes software utilities such as + gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such + as Purify. + @end ifclear + + @node The External Symbol Naming Scheme of GNAT + @section The External Symbol Naming Scheme of GNAT + + @noindent + In order to interpret the output from GNAT, when using tools that are + originally intended for use with other languages, it is useful to + understand the conventions used to generate link names from the Ada + entity names. + + All link names are in all lowercase letters. With the exception of library + procedure names, the mechanism used is simply to use the full expanded + Ada name with dots replaced by double underscores. For example, suppose + we have the following package spec: + + @smallexample @c ada + @group + @cartouche + package QRS is + MN : Integer; + end QRS; + @end cartouche + @end group + @end smallexample + + @noindent + The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so + the corresponding link name is @code{qrs__mn}. + @findex Export + Of course if a @code{pragma Export} is used this may be overridden: + + @smallexample @c ada + @group + @cartouche + package Exports is + Var1 : Integer; + pragma Export (Var1, C, External_Name => "var1_name"); + Var2 : Integer; + pragma Export (Var2, C, Link_Name => "var2_link_name"); + end Exports; + @end cartouche + @end group + @end smallexample + + @noindent + In this case, the link name for @var{Var1} is whatever link name the + C compiler would assign for the C function @var{var1_name}. This typically + would be either @var{var1_name} or @var{_var1_name}, depending on operating + system conventions, but other possibilities exist. The link name for + @var{Var2} is @var{var2_link_name}, and this is not operating system + dependent. + + @findex _main + One exception occurs for library level procedures. A potential ambiguity + arises between the required name @code{_main} for the C main program, + and the name we would otherwise assign to an Ada library level procedure + called @code{Main} (which might well not be the main program). + + To avoid this ambiguity, we attach the prefix @code{_ada_} to such + names. So if we have a library level procedure such as + + @smallexample @c ada + @group + @cartouche + procedure Hello (S : String); + @end cartouche + @end group + @end smallexample + + @noindent + the external name of this procedure will be @var{_ada_hello}. + + @ifclear vms + @node Ada Mode for Glide + @section Ada Mode for @code{Glide} + @cindex Ada mode (for Glide) + + @noindent + The Glide mode for programming in Ada (both Ada83 and Ada95) helps the + user to understand and navigate existing code, and facilitates writing + new code. It furthermore provides some utility functions for easier + integration of standard Emacs features when programming in Ada. + + Its general features include: + + @itemize @bullet + @item + An Integrated Development Environment with functionality such as the + following + + @itemize @bullet + @item + ``Project files'' for configuration-specific aspects + (e.g. directories and compilation options) + + @item + Compiling and stepping through error messages. + + @item + Running and debugging an applications within Glide. + @end itemize + + @item + Pull-down menus + + @item + User configurability + @end itemize + + Some of the specific Ada mode features are: + + @itemize @bullet + @item + Functions for easy and quick stepping through Ada code + + @item + Getting cross reference information for identifiers (e.g., finding a + defining occurrence) + + @item + Displaying an index menu of types and subprograms, allowing + direct selection for browsing + + @item + Automatic color highlighting of the various Ada entities + @end itemize + + Glide directly supports writing Ada code, via several facilities: + + @itemize @bullet + @item + Switching between spec and body files with possible + autogeneration of body files + + @item + Automatic formating of subprogram parameter lists + + @item + Automatic indentation according to Ada syntax + + @item + Automatic completion of identifiers + + @item + Automatic (and configurable) casing of identifiers, keywords, and attributes + + @item + Insertion of syntactic templates + + @item + Block commenting / uncommenting + @end itemize + + @noindent + For more information, please refer to the online documentation + available in the @code{Glide} @result{} @code{Help} menu. + @end ifclear + + + @node Converting Ada Files to html with gnathtml + @section Converting Ada Files to HTML with @code{gnathtml} + + @noindent + This @code{Perl} script allows Ada source files to be browsed using + standard Web browsers. For installation procedure, see the section + @xref{Installing gnathtml}. + + Ada reserved keywords are highlighted in a bold font and Ada comments in + a blue font. Unless your program was compiled with the gcc @option{-gnatx} + switch to suppress the generation of cross-referencing information, user + defined variables and types will appear in a different color; you will + be able to click on any identifier and go to its declaration. + + The command line is as follow: + @smallexample + $ perl gnathtml.pl [switches] ada-files + @end smallexample + + @noindent + You can pass it as many Ada files as you want. @code{gnathtml} will generate + an html file for every ada file, and a global file called @file{index.htm}. + This file is an index of every identifier defined in the files. + + The available switches are the following ones : + + @table @option + @item -83 + @cindex @option{-83} (@code{gnathtml}) + Only the subset on the Ada 83 keywords will be highlighted, not the full + Ada 95 keywords set. + + @item -cc @var{color} + @cindex @option{-cc} (@code{gnathtml}) + This option allows you to change the color used for comments. The default + value is green. The color argument can be any name accepted by html. + + @item -d + @cindex @option{-d} (@code{gnathtml}) + If the ada files depend on some other files (using for instance the + @code{with} command, the latter will also be converted to html. + Only the files in the user project will be converted to html, not the files + in the run-time library itself. + + @item -D + @cindex @option{-D} (@code{gnathtml}) + This command is the same as @option{-d} above, but @command{gnathtml} will + also look for files in the run-time library, and generate html files for them. + + @item -ext @var{extension} + @cindex @option{-ext} (@code{gnathtml}) + This option allows you to change the extension of the generated HTML files. + If you do not specify an extension, it will default to @file{htm}. + + @item -f + @cindex @option{-f} (@code{gnathtml}) + By default, gnathtml will generate html links only for global entities + ('with'ed units, global variables and types,...). If you specify the + @option{-f} on the command line, then links will be generated for local + entities too. + + @item -l @var{number} + @cindex @option{-l} (@code{gnathtml}) + If this switch is provided and @var{number} is not 0, then @code{gnathtml} + will number the html files every @var{number} line. + + @item -I @var{dir} + @cindex @option{-I} (@code{gnathtml}) + Specify a directory to search for library files (@file{.ALI} files) and + source files. You can provide several -I switches on the command line, + and the directories will be parsed in the order of the command line. + + @item -o @var{dir} + @cindex @option{-o} (@code{gnathtml}) + Specify the output directory for html files. By default, gnathtml will + saved the generated html files in a subdirectory named @file{html/}. + + @item -p @var{file} + @cindex @option{-p} (@code{gnathtml}) + If you are using Emacs and the most recent Emacs Ada mode, which provides + a full Integrated Development Environment for compiling, checking, + running and debugging applications, you may use @file{.gpr} files + to give the directories where Emacs can find sources and object files. + + Using this switch, you can tell gnathtml to use these files. This allows + you to get an html version of your application, even if it is spread + over multiple directories. + + @item -sc @var{color} + @cindex @option{-sc} (@code{gnathtml}) + This option allows you to change the color used for symbol definitions. + The default value is red. The color argument can be any name accepted by html. + + @item -t @var{file} + @cindex @option{-t} (@code{gnathtml}) + This switch provides the name of a file. This file contains a list of + file names to be converted, and the effect is exactly as though they had + appeared explicitly on the command line. This + is the recommended way to work around the command line length limit on some + systems. + + @end table + + @node Installing gnathtml + @section Installing @code{gnathtml} + + @noindent + @code{Perl} needs to be installed on your machine to run this script. + @code{Perl} is freely available for almost every architecture and + Operating System via the Internet. + + On Unix systems, you may want to modify the first line of the script + @code{gnathtml}, to explicitly tell the Operating system where Perl + is. The syntax of this line is : + @smallexample + #!full_path_name_to_perl + @end smallexample + + @noindent + Alternatively, you may run the script using the following command line: + + @smallexample + $ perl gnathtml.pl [switches] files + @end smallexample + + @ifset vms + @node LSE + @section LSE + @findex LSE + + @noindent + The GNAT distribution provides an Ada 95 template for the Digital Language + Sensitive Editor (LSE), a component of DECset. In order to + access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV. + + @node Profiling + @section Profiling + @findex PCA + + @noindent + GNAT supports The Digital Performance Coverage Analyzer (PCA), a component + of DECset. To use it proceed as outlined under ``HELP PCA'', except for running + the collection phase with the /DEBUG qualifier. + + @smallexample + $ GNAT MAKE /DEBUG + $ DEFINE LIB$DEBUG PCA$COLLECTOR + $ RUN/DEBUG + @end smallexample + @noindent + @end ifset + + @node Running and Debugging Ada Programs + @chapter Running and Debugging Ada Programs + @cindex Debugging + + @noindent + This chapter discusses how to debug Ada programs. An incorrect Ada program + may be handled in three ways by the GNAT compiler: + + @enumerate + @item + The illegality may be a violation of the static semantics of Ada. In + that case GNAT diagnoses the constructs in the program that are illegal. + It is then a straightforward matter for the user to modify those parts of + the program. + + @item + The illegality may be a violation of the dynamic semantics of Ada. In + that case the program compiles and executes, but may generate incorrect + results, or may terminate abnormally with some exception. + + @item + When presented with a program that contains convoluted errors, GNAT + itself may terminate abnormally without providing full diagnostics on + the incorrect user program. + @end enumerate + + @menu + * The GNAT Debugger GDB:: + * Running GDB:: + * Introduction to GDB Commands:: + * Using Ada Expressions:: + * Calling User-Defined Subprograms:: + * Using the Next Command in a Function:: + * Ada Exceptions:: + * Ada Tasks:: + * Debugging Generic Units:: + * GNAT Abnormal Termination or Failure to Terminate:: + * Naming Conventions for GNAT Source Files:: + * Getting Internal Debugging Information:: + * Stack Traceback:: + @end menu + + @cindex Debugger + @findex gdb + + @node The GNAT Debugger GDB + @section The GNAT Debugger GDB + + @noindent + @code{GDB} is a general purpose, platform-independent debugger that + can be used to debug mixed-language programs compiled with @code{GCC}, + and in particular is capable of debugging Ada programs compiled with + GNAT. The latest versions of @code{GDB} are Ada-aware and can handle + complex Ada data structures. + + The manual @cite{Debugging with GDB} + @ifset vms + , located in the GNU:[DOCS] directory, + @end ifset + contains full details on the usage of @code{GDB}, including a section on + its usage on programs. This manual should be consulted for full + details. The section that follows is a brief introduction to the + philosophy and use of @code{GDB}. + + When GNAT programs are compiled, the compiler optionally writes debugging + information into the generated object file, including information on + line numbers, and on declared types and variables. This information is + separate from the generated code. It makes the object files considerably + larger, but it does not add to the size of the actual executable that + will be loaded into memory, and has no impact on run-time performance. The + generation of debug information is triggered by the use of the + ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out + the compilations. It is important to emphasize that the use of these + options does not change the generated code. + + The debugging information is written in standard system formats that + are used by many tools, including debuggers and profilers. The format + of the information is typically designed to describe C types and + semantics, but GNAT implements a translation scheme which allows full + details about Ada types and variables to be encoded into these + standard C formats. Details of this encoding scheme may be found in + the file exp_dbug.ads in the GNAT source distribution. However, the + details of this encoding are, in general, of no interest to a user, + since @code{GDB} automatically performs the necessary decoding. + + When a program is bound and linked, the debugging information is + collected from the object files, and stored in the executable image of + the program. Again, this process significantly increases the size of + the generated executable file, but it does not increase the size of + the executable program itself. Furthermore, if this program is run in + the normal manner, it runs exactly as if the debug information were + not present, and takes no more actual memory. + + However, if the program is run under control of @code{GDB}, the + debugger is activated. The image of the program is loaded, at which + point it is ready to run. If a run command is given, then the program + will run exactly as it would have if @code{GDB} were not present. This + is a crucial part of the @code{GDB} design philosophy. @code{GDB} is + entirely non-intrusive until a breakpoint is encountered. If no + breakpoint is ever hit, the program will run exactly as it would if no + debugger were present. When a breakpoint is hit, @code{GDB} accesses + the debugging information and can respond to user commands to inspect + variables, and more generally to report on the state of execution. + + @c ************** + @node Running GDB + @section Running GDB + + @noindent + The debugger can be launched directly and simply from @code{glide} or + through its graphical interface: @code{gvd}. It can also be used + directly in text mode. Here is described the basic use of @code{GDB} + in text mode. All the commands described below can be used in the + @code{gvd} console window even though there is usually other more + graphical ways to achieve the same goals. + + @ifclear vms + @noindent + The command to run the graphical interface of the debugger is + @smallexample + $ gvd program + @end smallexample + @end ifclear + + @noindent + The command to run @code{GDB} in text mode is + + @smallexample + $ ^gdb program^$ GDB PROGRAM^ + @end smallexample + + @noindent + where @code{^program^PROGRAM^} is the name of the executable file. This + activates the debugger and results in a prompt for debugger commands. + The simplest command is simply @code{run}, which causes the program to run + exactly as if the debugger were not present. The following section + describes some of the additional commands that can be given to @code{GDB}. + + + @c ******************************* + @node Introduction to GDB Commands + @section Introduction to GDB Commands + + @noindent + @code{GDB} contains a large repertoire of commands. The manual + @cite{Debugging with GDB} + @ifset vms + , located in the GNU:[DOCS] directory, + @end ifset + includes extensive documentation on the use + of these commands, together with examples of their use. Furthermore, + the command @var{help} invoked from within @code{GDB} activates a simple help + facility which summarizes the available commands and their options. + In this section we summarize a few of the most commonly + used commands to give an idea of what @code{GDB} is about. You should create + a simple program with debugging information and experiment with the use of + these @code{GDB} commands on the program as you read through the + following section. + + @table @code + @item set args @var{arguments} + The @var{arguments} list above is a list of arguments to be passed to + the program on a subsequent run command, just as though the arguments + had been entered on a normal invocation of the program. The @code{set args} + command is not needed if the program does not require arguments. + + @item run + The @code{run} command causes execution of the program to start from + the beginning. If the program is already running, that is to say if + you are currently positioned at a breakpoint, then a prompt will ask + for confirmation that you want to abandon the current execution and + restart. + + @item breakpoint @var{location} + The breakpoint command sets a breakpoint, that is to say a point at which + execution will halt and @code{GDB} will await further + commands. @var{location} is + either a line number within a file, given in the format @code{file:linenumber}, + or it is the name of a subprogram. If you request that a breakpoint be set on + a subprogram that is overloaded, a prompt will ask you to specify on which of + those subprograms you want to breakpoint. You can also + specify that all of them should be breakpointed. If the program is run + and execution encounters the breakpoint, then the program + stops and @code{GDB} signals that the breakpoint was encountered by + printing the line of code before which the program is halted. + + @item breakpoint exception @var{name} + A special form of the breakpoint command which breakpoints whenever + exception @var{name} is raised. + If @var{name} is omitted, + then a breakpoint will occur when any exception is raised. + + @item print @var{expression} + This will print the value of the given expression. Most simple + Ada expression formats are properly handled by @code{GDB}, so the expression + can contain function calls, variables, operators, and attribute references. + + @item continue + Continues execution following a breakpoint, until the next breakpoint or the + termination of the program. + + @item step + Executes a single line after a breakpoint. If the next statement + is a subprogram call, execution continues into (the first statement of) + the called subprogram. + + @item next + Executes a single line. If this line is a subprogram call, executes and + returns from the call. + + @item list + Lists a few lines around the current source location. In practice, it + is usually more convenient to have a separate edit window open with the + relevant source file displayed. Successive applications of this command + print subsequent lines. The command can be given an argument which is a + line number, in which case it displays a few lines around the specified one. + + @item backtrace + Displays a backtrace of the call chain. This command is typically + used after a breakpoint has occurred, to examine the sequence of calls that + leads to the current breakpoint. The display includes one line for each + activation record (frame) corresponding to an active subprogram. + + @item up + At a breakpoint, @code{GDB} can display the values of variables local + to the current frame. The command @code{up} can be used to + examine the contents of other active frames, by moving the focus up + the stack, that is to say from callee to caller, one frame at a time. + + @item down + Moves the focus of @code{GDB} down from the frame currently being + examined to the frame of its callee (the reverse of the previous command), + + @item frame @var{n} + Inspect the frame with the given number. The value 0 denotes the frame + of the current breakpoint, that is to say the top of the call stack. + + @end table + + The above list is a very short introduction to the commands that + @code{GDB} provides. Important additional capabilities, including conditional + breakpoints, the ability to execute command sequences on a breakpoint, + the ability to debug at the machine instruction level and many other + features are described in detail in @cite{Debugging with GDB}. + Note that most commands can be abbreviated + (for example, c for continue, bt for backtrace). + + @node Using Ada Expressions + @section Using Ada Expressions + @cindex Ada expressions + + @noindent + @code{GDB} supports a fairly large subset of Ada expression syntax, with some + extensions. The philosophy behind the design of this subset is + + @itemize @bullet + @item + That @code{GDB} should provide basic literals and access to operations for + arithmetic, dereferencing, field selection, indexing, and subprogram calls, + leaving more sophisticated computations to subprograms written into the + program (which therefore may be called from @code{GDB}). + + @item + That type safety and strict adherence to Ada language restrictions + are not particularly important to the @code{GDB} user. + + @item + That brevity is important to the @code{GDB} user. + @end itemize + + Thus, for brevity, the debugger acts as if there were + implicit @code{with} and @code{use} clauses in effect for all user-written + packages, thus making it unnecessary to fully qualify most names with + their packages, regardless of context. Where this causes ambiguity, + @code{GDB} asks the user's intent. + + For details on the supported Ada syntax, see @cite{Debugging with GDB}. + + @node Calling User-Defined Subprograms + @section Calling User-Defined Subprograms + + @noindent + An important capability of @code{GDB} is the ability to call user-defined + subprograms while debugging. This is achieved simply by entering + a subprogram call statement in the form: + + @smallexample + call subprogram-name (parameters) + @end smallexample + + @noindent + The keyword @code{call} can be omitted in the normal case where the + @code{subprogram-name} does not coincide with any of the predefined + @code{GDB} commands. + + The effect is to invoke the given subprogram, passing it the + list of parameters that is supplied. The parameters can be expressions and + can include variables from the program being debugged. The + subprogram must be defined + at the library level within your program, and @code{GDB} will call the + subprogram within the environment of your program execution (which + means that the subprogram is free to access or even modify variables + within your program). + + The most important use of this facility is in allowing the inclusion of + debugging routines that are tailored to particular data structures + in your program. Such debugging routines can be written to provide a suitably + high-level description of an abstract type, rather than a low-level dump + of its physical layout. After all, the standard + @code{GDB print} command only knows the physical layout of your + types, not their abstract meaning. Debugging routines can provide information + at the desired semantic level and are thus enormously useful. + + For example, when debugging GNAT itself, it is crucial to have access to + the contents of the tree nodes used to represent the program internally. + But tree nodes are represented simply by an integer value (which in turn + is an index into a table of nodes). + Using the @code{print} command on a tree node would simply print this integer + value, which is not very useful. But the PN routine (defined in file + treepr.adb in the GNAT sources) takes a tree node as input, and displays + a useful high level representation of the tree node, which includes the + syntactic category of the node, its position in the source, the integers + that denote descendant nodes and parent node, as well as varied + semantic information. To study this example in more detail, you might want to + look at the body of the PN procedure in the stated file. + + @node Using the Next Command in a Function + @section Using the Next Command in a Function + + @noindent + When you use the @code{next} command in a function, the current source + location will advance to the next statement as usual. A special case + arises in the case of a @code{return} statement. + + Part of the code for a return statement is the ``epilog'' of the function. + This is the code that returns to the caller. There is only one copy of + this epilog code, and it is typically associated with the last return + statement in the function if there is more than one return. In some + implementations, this epilog is associated with the first statement + of the function. + + The result is that if you use the @code{next} command from a return + statement that is not the last return statement of the function you + may see a strange apparent jump to the last return statement or to + the start of the function. You should simply ignore this odd jump. + The value returned is always that from the first return statement + that was stepped through. + + @node Ada Exceptions + @section Breaking on Ada Exceptions + @cindex Exceptions + + @noindent + You can set breakpoints that trip when your program raises + selected exceptions. + + @table @code + @item break exception + Set a breakpoint that trips whenever (any task in the) program raises + any exception. + + @item break exception @var{name} + Set a breakpoint that trips whenever (any task in the) program raises + the exception @var{name}. + + @item break exception unhandled + Set a breakpoint that trips whenever (any task in the) program raises an + exception for which there is no handler. + + @item info exceptions + @itemx info exceptions @var{regexp} + The @code{info exceptions} command permits the user to examine all defined + exceptions within Ada programs. With a regular expression, @var{regexp}, as + argument, prints out only those exceptions whose name matches @var{regexp}. + @end table + + @node Ada Tasks + @section Ada Tasks + @cindex Tasks + + @noindent + @code{GDB} allows the following task-related commands: + + @table @code + @item info tasks + This command shows a list of current Ada tasks, as in the following example: + + @smallexample + @iftex + @leftskip=0cm + @end iftex + (gdb) info tasks + ID TID P-ID Thread Pri State Name + 1 8088000 0 807e000 15 Child Activation Wait main_task + 2 80a4000 1 80ae000 15 Accept/Select Wait b + 3 809a800 1 80a4800 15 Child Activation Wait a + * 4 80ae800 3 80b8000 15 Running c + @end smallexample + + @noindent + In this listing, the asterisk before the first task indicates it to be the + currently running task. The first column lists the task ID that is used + to refer to tasks in the following commands. + + @item break @var{linespec} task @var{taskid} + @itemx break @var{linespec} task @var{taskid} if @dots{} + @cindex Breakpoints and tasks + These commands are like the @code{break @dots{} thread @dots{}}. + @var{linespec} specifies source lines. + + Use the qualifier @samp{task @var{taskid}} with a breakpoint command + to specify that you only want @code{GDB} to stop the program when a + particular Ada task reaches this breakpoint. @var{taskid} is one of the + numeric task identifiers assigned by @code{GDB}, shown in the first + column of the @samp{info tasks} display. + + If you do not specify @samp{task @var{taskid}} when you set a + breakpoint, the breakpoint applies to @emph{all} tasks of your + program. + + You can use the @code{task} qualifier on conditional breakpoints as + well; in this case, place @samp{task @var{taskid}} before the + breakpoint condition (before the @code{if}). + + @item task @var{taskno} + @cindex Task switching + + This command allows to switch to the task referred by @var{taskno}. In + particular, This allows to browse the backtrace of the specified + task. It is advised to switch back to the original task before + continuing execution otherwise the scheduling of the program may be + perturbated. + @end table + + @noindent + For more detailed information on the tasking support, + see @cite{Debugging with GDB}. + + @node Debugging Generic Units + @section Debugging Generic Units + @cindex Debugging Generic Units + @cindex Generics + + @noindent + GNAT always uses code expansion for generic instantiation. This means that + each time an instantiation occurs, a complete copy of the original code is + made, with appropriate substitutions of formals by actuals. + + It is not possible to refer to the original generic entities in + @code{GDB}, but it is always possible to debug a particular instance of + a generic, by using the appropriate expanded names. For example, if we have + + @smallexample @c ada + @group + @cartouche + procedure g is + + generic package k is + procedure kp (v1 : in out integer); + end k; + + package body k is + procedure kp (v1 : in out integer) is + begin + v1 := v1 + 1; + end kp; + end k; + + package k1 is new k; + package k2 is new k; + + var : integer := 1; + + begin + k1.kp (var); + k2.kp (var); + k1.kp (var); + k2.kp (var); + end; + @end cartouche + @end group + @end smallexample + + @noindent + Then to break on a call to procedure kp in the k2 instance, simply + use the command: + + @smallexample + (gdb) break g.k2.kp + @end smallexample + + @noindent + When the breakpoint occurs, you can step through the code of the + instance in the normal manner and examine the values of local variables, as for + other units. + + @node GNAT Abnormal Termination or Failure to Terminate + @section GNAT Abnormal Termination or Failure to Terminate + @cindex GNAT Abnormal Termination or Failure to Terminate + + @noindent + When presented with programs that contain serious errors in syntax + or semantics, + GNAT may on rare occasions experience problems in operation, such + as aborting with a + segmentation fault or illegal memory access, raising an internal + exception, terminating abnormally, or failing to terminate at all. + In such cases, you can activate + various features of GNAT that can help you pinpoint the construct in your + program that is the likely source of the problem. + + The following strategies are presented in increasing order of + difficulty, corresponding to your experience in using GNAT and your + familiarity with compiler internals. + + @enumerate + @item + Run @code{gcc} with the @option{-gnatf}. This first + switch causes all errors on a given line to be reported. In its absence, + only the first error on a line is displayed. + + The @option{-gnatdO} switch causes errors to be displayed as soon as they + are encountered, rather than after compilation is terminated. If GNAT + terminates prematurely or goes into an infinite loop, the last error + message displayed may help to pinpoint the culprit. + + @item + Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode, + @code{gcc} produces ongoing information about the progress of the + compilation and provides the name of each procedure as code is + generated. This switch allows you to find which Ada procedure was being + compiled when it encountered a code generation problem. + + @item + @cindex @option{-gnatdc} switch + Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific + switch that does for the front-end what @option{^-v^VERBOSE^} does + for the back end. The system prints the name of each unit, + either a compilation unit or nested unit, as it is being analyzed. + @item + Finally, you can start + @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the + front-end of GNAT, and can be run independently (normally it is just + called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you + would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The + @code{where} command is the first line of attack; the variable + @code{lineno} (seen by @code{print lineno}), used by the second phase of + @code{gnat1} and by the @code{gcc} backend, indicates the source line at + which the execution stopped, and @code{input_file name} indicates the name of + the source file. + @end enumerate + + @node Naming Conventions for GNAT Source Files + @section Naming Conventions for GNAT Source Files + + @noindent + In order to examine the workings of the GNAT system, the following + brief description of its organization may be helpful: + + @itemize @bullet + @item + Files with prefix @file{^sc^SC^} contain the lexical scanner. + + @item + All files prefixed with @file{^par^PAR^} are components of the parser. The + numbers correspond to chapters of the Ada 95 Reference Manual. For example, + parsing of select statements can be found in @file{par-ch9.adb}. + + @item + All files prefixed with @file{^sem^SEM^} perform semantic analysis. The + numbers correspond to chapters of the Ada standard. For example, all + issues involving context clauses can be found in @file{sem_ch10.adb}. In + addition, some features of the language require sufficient special processing + to justify their own semantic files: sem_aggr for aggregates, sem_disp for + dynamic dispatching, etc. + + @item + All files prefixed with @file{^exp^EXP^} perform normalization and + expansion of the intermediate representation (abstract syntax tree, or AST). + these files use the same numbering scheme as the parser and semantics files. + For example, the construction of record initialization procedures is done in + @file{exp_ch3.adb}. + + @item + The files prefixed with @file{^bind^BIND^} implement the binder, which + verifies the consistency of the compilation, determines an order of + elaboration, and generates the bind file. + + @item + The files @file{atree.ads} and @file{atree.adb} detail the low-level + data structures used by the front-end. + + @item + The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of + the abstract syntax tree as produced by the parser. + + @item + The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of + all entities, computed during semantic analysis. + + @item + Library management issues are dealt with in files with prefix + @file{^lib^LIB^}. + + @item + @findex Ada + @cindex Annex A + Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as + defined in Annex A. + + @item + @findex Interfaces + @cindex Annex B + Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as + defined in Annex B. + + @item + @findex System + Files with prefix @file{^s-^S-^} are children of @code{System}. This includes + both language-defined children and GNAT run-time routines. + + @item + @findex GNAT + Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful + general-purpose packages, fully documented in their specifications. All + the other @file{.c} files are modifications of common @code{gcc} files. + @end itemize + + @node Getting Internal Debugging Information + @section Getting Internal Debugging Information + + @noindent + Most compilers have internal debugging switches and modes. GNAT + does also, except GNAT internal debugging switches and modes are not + secret. A summary and full description of all the compiler and binder + debug flags are in the file @file{debug.adb}. You must obtain the + sources of the compiler to see the full detailed effects of these flags. + + The switches that print the source of the program (reconstructed from + the internal tree) are of general interest for user programs, as are the + options to print + the full internal tree, and the entity table (the symbol table + information). The reconstructed source provides a readable version of the + program after the front-end has completed analysis and expansion, + and is useful when studying the performance of specific constructs. + For example, constraint checks are indicated, complex aggregates + are replaced with loops and assignments, and tasking primitives + are replaced with run-time calls. + + @node Stack Traceback + @section Stack Traceback + @cindex traceback + @cindex stack traceback + @cindex stack unwinding + + @noindent + Traceback is a mechanism to display the sequence of subprogram calls that + leads to a specified execution point in a program. Often (but not always) + the execution point is an instruction at which an exception has been raised. + This mechanism is also known as @i{stack unwinding} because it obtains + its information by scanning the run-time stack and recovering the activation + records of all active subprograms. Stack unwinding is one of the most + important tools for program debugging. + + @noindent + The first entry stored in traceback corresponds to the deepest calling level, + that is to say the subprogram currently executing the instruction + from which we want to obtain the traceback. + + @noindent + Note that there is no runtime performance penalty when stack traceback + is enabled and no exception are raised during program execution. + + @menu + * Non-Symbolic Traceback:: + * Symbolic Traceback:: + @end menu + + @node Non-Symbolic Traceback + @subsection Non-Symbolic Traceback + @cindex traceback, non-symbolic + + @noindent + Note: this feature is not supported on all platforms. See + @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported + platforms. + + @menu + * Tracebacks From an Unhandled Exception:: + * Tracebacks From Exception Occurrences (non-symbolic):: + * Tracebacks From Anywhere in a Program (non-symbolic):: + @end menu + + @node Tracebacks From an Unhandled Exception + @subsubsection Tracebacks From an Unhandled Exception + + @noindent + A runtime non-symbolic traceback is a list of addresses of call instructions. + To enable this feature you must use the @option{-E} + @code{gnatbind}'s option. With this option a stack traceback is stored as part + of exception information. It is possible to retrieve this information using the + standard @code{Ada.Exception.Exception_Information} routine. + + @noindent + Let's have a look at a simple example: + + @smallexample @c ada + @cartouche + procedure STB is + + procedure P1 is + begin + raise Constraint_Error; + end P1; + + procedure P2 is + begin + P1; + end P2; + + begin + P2; + end STB; + @end cartouche + @end smallexample + + @smallexample + $ gnatmake stb -bargs -E + $ stb + + Execution terminated by unhandled exception + Exception name: CONSTRAINT_ERROR + Message: stb.adb:5 + Call stack traceback locations: + 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 + @end smallexample + + @noindent + As we see the traceback lists a sequence of addresses for the unhandled + exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to + guess that this exception come from procedure P1. To translate these + addresses into the source lines where the calls appear, the + @code{addr2line} tool, described below, is invaluable. The use of this tool + requires the program to be compiled with debug information. + + @smallexample + $ gnatmake -g stb -bargs -E + $ stb + + Execution terminated by unhandled exception + Exception name: CONSTRAINT_ERROR + Message: stb.adb:5 + Call stack traceback locations: + 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 + + $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 + 0x4011f1 0x77e892a4 + + 00401373 at d:/stb/stb.adb:5 + 0040138B at d:/stb/stb.adb:10 + 0040139C at d:/stb/stb.adb:14 + 00401335 at d:/stb/b~stb.adb:104 + 004011C4 at /build/.../crt1.c:200 + 004011F1 at /build/.../crt1.c:222 + 77E892A4 in ?? at ??:0 + @end smallexample + + @noindent + @code{addr2line} has a number of other useful options: + + @table @code + @item --functions + to get the function name corresponding to any location + + @item --demangle=gnat + to use the @b{gnat} decoding mode for the function names. Note that + for binutils version 2.9.x the option is simply @option{--demangle}. + @end table + + @smallexample + $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b + 0x40139c 0x401335 0x4011c4 0x4011f1 + + 00401373 in stb.p1 at d:/stb/stb.adb:5 + 0040138B in stb.p2 at d:/stb/stb.adb:10 + 0040139C in stb at d:/stb/stb.adb:14 + 00401335 in main at d:/stb/b~stb.adb:104 + 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200 + 004011F1 in at /build/.../crt1.c:222 + @end smallexample + + @noindent + From this traceback we can see that the exception was raised in + @file{stb.adb} at line 5, which was reached from a procedure call in + @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file, + which contains the call to the main program. + @pxref{Running gnatbind}. The remaining entries are assorted runtime routines, + and the output will vary from platform to platform. + + @noindent + It is also possible to use @code{GDB} with these traceback addresses to debug + the program. For example, we can break at a given code location, as reported + in the stack traceback: + + @smallexample + $ gdb -nw stb + @ifclear vms + @noindent + Furthermore, this feature is not implemented inside Windows DLL. Only + the non-symbolic traceback is reported in this case. + @end ifclear + + (gdb) break *0x401373 + Breakpoint 1 at 0x401373: file stb.adb, line 5. + @end smallexample + + @noindent + It is important to note that the stack traceback addresses + do not change when debug information is included. This is particularly useful + because it makes it possible to release software without debug information (to + minimize object size), get a field report that includes a stack traceback + whenever an internal bug occurs, and then be able to retrieve the sequence + of calls with the same program compiled with debug information. + + @node Tracebacks From Exception Occurrences (non-symbolic) + @subsubsection Tracebacks From Exception Occurrences + + @noindent + Non-symbolic tracebacks are obtained by using the @option{-E} binder argument. + The stack traceback is attached to the exception information string, and can + be retrieved in an exception handler within the Ada program, by means of the + Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example: + + @smallexample @c ada + with Ada.Text_IO; + with Ada.Exceptions; + + procedure STB is + + use Ada; + use Ada.Exceptions; + + procedure P1 is + K : Positive := 1; + begin + K := K - 1; + exception + when E : others => + Text_IO.Put_Line (Exception_Information (E)); + end P1; + + procedure P2 is + begin + P1; + end P2; + + begin + P2; + end STB; + @end smallexample + + @noindent + This program will output: + + @smallexample + $ stb + + Exception name: CONSTRAINT_ERROR + Message: stb.adb:12 + Call stack traceback locations: + 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 + @end smallexample + + @node Tracebacks From Anywhere in a Program (non-symbolic) + @subsubsection Tracebacks From Anywhere in a Program + + @noindent + It is also possible to retrieve a stack traceback from anywhere in a + program. For this you need to + use the @code{GNAT.Traceback} API. This package includes a procedure called + @code{Call_Chain} that computes a complete stack traceback, as well as useful + display procedures described below. It is not necessary to use the + @option{-E gnatbind} option in this case, because the stack traceback mechanism + is invoked explicitly. + + @noindent + In the following example we compute a traceback at a specific location in + the program, and we display it using @code{GNAT.Debug_Utilities.Image} to + convert addresses to strings: + + @smallexample @c ada + with Ada.Text_IO; + with GNAT.Traceback; + with GNAT.Debug_Utilities; + + procedure STB is + + use Ada; + use GNAT; + use GNAT.Traceback; + + procedure P1 is + TB : Tracebacks_Array (1 .. 10); + -- We are asking for a maximum of 10 stack frames. + Len : Natural; + -- Len will receive the actual number of stack frames returned. + begin + Call_Chain (TB, Len); + + Text_IO.Put ("In STB.P1 : "); + + for K in 1 .. Len loop + Text_IO.Put (Debug_Utilities.Image (TB (K))); + Text_IO.Put (' '); + end loop; + + Text_IO.New_Line; + end P1; + + procedure P2 is + begin + P1; + end P2; + + begin + P2; + end STB; + @end smallexample + + @smallexample + $ gnatmake stb + $ stb + + In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# + 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# + @end smallexample + + @node Symbolic Traceback + @subsection Symbolic Traceback + @cindex traceback, symbolic + + @noindent + A symbolic traceback is a stack traceback in which procedure names are + associated with each code location. + + @noindent + Note that this feature is not supported on all platforms. See + @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete + list of currently supported platforms. + + @noindent + Note that the symbolic traceback requires that the program be compiled + with debug information. If it is not compiled with debug information + only the non-symbolic information will be valid. + + @menu + * Tracebacks From Exception Occurrences (symbolic):: + * Tracebacks From Anywhere in a Program (symbolic):: + @end menu + + @node Tracebacks From Exception Occurrences (symbolic) + @subsubsection Tracebacks From Exception Occurrences + + @smallexample @c ada + with Ada.Text_IO; + with GNAT.Traceback.Symbolic; + + procedure STB is + + procedure P1 is + begin + raise Constraint_Error; + end P1; + + procedure P2 is + begin + P1; + end P2; + + procedure P3 is + begin + P2; + end P3; + + begin + P3; + exception + when E : others => + Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); + end STB; + @end smallexample + + @smallexample + $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl + $ stb + + 0040149F in stb.p1 at stb.adb:8 + 004014B7 in stb.p2 at stb.adb:13 + 004014CF in stb.p3 at stb.adb:18 + 004015DD in ada.stb at stb.adb:22 + 00401461 in main at b~stb.adb:168 + 004011C4 in __mingw_CRTStartup at crt1.c:200 + 004011F1 in mainCRTStartup at crt1.c:222 + 77E892A4 in ?? at ??:0 + @end smallexample + + @noindent + The exact sequence of linker options may vary from platform to platform. + The above @option{-largs} section is for Windows platforms. By contrast, + under Unix there is no need for the @option{-largs} section. + Differences across platforms are due to details of linker implementation. + + @node Tracebacks From Anywhere in a Program (symbolic) + @subsubsection Tracebacks From Anywhere in a Program + + @noindent + It is possible to get a symbolic stack traceback + from anywhere in a program, just as for non-symbolic tracebacks. + The first step is to obtain a non-symbolic + traceback, and then call @code{Symbolic_Traceback} to compute the symbolic + information. Here is an example: + + @smallexample @c ada + with Ada.Text_IO; + with GNAT.Traceback; + with GNAT.Traceback.Symbolic; + + procedure STB is + + use Ada; + use GNAT.Traceback; + use GNAT.Traceback.Symbolic; + + procedure P1 is + TB : Tracebacks_Array (1 .. 10); + -- We are asking for a maximum of 10 stack frames. + Len : Natural; + -- Len will receive the actual number of stack frames returned. + begin + Call_Chain (TB, Len); + Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); + end P1; + + procedure P2 is + begin + P1; + end P2; + + begin + P2; + end STB; + @end smallexample + + @ifset vms + @node Compatibility with DEC Ada + @chapter Compatibility with DEC Ada + @cindex Compatibility + + @noindent + This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT + OpenVMS Alpha. GNAT achieves a high level of compatibility + with DEC Ada, and it should generally be straightforward to port code + from the DEC Ada environment to GNAT. However, there are a few language + and implementation differences of which the user must be aware. These + differences are discussed in this section. In + addition, the operating environment and command structure for the + compiler are different, and these differences are also discussed. + + Note that this discussion addresses specifically the implementation + of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation + of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, + GNAT always follows the Alpha implementation. + + @menu + * Ada 95 Compatibility:: + * Differences in the Definition of Package System:: + * Language-Related Features:: + * The Package STANDARD:: + * The Package SYSTEM:: + * Tasking and Task-Related Features:: + * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems:: + * Pragmas and Pragma-Related Features:: + * Library of Predefined Units:: + * Bindings:: + * Main Program Definition:: + * Implementation-Defined Attributes:: + * Compiler and Run-Time Interfacing:: + * Program Compilation and Library Management:: + * Input-Output:: + * Implementation Limits:: + * Tools:: + @end menu + + @node Ada 95 Compatibility + @section Ada 95 Compatibility + + @noindent + GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83 + compiler. Ada 95 is almost completely upwards compatible + with Ada 83, and therefore Ada 83 programs will compile + and run under GNAT with + no changes or only minor changes. The Ada 95 Reference + Manual (ANSI/ISO/IEC-8652:1995) provides details on specific + incompatibilities. + + GNAT provides the switch /83 on the GNAT COMPILE command, + as well as the pragma ADA_83, to force the compiler to + operate in Ada 83 mode. This mode does not guarantee complete + conformance to Ada 83, but in practice is sufficient to + eliminate most sources of incompatibilities. + In particular, it eliminates the recognition of the + additional Ada 95 keywords, so that their use as identifiers + in Ada83 program is legal, and handles the cases of packages + with optional bodies, and generics that instantiate unconstrained + types without the use of @code{(<>)}. + + @node Differences in the Definition of Package System + @section Differences in the Definition of Package System + + @noindent + Both the Ada 95 and Ada 83 reference manuals permit a compiler to add + implementation-dependent declarations to package System. In normal mode, + GNAT does not take advantage of this permission, and the version of System + provided by GNAT exactly matches that in the Ada 95 Reference Manual. + + However, DEC Ada adds an extensive set of declarations to package System, + as fully documented in the DEC Ada manuals. To minimize changes required + for programs that make use of these extensions, GNAT provides the pragma + Extend_System for extending the definition of package System. By using: + + @smallexample @c ada + @group + @cartouche + pragma Extend_System (Aux_DEC); + @end cartouche + @end group + @end smallexample + + @noindent + The set of definitions in System is extended to include those in package + @code{System.Aux_DEC}. + These definitions are incorporated directly into package + System, as though they had been declared there in the first place. For a + list of the declarations added, see the specification of this package, + which can be found in the file @code{s-auxdec.ads} in the GNAT library. + The pragma Extend_System is a configuration pragma, which means that + it can be placed in the file @file{gnat.adc}, so that it will automatically + apply to all subsequent compilations. See the section on Configuration + Pragmas for further details. + + An alternative approach that avoids the use of the non-standard + Extend_System pragma is to add a context clause to the unit that + references these facilities: + + @smallexample @c ada + @group + @cartouche + with System.Aux_DEC; + use System.Aux_DEC; + @end cartouche + @end group + @end smallexample + + @noindent + The effect is not quite semantically identical to incorporating + the declarations directly into package @code{System}, + but most programs will not notice a difference + unless they use prefix notation (e.g. @code{System.Integer_8}) + to reference the + entities directly in package @code{System}. + For units containing such references, + the prefixes must either be removed, or the pragma @code{Extend_System} + must be used. + + @node Language-Related Features + @section Language-Related Features + + @noindent + The following sections highlight differences in types, + representations of types, operations, alignment, and + related topics. + + @menu + * Integer Types and Representations:: + * Floating-Point Types and Representations:: + * Pragmas Float_Representation and Long_Float:: + * Fixed-Point Types and Representations:: + * Record and Array Component Alignment:: + * Address Clauses:: + * Other Representation Clauses:: + @end menu + + @node Integer Types and Representations + @subsection Integer Types and Representations + + @noindent + The set of predefined integer types is identical in DEC Ada and GNAT. + Furthermore the representation of these integer types is also identical, + including the capability of size clauses forcing biased representation. + + In addition, + DEC Ada for OpenVMS Alpha systems has defined the + following additional integer types in package System: + + @itemize @bullet + + @item + INTEGER_8 + + @item + INTEGER_16 + + @item + INTEGER_32 + + @item + INTEGER_64 + + @item + LARGEST_INTEGER + @end itemize + + @noindent + When using GNAT, the first four of these types may be obtained from the + standard Ada 95 package @code{Interfaces}. + Alternatively, by use of the pragma + @code{Extend_System}, identical + declarations can be referenced directly in package @code{System}. + On both GNAT and DEC Ada, the maximum integer size is 64 bits. + + @node Floating-Point Types and Representations + @subsection Floating-Point Types and Representations + @cindex Floating-Point types + + @noindent + The set of predefined floating-point types is identical in DEC Ada and GNAT. + Furthermore the representation of these floating-point + types is also identical. One important difference is that the default + representation for DEC Ada is VAX_Float, but the default representation + for GNAT is IEEE. + + Specific types may be declared to be VAX_Float or IEEE, using the pragma + @code{Float_Representation} as described in the DEC Ada documentation. + For example, the declarations: + + @smallexample @c ada + @group + @cartouche + type F_Float is digits 6; + pragma Float_Representation (VAX_Float, F_Float); + @end cartouche + @end group + @end smallexample + + @noindent + declare a type F_Float that will be represented in VAX_Float format. + This set of declarations actually appears in System.Aux_DEC, which provides + the full set of additional floating-point declarations provided in + the DEC Ada version of package + System. This and similar declarations may be accessed in a user program + by using pragma @code{Extend_System}. The use of this + pragma, and the related pragma @code{Long_Float} is described in further + detail in the following section. + + @node Pragmas Float_Representation and Long_Float + @subsection Pragmas Float_Representation and Long_Float + + @noindent + DEC Ada provides the pragma @code{Float_Representation}, which + acts as a program library switch to allow control over + the internal representation chosen for the predefined + floating-point types declared in the package @code{Standard}. + The format of this pragma is as follows: + + @smallexample + @group + @cartouche + @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float); + @end cartouche + @end group + @end smallexample + + @noindent + This pragma controls the representation of floating-point + types as follows: + + @itemize @bullet + @item + @code{VAX_Float} specifies that floating-point + types are represented by default with the VAX hardware types + F-floating, D-floating, G-floating. Note that the H-floating + type is available only on DIGITAL Vax systems, and is not available + in either DEC Ada or GNAT for Alpha systems. + + @item + @code{IEEE_Float} specifies that floating-point + types are represented by default with the IEEE single and + double floating-point types. + @end itemize + + @noindent + GNAT provides an identical implementation of the pragma + @code{Float_Representation}, except that it functions as a + configuration pragma, as defined by Ada 95. Note that the + notion of configuration pragma corresponds closely to the + DEC Ada notion of a program library switch. + + When no pragma is used in GNAT, the default is IEEE_Float, which is different + from DEC Ada 83, where the default is VAX_Float. In addition, the + predefined libraries in GNAT are built using IEEE_Float, so it is not + advisable to change the format of numbers passed to standard library + routines, and if necessary explicit type conversions may be needed. + + The use of IEEE_Float is recommended in GNAT since it is more efficient, + and (given that it conforms to an international standard) potentially more + portable. The situation in which VAX_Float may be useful is in interfacing + to existing code and data that expects the use of VAX_Float. There are + two possibilities here. If the requirement for the use of VAX_Float is + localized, then the best approach is to use the predefined VAX_Float + types in package @code{System}, as extended by + @code{Extend_System}. For example, use @code{System.F_Float} + to specify the 32-bit @code{F-Float} format. + + Alternatively, if an entire program depends heavily on the use of + the @code{VAX_Float} and in particular assumes that the types in + package @code{Standard} are in @code{Vax_Float} format, then it + may be desirable to reconfigure GNAT to assume Vax_Float by default. + This is done by using the GNAT LIBRARY command to rebuild the library, and + then using the general form of the @code{Float_Representation} + pragma to ensure that this default format is used throughout. + The form of the GNAT LIBRARY command is: + + @smallexample + GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory} + @end smallexample + + @noindent + where @i{file} contains the new configuration pragmas + and @i{directory} is the directory to be created to contain + the new library. + + @noindent + On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float} + to allow control over the internal representation chosen + for the predefined type @code{Long_Float} and for floating-point + type declarations with digits specified in the range 7 .. 15. + The format of this pragma is as follows: + + @smallexample @c ada + @cartouche + pragma Long_Float (D_FLOAT | G_FLOAT); + @end cartouche + @end smallexample + + @node Fixed-Point Types and Representations + @subsection Fixed-Point Types and Representations + + @noindent + On DEC Ada for OpenVMS Alpha systems, rounding is + away from zero for both positive and negative numbers. + Therefore, +0.5 rounds to 1 and -0.5 rounds to -1. + + On GNAT for OpenVMS Alpha, the results of operations + on fixed-point types are in accordance with the Ada 95 + rules. In particular, results of operations on decimal + fixed-point types are truncated. + + @node Record and Array Component Alignment + @subsection Record and Array Component Alignment + + @noindent + On DEC Ada for OpenVMS Alpha, all non composite components + are aligned on natural boundaries. For example, 1-byte + components are aligned on byte boundaries, 2-byte + components on 2-byte boundaries, 4-byte components on 4-byte + byte boundaries, and so on. The OpenVMS Alpha hardware + runs more efficiently with naturally aligned data. + + ON GNAT for OpenVMS Alpha, alignment rules are compatible + with DEC Ada for OpenVMS Alpha. + + @node Address Clauses + @subsection Address Clauses + + @noindent + In DEC Ada and GNAT, address clauses are supported for + objects and imported subprograms. + The predefined type @code{System.Address} is a private type + in both compilers, with the same representation (it is simply + a machine pointer). Addition, subtraction, and comparison + operations are available in the standard Ada 95 package + @code{System.Storage_Elements}, or in package @code{System} + if it is extended to include @code{System.Aux_DEC} using a + pragma @code{Extend_System} as previously described. + + Note that code that with's both this extended package @code{System} + and the package @code{System.Storage_Elements} should not @code{use} + both packages, or ambiguities will result. In general it is better + not to mix these two sets of facilities. The Ada 95 package was + designed specifically to provide the kind of features that DEC Ada + adds directly to package @code{System}. + + GNAT is compatible with DEC Ada in its handling of address + clauses, except for some limitations in + the form of address clauses for composite objects with + initialization. Such address clauses are easily replaced + by the use of an explicitly-defined constant as described + in the Ada 95 Reference Manual (13.1(22)). For example, the sequence + of declarations: + + @smallexample @c ada + @cartouche + X, Y : Integer := Init_Func; + Q : String (X .. Y) := "abc"; + ... + for Q'Address use Compute_Address; + @end cartouche + @end smallexample + + @noindent + will be rejected by GNAT, since the address cannot be computed at the time + that Q is declared. To achieve the intended effect, write instead: + + @smallexample @c ada + @group + @cartouche + X, Y : Integer := Init_Func; + Q_Address : constant Address := Compute_Address; + Q : String (X .. Y) := "abc"; + ... + for Q'Address use Q_Address; + @end cartouche + @end group + @end smallexample + + @noindent + which will be accepted by GNAT (and other Ada 95 compilers), and is also + backwards compatible with Ada 83. A fuller description of the restrictions + on address specifications is found in the GNAT Reference Manual. + + @node Other Representation Clauses + @subsection Other Representation Clauses + + @noindent + GNAT supports in a compatible manner all the representation + clauses supported by DEC Ada. In addition, it + supports representation clause forms that are new in Ada 95 + including COMPONENT_SIZE and SIZE clauses for objects. + + @node The Package STANDARD + @section The Package STANDARD + + @noindent + The package STANDARD, as implemented by DEC Ada, is fully + described in the Reference Manual for the Ada Programming + Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada + Language Reference Manual. As implemented by GNAT, the + package STANDARD is described in the Ada 95 Reference + Manual. + + In addition, DEC Ada supports the Latin-1 character set in + the type CHARACTER. GNAT supports the Latin-1 character set + in the type CHARACTER and also Unicode (ISO 10646 BMP) in + the type WIDE_CHARACTER. + + The floating-point types supported by GNAT are those + supported by DEC Ada, but defaults are different, and are controlled by + pragmas. See @pxref{Floating-Point Types and Representations} for details. + + @node The Package SYSTEM + @section The Package SYSTEM + + @noindent + DEC Ada provides a system-specific version of the package + SYSTEM for each platform on which the language ships. + For the complete specification of the package SYSTEM, see + Appendix F of the DEC Ada Language Reference Manual. + + On DEC Ada, the package SYSTEM includes the following conversion functions: + @itemize @bullet + @item TO_ADDRESS(INTEGER) + + @item TO_ADDRESS(UNSIGNED_LONGWORD) + + @item TO_ADDRESS(universal_integer) + + @item TO_INTEGER(ADDRESS) + + @item TO_UNSIGNED_LONGWORD(ADDRESS) + + @item Function IMPORT_VALUE return UNSIGNED_LONGWORD and the + functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE + @end itemize + + @noindent + By default, GNAT supplies a version of SYSTEM that matches + the definition given in the Ada 95 Reference Manual. + This + is a subset of the DIGITAL system definitions, which is as + close as possible to the original definitions. The only difference + is that the definition of SYSTEM_NAME is different: + + @smallexample @c ada + @group + @cartouche + type Name is (SYSTEM_NAME_GNAT); + System_Name : constant Name := SYSTEM_NAME_GNAT; + @end cartouche + @end group + @end smallexample + + @noindent + Also, GNAT adds the new Ada 95 declarations for + BIT_ORDER and DEFAULT_BIT_ORDER. + + However, the use of the following pragma causes GNAT + to extend the definition of package SYSTEM so that it + encompasses the full set of DIGITAL-specific extensions, + including the functions listed above: + + @smallexample @c ada + @cartouche + pragma Extend_System (Aux_DEC); + @end cartouche + @end smallexample + + @noindent + The pragma Extend_System is a configuration pragma that + is most conveniently placed in the @file{gnat.adc} file. See the + GNAT Reference Manual for further details. + + DEC Ada does not allow the recompilation of the package + SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_ + NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in + the package SYSTEM. On OpenVMS Alpha systems, the pragma + SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as + its single argument. + + GNAT does permit the recompilation of package SYSTEM using + a special switch (@option{-gnatg}) and this switch can be used if + it is necessary to modify the definitions in SYSTEM. GNAT does + not permit the specification of SYSTEM_NAME, STORAGE_UNIT + or MEMORY_SIZE by any other means. + + On GNAT systems, the pragma SYSTEM_NAME takes the + enumeration literal SYSTEM_NAME_GNAT. + + The definitions provided by the use of + + @smallexample @c ada + pragma Extend_System (AUX_Dec); + @end smallexample + + @noindent + are virtually identical to those provided by the DEC Ada 83 package + System. One important difference is that the name of the TO_ADDRESS + function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG. + See the GNAT Reference manual for a discussion of why this change was + necessary. + + @noindent + The version of TO_ADDRESS taking a universal integer argument is in fact + an extension to Ada 83 not strictly compatible with the reference manual. + In GNAT, we are constrained to be exactly compatible with the standard, + and this means we cannot provide this capability. In DEC Ada 83, the + point of this definition is to deal with a call like: + + @smallexample @c ada + TO_ADDRESS (16#12777#); + @end smallexample + + @noindent + Normally, according to the Ada 83 standard, one would expect this to be + ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms + of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the + definition using universal_integer takes precedence. + + In GNAT, since the version with universal_integer cannot be supplied, it is + not possible to be 100% compatible. Since there are many programs using + numeric constants for the argument to TO_ADDRESS, the decision in GNAT was + to change the name of the function in the UNSIGNED_LONGWORD case, so the + declarations provided in the GNAT version of AUX_Dec are: + + @smallexample @c ada + function To_Address (X : Integer) return Address; + pragma Pure_Function (To_Address); + + function To_Address_Long (X : Unsigned_Longword) return Address; + pragma Pure_Function (To_Address_Long); + @end smallexample + + @noindent + This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must + change the name to TO_ADDRESS_LONG. + + @node Tasking and Task-Related Features + @section Tasking and Task-Related Features + + @noindent + The concepts relevant to a comparison of tasking on GNAT + and on DEC Ada for OpenVMS Alpha systems are discussed in + the following sections. + + For detailed information on concepts related to tasking in + DEC Ada, see the DEC Ada Language Reference Manual and the + relevant run-time reference manual. + + @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems + @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems + + @noindent + On OpenVMS Alpha systems, each Ada task (except a passive + task) is implemented as a single stream of execution + that is created and managed by the kernel. On these + systems, DEC Ada tasking support is based on DECthreads, + an implementation of the POSIX standard for threads. + + Although tasks are implemented as threads, all tasks in + an Ada program are part of the same process. As a result, + resources such as open files and virtual memory can be + shared easily among tasks. Having all tasks in one process + allows better integration with the programming environment + (the shell and the debugger, for example). + + Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign + code that calls DECthreads routines can be used together. + The interaction between Ada tasks and DECthreads routines + can have some benefits. For example when on OpenVMS Alpha, + DEC Ada can call C code that is already threaded. + GNAT on OpenVMS Alpha uses the facilities of DECthreads, + and Ada tasks are mapped to threads. + + @menu + * Assigning Task IDs:: + * Task IDs and Delays:: + * Task-Related Pragmas:: + * Scheduling and Task Priority:: + * The Task Stack:: + * External Interrupts:: + @end menu + + @node Assigning Task IDs + @subsection Assigning Task IDs + + @noindent + The DEC Ada Run-Time Library always assigns %TASK 1 to + the environment task that executes the main program. On + OpenVMS Alpha systems, %TASK 0 is often used for tasks + that have been created but are not yet activated. + + On OpenVMS Alpha systems, task IDs are assigned at + activation. On GNAT systems, task IDs are also assigned at + task creation but do not have the same form or values as + task ID values in DEC Ada. There is no null task, and the + environment task does not have a specific task ID value. + + @node Task IDs and Delays + @subsection Task IDs and Delays + + @noindent + On OpenVMS Alpha systems, tasking delays are implemented + using Timer System Services. The Task ID is used for the + identification of the timer request (the REQIDT parameter). + If Timers are used in the application take care not to use + 0 for the identification, because cancelling such a timer + will cancel all timers and may lead to unpredictable results. + + @node Task-Related Pragmas + @subsection Task-Related Pragmas + + @noindent + Ada supplies the pragma TASK_STORAGE, which allows + specification of the size of the guard area for a task + stack. (The guard area forms an area of memory that has no + read or write access and thus helps in the detection of + stack overflow.) On OpenVMS Alpha systems, if the pragma + TASK_STORAGE specifies a value of zero, a minimal guard + area is created. In the absence of a pragma TASK_STORAGE, a default guard + area is created. + + GNAT supplies the following task-related pragmas: + + @itemize @bullet + @item TASK_INFO + + This pragma appears within a task definition and + applies to the task in which it appears. The argument + must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE. + + @item TASK_STORAGE + + GNAT implements pragma TASK_STORAGE in the same way as + DEC Ada. + Both DEC Ada and GNAT supply the pragmas PASSIVE, + SUPPRESS, and VOLATILE. + @end itemize + @node Scheduling and Task Priority + @subsection Scheduling and Task Priority + + @noindent + DEC Ada implements the Ada language requirement that + when two tasks are eligible for execution and they have + different priorities, the lower priority task does not + execute while the higher priority task is waiting. The DEC + Ada Run-Time Library keeps a task running until either the + task is suspended or a higher priority task becomes ready. + + On OpenVMS Alpha systems, the default strategy is round- + robin with preemption. Tasks of equal priority take turns + at the processor. A task is run for a certain period of + time and then placed at the rear of the ready queue for + its priority level. + + DEC Ada provides the implementation-defined pragma TIME_SLICE, + which can be used to enable or disable round-robin + scheduling of tasks with the same priority. + See the relevant DEC Ada run-time reference manual for + information on using the pragmas to control DEC Ada task + scheduling. + + GNAT follows the scheduling rules of Annex D (real-time + Annex) of the Ada 95 Reference Manual. In general, this + scheduling strategy is fully compatible with DEC Ada + although it provides some additional constraints (as + fully documented in Annex D). + GNAT implements time slicing control in a manner compatible with + DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical + to the DEC Ada 83 pragma of the same name. + Note that it is not possible to mix GNAT tasking and + DEC Ada 83 tasking in the same program, since the two run times are + not compatible. + + @node The Task Stack + @subsection The Task Stack + + @noindent + In DEC Ada, a task stack is allocated each time a + non passive task is activated. As soon as the task is + terminated, the storage for the task stack is deallocated. + If you specify a size of zero (bytes) with T'STORAGE_SIZE, + a default stack size is used. Also, regardless of the size + specified, some additional space is allocated for task + management purposes. On OpenVMS Alpha systems, at least + one page is allocated. + + GNAT handles task stacks in a similar manner. According to + the Ada 95 rules, it provides the pragma STORAGE_SIZE as + an alternative method for controlling the task stack size. + The specification of the attribute T'STORAGE_SIZE is also + supported in a manner compatible with DEC Ada. + + @node External Interrupts + @subsection External Interrupts + + @noindent + On DEC Ada, external interrupts can be associated with task entries. + GNAT is compatible with DEC Ada in its handling of external interrupts. + + @node Pragmas and Pragma-Related Features + @section Pragmas and Pragma-Related Features + + @noindent + Both DEC Ada and GNAT supply all language-defined pragmas + as specified by the Ada 83 standard. GNAT also supplies all + language-defined pragmas specified in the Ada 95 Reference Manual. + In addition, GNAT implements the implementation-defined pragmas + from DEC Ada 83. + + @itemize @bullet + @item AST_ENTRY + + @item COMMON_OBJECT + + @item COMPONENT_ALIGNMENT + + @item EXPORT_EXCEPTION + + @item EXPORT_FUNCTION + + @item EXPORT_OBJECT + + @item EXPORT_PROCEDURE + + @item EXPORT_VALUED_PROCEDURE + + @item FLOAT_REPRESENTATION + + @item IDENT + + @item IMPORT_EXCEPTION + + @item IMPORT_FUNCTION + + @item IMPORT_OBJECT + + @item IMPORT_PROCEDURE + + @item IMPORT_VALUED_PROCEDURE + + @item INLINE_GENERIC + + @item INTERFACE_NAME + + @item LONG_FLOAT + + @item MAIN_STORAGE + + @item PASSIVE + + @item PSET_OBJECT + + @item SHARE_GENERIC + + @item SUPPRESS_ALL + + @item TASK_STORAGE + + @item TIME_SLICE + + @item TITLE + @end itemize + + @noindent + These pragmas are all fully implemented, with the exception of @code{Title}, + @code{Passive}, and @code{Share_Generic}, which are + recognized, but which have no + effect in GNAT. The effect of @code{Passive} may be obtained by the + use of protected objects in Ada 95. In GNAT, all generics are inlined. + + Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require + a separate subprogram specification which must appear before the + subprogram body. + + GNAT also supplies a number of implementation-defined pragmas as follows: + @itemize @bullet + @item C_PASS_BY_COPY + + @item EXTEND_SYSTEM + + @item SOURCE_FILE_NAME + + @item UNSUPPRESS + + @item WARNINGS + + @item ABORT_DEFER + + @item ADA_83 + + @item ADA_95 + + @item ANNOTATE + + @item ASSERT + + @item CPP_CLASS + + @item CPP_CONSTRUCTOR + + @item CPP_DESTRUCTOR + + @item CPP_VIRTUAL + + @item CP_VTABLE + + @item DEBUG + + @item LINKER_ALIAS + + @item LINKER_SECTION + + @item MACHINE_ATTRIBUTE + + @item NO_RETURN + + @item PURE_FUNCTION + + @item SOURCE_REFERENCE + + @item TASK_INFO + + @item UNCHECKED_UNION + + @item UNIMPLEMENTED_UNIT + + @item UNIVERSAL_DATA + + @item WEAK_EXTERNAL + @end itemize + + @noindent + For full details on these GNAT implementation-defined pragmas, see + the GNAT Reference Manual. + + @menu + * Restrictions on the Pragma INLINE:: + * Restrictions on the Pragma INTERFACE:: + * Restrictions on the Pragma SYSTEM_NAME:: + @end menu + + @node Restrictions on the Pragma INLINE + @subsection Restrictions on the Pragma INLINE + + @noindent + DEC Ada applies the following restrictions to the pragma INLINE: + @itemize @bullet + @item Parameters cannot be a task type. + + @item Function results cannot be task types, unconstrained + array types, or unconstrained types with discriminants. + + @item Bodies cannot declare the following: + @itemize @bullet + @item Subprogram body or stub (imported subprogram is allowed) + + @item Tasks + + @item Generic declarations + + @item Instantiations + + @item Exceptions + + @item Access types (types derived from access types allowed) + + @item Array or record types + + @item Dependent tasks + + @item Direct recursive calls of subprogram or containing + subprogram, directly or via a renaming + + @end itemize + @end itemize + + @noindent + In GNAT, the only restriction on pragma INLINE is that the + body must occur before the call if both are in the same + unit, and the size must be appropriately small. There are + no other specific restrictions which cause subprograms to + be incapable of being inlined. + + @node Restrictions on the Pragma INTERFACE + @subsection Restrictions on the Pragma INTERFACE + + @noindent + The following lists and describes the restrictions on the + pragma INTERFACE on DEC Ada and GNAT: + @itemize @bullet + @item Languages accepted: Ada, Bliss, C, Fortran, Default. + Default is the default on OpenVMS Alpha systems. + + @item Parameter passing: Language specifies default + mechanisms but can be overridden with an EXPORT pragma. + + @itemize @bullet + @item Ada: Use internal Ada rules. + + @item Bliss, C: Parameters must be mode @code{in}; cannot be + record or task type. Result cannot be a string, an + array, or a record. + + @item Fortran: Parameters cannot be a task. Result cannot + be a string, an array, or a record. + @end itemize + @end itemize + + @noindent + GNAT is entirely upwards compatible with DEC Ada, and in addition allows + record parameters for all languages. + + @node Restrictions on the Pragma SYSTEM_NAME + @subsection Restrictions on the Pragma SYSTEM_NAME + + @noindent + For DEC Ada for OpenVMS Alpha, the enumeration literal + for the type NAME is OPENVMS_AXP. In GNAT, the enumeration + literal for the type NAME is SYSTEM_NAME_GNAT. + + @node Library of Predefined Units + @section Library of Predefined Units + + @noindent + A library of predefined units is provided as part of the + DEC Ada and GNAT implementations. DEC Ada does not provide + the package MACHINE_CODE but instead recommends importing + assembler code. + + The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:) + units are taken from the OpenVMS Alpha version, not the OpenVMS VAX + version. During GNAT installation, the DEC Ada Predefined + Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] + (aka DECLIB) directory and patched to remove Ada 95 incompatibilities + and to make them interoperable with GNAT, @pxref{Changes to DECLIB} + for details. + + The GNAT RTL is contained in + the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and + the default search path is set up to find DECLIB units in preference + to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO, + for example). + + However, it is possible to change the default so that the + reverse is true, or even to mix them using child package + notation. The DEC Ada 83 units are available as DEC.xxx where xxx + is the package name, and the Ada units are available in the + standard manner defined for Ada 95, that is to say as Ada.xxx. To + change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH + appropriately. For example, to change the default to use the Ada95 + versions do: + + @smallexample + $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],- + GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB] + $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],- + GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB] + @end smallexample + + @menu + * Changes to DECLIB:: + @end menu + + @node Changes to DECLIB + @subsection Changes to DECLIB + + @noindent + The changes made to the DEC Ada predefined library for GNAT and Ada 95 + compatibility are minor and include the following: + + @itemize @bullet + @item Adjusting the location of pragmas and record representation + clauses to obey Ada 95 rules + + @item Adding the proper notation to generic formal parameters + that take unconstrained types in instantiation + + @item Adding pragma ELABORATE_BODY to package specifications + that have package bodies not otherwise allowed + + @item Occurrences of the identifier @code{"PROTECTED"} are renamed to + @code{"PROTECTD"}. + Currently these are found only in the STARLET package spec. + @end itemize + + @noindent + None of the above changes is visible to users. + + @node Bindings + @section Bindings + + @noindent + On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings: + @itemize @bullet + + @item Command Language Interpreter (CLI interface) + + @item DECtalk Run-Time Library (DTK interface) + + @item Librarian utility routines (LBR interface) + + @item General Purpose Run-Time Library (LIB interface) + + @item Math Run-Time Library (MTH interface) + + @item National Character Set Run-Time Library (NCS interface) + + @item Compiled Code Support Run-Time Library (OTS interface) + + @item Parallel Processing Run-Time Library (PPL interface) + + @item Screen Management Run-Time Library (SMG interface) + + @item Sort Run-Time Library (SOR interface) + + @item String Run-Time Library (STR interface) + + @item STARLET System Library + @findex Starlet + + @item X Window System Version 11R4 and 11R5 (X, XLIB interface) + + @item X Windows Toolkit (XT interface) + + @item X/Motif Version 1.1.3 and 1.2 (XM interface) + @end itemize + + @noindent + GNAT provides implementations of these DEC bindings in the DECLIB directory. + + The X/Motif bindings used to build DECLIB are whatever versions are in the + DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}. + The build script will + automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt}, + and @code{X_Lib} + causing the default X/Motif sharable image libraries to be linked in. This + is done via options files named @file{xm.opt}, @file{xt.opt}, and + @file{x_lib.opt} (also located in the @file{DECLIB} directory). + + It may be necessary to edit these options files to update or correct the + library names if, for example, the newer X/Motif bindings from + @file{ADA$EXAMPLES} + had been (previous to installing GNAT) copied and renamed to supersede the + default @file{ADA$PREDEFINED} versions. + + @menu + * Shared Libraries and Options Files:: + * Interfaces to C:: + @end menu + + @node Shared Libraries and Options Files + @subsection Shared Libraries and Options Files + + @noindent + When using the DEC Ada + predefined X and Motif bindings, the linking with their sharable images is + done automatically by @command{GNAT LINK}. + When using other X and Motif bindings, you need + to add the corresponding sharable images to the command line for + @code{GNAT LINK}. When linking with shared libraries, or with + @file{.OPT} files, you must + also add them to the command line for @command{GNAT LINK}. + + A shared library to be used with GNAT is built in the same way as other + libraries under VMS. The VMS Link command can be used in standard fashion. + + @node Interfaces to C + @subsection Interfaces to C + + @noindent + DEC Ada + provides the following Ada types and operations: + + @itemize @bullet + @item C types package (C_TYPES) + + @item C strings (C_TYPES.NULL_TERMINATED) + + @item Other_types (SHORT_INT) + @end itemize + + @noindent + Interfacing to C with GNAT, one can use the above approach + described for DEC Ada or the facilities of Annex B of + the Ada 95 Reference Manual (packages INTERFACES.C, + INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more + information, see the section ``Interfacing to C'' in the + @cite{GNAT Reference Manual}. + + The @option{-gnatF} qualifier forces default and explicit + @code{External_Name} parameters in pragmas Import and Export + to be uppercased for compatibility with the default behavior + of Compaq C. The qualifier has no effect on @code{Link_Name} parameters. + + @node Main Program Definition + @section Main Program Definition + + @noindent + The following section discusses differences in the + definition of main programs on DEC Ada and GNAT. + On DEC Ada, main programs are defined to meet the + following conditions: + @itemize @bullet + @item Procedure with no formal parameters (returns 0 upon + normal completion) + + @item Procedure with no formal parameters (returns 42 when + unhandled exceptions are raised) + + @item Function with no formal parameters whose returned value + is of a discrete type + + @item Procedure with one OUT formal of a discrete type for + which a specification of pragma EXPORT_VALUED_PROCEDURE is given. + + @end itemize + + @noindent + When declared with the pragma EXPORT_VALUED_PROCEDURE, + a main function or main procedure returns a discrete + value whose size is less than 64 bits (32 on VAX systems), + the value is zero- or sign-extended as appropriate. + On GNAT, main programs are defined as follows: + @itemize @bullet + @item Must be a non-generic, parameter-less subprogram that + is either a procedure or function returning an Ada + STANDARD.INTEGER (the predefined type) + + @item Cannot be a generic subprogram or an instantiation of a + generic subprogram + @end itemize + + @node Implementation-Defined Attributes + @section Implementation-Defined Attributes + + @noindent + GNAT provides all DEC Ada implementation-defined + attributes. + + @node Compiler and Run-Time Interfacing + @section Compiler and Run-Time Interfacing + + @noindent + DEC Ada provides the following ways to pass options to the linker + (ACS LINK): + @itemize @bullet + @item /WAIT and /SUBMIT qualifiers + + @item /COMMAND qualifier + + @item /[NO]MAP qualifier + + @item /OUTPUT=file-spec + + @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers + @end itemize + + @noindent + To pass options to the linker, GNAT provides the following + switches: + + @itemize @bullet + @item @option{/EXECUTABLE=exec-name} + + @item @option{/VERBOSE qualifier} + + @item @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers + @end itemize + + @noindent + For more information on these switches, see + @ref{Switches for gnatlink}. + In DEC Ada, the command-line switch @option{/OPTIMIZE} is available + to control optimization. DEC Ada also supplies the + following pragmas: + @itemize @bullet + @item @code{OPTIMIZE} + + @item @code{INLINE} + + @item @code{INLINE_GENERIC} + + @item @code{SUPPRESS_ALL} + + @item @code{PASSIVE} + @end itemize + + @noindent + In GNAT, optimization is controlled strictly by command + line parameters, as described in the corresponding section of this guide. + The DIGITAL pragmas for control of optimization are + recognized but ignored. + + Note that in GNAT, the default is optimization off, whereas in DEC Ada 83, + the default is that optimization is turned on. + + @node Program Compilation and Library Management + @section Program Compilation and Library Management + + @noindent + DEC Ada and GNAT provide a comparable set of commands to + build programs. DEC Ada also provides a program library, + which is a concept that does not exist on GNAT. Instead, + GNAT provides directories of sources that are compiled as + needed. + + The following table summarizes + the DEC Ada commands and provides + equivalent GNAT commands. In this table, some GNAT + equivalents reflect the fact that GNAT does not use the + concept of a program library. Instead, it uses a model + in which collections of source and object files are used + in a manner consistent with other languages like C and + Fortran. Therefore, standard system file commands are used + to manipulate these elements. Those GNAT commands are marked with + an asterisk. + Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards. + + @need 1500 + @multitable @columnfractions .35 .65 + + @item @emph{DEC Ada Command} + @tab @emph{GNAT Equivalent / Description} + + @item @command{ADA} + @tab @command{GNAT COMPILE}@* + Invokes the compiler to compile one or more Ada source files. + + @item @command{ACS ATTACH}@* + @tab [No equivalent]@* + Switches control of terminal from current process running the program + library manager. + + @item @command{ACS CHECK} + @tab @command{GNAT MAKE /DEPENDENCY_LIST}@* + Forms the execution closure of one + or more compiled units and checks completeness and currency. + + @item @command{ACS COMPILE} + @tab @command{GNAT MAKE /ACTIONS=COMPILE}@* + Forms the execution closure of one or + more specified units, checks completeness and currency, + identifies units that have revised source files, compiles same, + and recompiles units that are or will become obsolete. + Also completes incomplete generic instantiations. + + @item @command{ACS COPY FOREIGN} + @tab Copy (*)@* + Copies a foreign object file into the program library as a + library unit body. + + @item @command{ACS COPY UNIT} + @tab Copy (*)@* + Copies a compiled unit from one program library to another. + + @item @command{ACS CREATE LIBRARY} + @tab Create /directory (*)@* + Creates a program library. + + @item @command{ACS CREATE SUBLIBRARY} + @tab Create /directory (*)@* + Creates a program sublibrary. + + @item @command{ACS DELETE LIBRARY} + @tab @* + Deletes a program library and its contents. + + @item @command{ACS DELETE SUBLIBRARY} + @tab @* + Deletes a program sublibrary and its contents. + + @item @command{ACS DELETE UNIT} + @tab Delete file (*)@* + On OpenVMS systems, deletes one or more compiled units from + the current program library. + + @item @command{ACS DIRECTORY} + @tab Directory (*)@* + On OpenVMS systems, lists units contained in the current + program library. + + @item @command{ACS ENTER FOREIGN} + @tab Copy (*)@* + Allows the import of a foreign body as an Ada library + specification and enters a reference to a pointer. + + @item @command{ACS ENTER UNIT} + @tab Copy (*)@* + Enters a reference (pointer) from the current program library to + a unit compiled into another program library. + + @item @command{ACS EXIT} + @tab [No equivalent]@* + Exits from the program library manager. + + @item @command{ACS EXPORT} + @tab Copy (*)@* + Creates an object file that contains system-specific object code + for one or more units. With GNAT, object files can simply be copied + into the desired directory. + + @item @command{ACS EXTRACT SOURCE} + @tab Copy (*)@* + Allows access to the copied source file for each Ada compilation unit + + @item @command{ACS HELP} + @tab @command{HELP GNAT}@* + Provides online help. + + @item @command{ACS LINK} + @tab @command{GNAT LINK}@* + Links an object file containing Ada units into an executable file. + + @item @command{ACS LOAD} + @tab Copy (*)@* + Loads (partially compiles) Ada units into the program library. + Allows loading a program from a collection of files into a library + without knowing the relationship among units. + + @item @command{ACS MERGE} + @tab Copy (*)@* + Merges into the current program library, one or more units from + another library where they were modified. + + @item @command{ACS RECOMPILE} + @tab @command{GNAT MAKE /ACTIONS=COMPILE}@* + Recompiles from external or copied source files any obsolete + unit in the closure. Also, completes any incomplete generic + instantiations. + + @item @command{ACS REENTER} + @tab @command{GNAT MAKE}@* + Reenters current references to units compiled after last entered + with the @command{ACS ENTER UNIT} command. + + @item @command{ACS SET LIBRARY} + @tab Set default (*)@* + Defines a program library to be the compilation context as well + as the target library for compiler output and commands in general. + + @item @command{ACS SET PRAGMA} + @tab Edit @file{gnat.adc} (*)@* + Redefines specified values of the library characteristics + @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME}, + and @code{Float_Representation}. + + @item @command{ACS SET SOURCE} + @tab Define @code{ADA_INCLUDE_PATH} path (*)@* + Defines the source file search list for the @command{ACS COMPILE} command. + + @item @command{ACS SHOW LIBRARY} + @tab Directory (*)@* + Lists information about one or more program libraries. + + @item @command{ACS SHOW PROGRAM} + @tab [No equivalent]@* + Lists information about the execution closure of one or + more units in the program library. + + @item @command{ACS SHOW SOURCE} + @tab Show logical @code{ADA_INCLUDE_PATH}@* + Shows the source file search used when compiling units. + + @item @command{ACS SHOW VERSION} + @tab Compile with @option{VERBOSE} option + Displays the version number of the compiler and program library + manager used. + + @item @command{ACS SPAWN} + @tab [No equivalent]@* + Creates a subprocess of the current process (same as @command{DCL SPAWN} + command). + + @item @command{ACS VERIFY} + @tab [No equivalent]@* + Performs a series of consistency checks on a program library to + determine whether the library structure and library files are in + valid form. + @end multitable + + @noindent + + @node Input-Output + @section Input-Output + + @noindent + On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record + Management Services (RMS) to perform operations on + external files. + + @noindent + DEC Ada and GNAT predefine an identical set of input- + output packages. To make the use of the + generic TEXT_IO operations more convenient, DEC Ada + provides predefined library packages that instantiate the + integer and floating-point operations for the predefined + integer and floating-point types as shown in the following table. + + @multitable @columnfractions .45 .55 + @item @emph{Package Name} @tab Instantiation + + @item @code{INTEGER_TEXT_IO} + @tab @code{INTEGER_IO(INTEGER)} + + @item @code{SHORT_INTEGER_TEXT_IO} + @tab @code{INTEGER_IO(SHORT_INTEGER)} + + @item @code{SHORT_SHORT_INTEGER_TEXT_IO} + @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)} + + @item @code{FLOAT_TEXT_IO} + @tab @code{FLOAT_IO(FLOAT)} + + @item @code{LONG_FLOAT_TEXT_IO} + @tab @code{FLOAT_IO(LONG_FLOAT)} + @end multitable + + @noindent + The DEC Ada predefined packages and their operations + are implemented using OpenVMS Alpha files and input- + output facilities. DEC Ada supports asynchronous input- + output on OpenVMS Alpha. Familiarity with the following is + recommended: + @itemize @bullet + @item RMS file organizations and access methods + + @item OpenVMS file specifications and directories + + @item OpenVMS File Definition Language (FDL) + @end itemize + + @noindent + GNAT provides I/O facilities that are completely + compatible with DEC Ada. The distribution includes the + standard DEC Ada versions of all I/O packages, operating + in a manner compatible with DEC Ada. In particular, the + following packages are by default the DEC Ada (Ada 83) + versions of these packages rather than the renamings + suggested in annex J of the Ada 95 Reference Manual: + @itemize @bullet + @item @code{TEXT_IO} + + @item @code{SEQUENTIAL_IO} + + @item @code{DIRECT_IO} + @end itemize + + @noindent + The use of the standard Ada 95 syntax for child packages (for + example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these + packages, as defined in the Ada 95 Reference Manual. + GNAT provides DIGITAL-compatible predefined instantiations + of the @code{TEXT_IO} packages, and also + provides the standard predefined instantiations required + by the Ada 95 Reference Manual. + + For further information on how GNAT interfaces to the file + system or how I/O is implemented in programs written in + mixed languages, see the chapter ``Implementation of the + Standard I/O'' in the @cite{GNAT Reference Manual}. + This chapter covers the following: + @itemize @bullet + @item Standard I/O packages + + @item @code{FORM} strings + + @item @code{ADA.DIRECT_IO} + + @item @code{ADA.SEQUENTIAL_IO} + + @item @code{ADA.TEXT_IO} + + @item Stream pointer positioning + + @item Reading and writing non-regular files + + @item @code{GET_IMMEDIATE} + + @item Treating @code{TEXT_IO} files as streams + + @item Shared files + + @item Open modes + @end itemize + + @node Implementation Limits + @section Implementation Limits + + @noindent + The following table lists implementation limits for DEC Ada + and GNAT systems. + @multitable @columnfractions .60 .20 .20 + @sp 1 + @item @emph{Compilation Parameter} + @tab @emph{DEC Ada} + @tab @emph{GNAT} + @sp 1 + + @item In a subprogram or entry declaration, maximum number of + formal parameters that are of an unconstrained record type + @tab 32 + @tab No set limit + @sp 1 + + @item Maximum identifier length (number of characters) + @tab 255 + @tab 255 + @sp 1 + + @item Maximum number of characters in a source line + @tab 255 + @tab 255 + @sp 1 + + @item Maximum collection size (number of bytes) + @tab 2**31-1 + @tab 2**31-1 + @sp 1 + + @item Maximum number of discriminants for a record type + @tab 245 + @tab No set limit + @sp 1 + + @item Maximum number of formal parameters in an entry or + subprogram declaration + @tab 246 + @tab No set limit + @sp 1 + + @item Maximum number of dimensions in an array type + @tab 255 + @tab No set limit + @sp 1 + + @item Maximum number of library units and subunits in a compilation. + @tab 4095 + @tab No set limit + @sp 1 + + @item Maximum number of library units and subunits in an execution. + @tab 16383 + @tab No set limit + @sp 1 + + @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT} + or @code{PSECT_OBJECT} + @tab 32757 + @tab No set limit + @sp 1 + + @item Maximum number of enumeration literals in an enumeration type + definition + @tab 65535 + @tab No set limit + @sp 1 + + @item Maximum number of lines in a source file + @tab 65534 + @tab No set limit + @sp 1 + + @item Maximum number of bits in any object + @tab 2**31-1 + @tab 2**31-1 + @sp 1 + + @item Maximum size of the static portion of a stack frame (approximate) + @tab 2**31-1 + @tab 2**31-1 + @end multitable + + @node Tools + @section Tools + + @end ifset + + + @c ************************************** + @node Platform-Specific Information for the Run-Time Libraries + @appendix Platform-Specific Information for the Run-Time Libraries + @cindex Tasking and threads libraries + @cindex Threads libraries and tasking + @cindex Run-time libraries (platform-specific information) + + @noindent + The GNAT run-time implementation + may vary with respect to both the underlying threads library and + the exception handling scheme. + For threads support, one or more of the following are supplied: + @itemize @bullet + @item @b{native threads library}, a binding to the thread package from + the underlying operating system + + @item @b{FSU threads library}, a binding to the Florida State University + threads implementation, which complies fully with the requirements of Annex D + + @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris + POSIX thread package + @end itemize + + @noindent + For exception handling, either or both of two models are supplied: + @itemize @bullet + @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{ + Most programs should experience a substantial speed improvement by + being compiled with a ZCX run-time. + This is especially true for + tasking applications or applications with many exception handlers.} + @cindex Zero-Cost Exceptions + @cindex ZCX (Zero-Cost Exceptions) + which uses binder-generated tables that + are interrogated at run time to locate a handler + + @item @b{setjmp / longjmp} (``SJLJ''), + @cindex setjmp/longjmp Exception Model + @cindex SJLJ (setjmp/longjmp Exception Model) + which uses dynamically-set data to establish + the set of handlers + @end itemize + + @noindent + This appendix summarizes which combinations of threads and exception support + are supplied on various GNAT platforms. + It then shows how to select a particular library either + permanently or temporarily, + explains the properties of (and tradeoffs among) the various threads + libraries, and provides some additional + information about several specific platforms. + + @menu + * Summary of Run-Time Configurations:: + * Specifying a Run-Time Library:: + * Choosing between Native and FSU Threads Libraries:: + * Choosing the Scheduling Policy:: + * Solaris-Specific Considerations:: + * IRIX-Specific Considerations:: + * Linux-Specific Considerations:: + @end menu + + + @node Summary of Run-Time Configurations + @section Summary of Run-Time Configurations + + + @multitable @columnfractions .30 .70 + @item @b{alpha-openvms} + @item @code{@ @ }@i{rts-native (default)} + @item @code{@ @ @ @ }Tasking @tab native VMS threads + @item @code{@ @ @ @ }Exceptions @tab ZCX + @* + @item @b{pa-hpux} + @item @code{@ @ }@i{rts-native (default)} + @item @code{@ @ @ @ }Tasking @tab native HP threads library + @item @code{@ @ @ @ }Exceptions @tab ZCX + @* + @item @code{@ @ }@i{rts-sjlj} + @item @code{@ @ @ @ }Tasking @tab native HP threads library + @item @code{@ @ @ @ }Exceptions @tab SJLJ + @* + @item @b{sparc-solaris} @tab + @item @code{@ @ }@i{rts-native (default)} + @item @code{@ @ @ @ }Tasking @tab native Solaris threads library + @item @code{@ @ @ @ }Exceptions @tab ZCX + @* + @item @code{@ @ }@i{rts-fsu} @tab + @item @code{@ @ @ @ }Tasking @tab FSU threads library + @item @code{@ @ @ @ }Exceptions @tab SJLJ + @* + @item @code{@ @ }@i{rts-m64} + @item @code{@ @ @ @ }Tasking @tab native Solaris threads library + @item @code{@ @ @ @ }Exceptions @tab ZCX + @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode; + @item @tab Use only on Solaris 8 or later. + @item @tab @xref{Building and Debugging 64-bit Applications}, for details. + @* + @item @code{@ @ }@i{rts-pthread} + @item @code{@ @ @ @ }Tasking @tab pthreads library + @item @code{@ @ @ @ }Exceptions @tab ZCX + @* + @item @code{@ @ }@i{rts-sjlj} + @item @code{@ @ @ @ }Tasking @tab native Solaris threads library + @item @code{@ @ @ @ }Exceptions @tab SJLJ + @* + @item @b{x86-linux} + @item @code{@ @ }@i{rts-native (default)} + @item @code{@ @ @ @ }Tasking @tab LinuxThread library + @item @code{@ @ @ @ }Exceptions @tab ZCX + @* + @item @code{@ @ }@i{rts-fsu} + @item @code{@ @ @ @ }Tasking @tab FSU threads library + @item @code{@ @ @ @ }Exceptions @tab SJLJ + @* + @item @code{@ @ }@i{rts-sjlj} + @item @code{@ @ @ @ }Tasking @tab LinuxThread library + @item @code{@ @ @ @ }Exceptions @tab SJLJ + @* + @item @b{x86-windows} + @item @code{@ @ }@i{rts-native (default)} + @item @code{@ @ @ @ }Tasking @tab native Win32 threads + @item @code{@ @ @ @ }Exceptions @tab SJLJ + @* + @end multitable + + + + @node Specifying a Run-Time Library + @section Specifying a Run-Time Library + + @noindent + The @file{adainclude} subdirectory containing the sources of the GNAT + run-time library, and the @file{adalib} subdirectory containing the + @file{ALI} files and the static and/or shared GNAT library, are located + in the gcc target-dependent area: + + @smallexample + target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/ + @end smallexample + + @noindent + As indicated above, on some platforms several run-time libraries are supplied. + These libraries are installed in the target dependent area and + contain a complete source and binary subdirectory. The detailed description + below explains the differences between the different libraries in terms of + their thread support. + + The default run-time library (when GNAT is installed) is @emph{rts-native}. + This default run time is selected by the means of soft links. + For example on x86-linux: + + @smallexample + @group + $(target-dir) + | + +--- adainclude----------+ + | | + +--- adalib-----------+ | + | | | + +--- rts-native | | + | | | | + | +--- adainclude <---+ + | | | + | +--- adalib <----+ + | + +--- rts-fsu + | | + | +--- adainclude + | | + | +--- adalib + | + +--- rts-sjlj + | + +--- adainclude + | + +--- adalib + @end group + @end smallexample + + @noindent + If the @i{rts-fsu} library is to be selected on a permanent basis, + these soft links can be modified with the following commands: + + @smallexample + $ cd $target + $ rm -f adainclude adalib + $ ln -s rts-fsu/adainclude adainclude + $ ln -s rts-fsu/adalib adalib + @end smallexample + + @noindent + Alternatively, you can specify @file{rts-fsu/adainclude} in the file + @file{$target/ada_source_path} and @file{rts-fsu/adalib} in + @file{$target/ada_object_path}. + + Selecting another run-time library temporarily can be + achieved by the regular mechanism for GNAT object or source path selection: + + @itemize @bullet + @item + Set the environment variables: + + @smallexample + $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH + $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH + $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH + @end smallexample + + @item + Use @option{-aI$target/rts-fsu/adainclude} + and @option{-aO$target/rts-fsu/adalib} + on the @command{gnatmake} command line + + @item + Use the switch @option{--RTS}; e.g., @option{--RTS=fsu} + @cindex @option{--RTS} option + @end itemize + + @noindent + You can similarly switch to @emph{rts-sjlj}. + + @node Choosing between Native and FSU Threads Libraries + @section Choosing between Native and FSU Threads Libraries + @cindex Native threads library + @cindex FSU threads library + + @noindent + Some GNAT implementations offer a choice between + native threads and FSU threads. + + @itemize @bullet + @item + The @emph{native threads} library correspond to the standard system threads + implementation (e.g. LinuxThreads on GNU/Linux, + @cindex LinuxThreads library + POSIX threads on AIX, or + Solaris threads on Solaris). When this option is chosen, GNAT provides + a full and accurate implementation of the core language tasking model + as described in Chapter 9 of the Ada Reference Manual, + but might not (and probably does not) implement + the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex). + @cindex Annex D (Real-Time Systems Annex) compliance + @cindex Real-Time Systems Annex compliance + Indeed, the reason that a choice of libraries is offered + on a given target is because some of the + ACATS tests for @w{Annex D} fail using the native threads library. + As far as possible, this library is implemented + in accordance with Ada semantics (e.g., modifying priorities as required + to simulate ceiling locking), + but there are often slight inaccuracies, most often in the area of + absolutely respecting the priority rules on a single + processor. + Moreover, it is not possible in general to define the exact behavior, + because the native threads implementations + are not well enough documented. + + On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported, + @cindex POSIX scheduling policies + @cindex @code{SCHED_FIFO} scheduling policy + native threads will provide a behavior very close to the @w{Annex D} + requirements (i.e., a run-till-blocked scheduler with fixed priorities), but + on some systems (in particular GNU/Linux and Solaris), you need to have root + privileges to use the @code{SCHED_FIFO} policy. + + @item + The @emph{FSU threads} library provides a completely accurate implementation + of @w{Annex D}. + Thus, operating with this library, GNAT is 100% compliant with both the core + and all @w{Annex D} + requirements. + The formal validations for implementations offering + a choice of threads packages are always carried out using the FSU + threads option. + @end itemize + + @noindent + From these considerations, it might seem that FSU threads are the + better choice, + but that is by no means always the case. The FSU threads package + operates with all Ada tasks appearing to the system to be a single + thread. This is often considerably more efficient than operating + with separate threads, since for example, switching between tasks + can be accomplished without the (in some cases considerable) + overhead of a context switch between two system threads. However, + it means that you may well lose concurrency at the system + level. Notably, some system operations (such as I/O) may block all + tasks in a program and not just the calling task. More + significantly, the FSU threads approach likely means you cannot + take advantage of multiple processors, since for this you need + separate threads (or even separate processes) to operate on + different processors. + + For most programs, the native threads library is + usually the better choice. Use the FSU threads if absolute + conformance to @w{Annex D} is important for your application, or if + you find that the improved efficiency of FSU threads is significant to you. + + Note also that to take full advantage of Florist and Glade, it is highly + recommended that you use native threads. + + + @node Choosing the Scheduling Policy + @section Choosing the Scheduling Policy + + @noindent + When using a POSIX threads implementation, you have a choice of several + scheduling policies: @code{SCHED_FIFO}, + @cindex @code{SCHED_FIFO} scheduling policy + @code{SCHED_RR} + @cindex @code{SCHED_RR} scheduling policy + and @code{SCHED_OTHER}. + @cindex @code{SCHED_OTHER} scheduling policy + Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO} + or @code{SCHED_RR} requires special (e.g., root) privileges. + + By default, GNAT uses the @code{SCHED_OTHER} policy. To specify + @code{SCHED_FIFO}, + @cindex @code{SCHED_FIFO} scheduling policy + you can use one of the following: + + @itemize @bullet + @item + @code{pragma Time_Slice (0.0)} + @cindex pragma Time_Slice + @item + the corresponding binder option @option{-T0} + @cindex @option{-T0} option + @item + @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)} + @cindex pragma Task_Dispatching_Policy + @end itemize + + @noindent + To specify @code{SCHED_RR}, + @cindex @code{SCHED_RR} scheduling policy + you should use @code{pragma Time_Slice} with a + value greater than @code{0.0}, or else use the corresponding @option{-T} + binder option. + + + + @node Solaris-Specific Considerations + @section Solaris-Specific Considerations + @cindex Solaris Sparc threads libraries + + @noindent + This section addresses some topics related to the various threads libraries + on Sparc Solaris and then provides some information on building and + debugging 64-bit applications. + + @menu + * Solaris Threads Issues:: + * Building and Debugging 64-bit Applications:: + @end menu + + + @node Solaris Threads Issues + @subsection Solaris Threads Issues + + @noindent + Starting with version 3.14, GNAT under Solaris comes with a new tasking + run-time library based on POSIX threads --- @emph{rts-pthread}. + @cindex rts-pthread threads library + This run-time library has the advantage of being mostly shared across all + POSIX-compliant thread implementations, and it also provides under + @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT} + @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread) + and @code{PTHREAD_PRIO_PROTECT} + @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread) + semantics that can be selected using the predefined pragma + @code{Locking_Policy} + @cindex pragma Locking_Policy (under rts-pthread) + with respectively + @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy. + @cindex @code{Inheritance_Locking} (under rts-pthread) + @cindex @code{Ceiling_Locking} (under rts-pthread) + + As explained above, the native run-time library is based on the Solaris thread + library (@code{libthread}) and is the default library. + The FSU run-time library is based on the FSU threads. + @cindex FSU threads library + + Starting with Solaris 2.5.1, when the Solaris threads library is used + (this is the default), programs + compiled with GNAT can automatically take advantage of + and can thus execute on multiple processors. + The user can alternatively specify a processor on which the program should run + to emulate a single-processor system. The multiprocessor / uniprocessor choice + is made by + setting the environment variable @code{GNAT_PROCESSOR} + @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris) + to one of the following: + + @table @code + @item -2 + Use the default configuration (run the program on all + available processors) - this is the same as having + @code{GNAT_PROCESSOR} unset + + @item -1 + Let the run-time implementation choose one processor and run the program on + that processor + + @item 0 .. Last_Proc + Run the program on the specified processor. + @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1} + (where @code{_SC_NPROCESSORS_CONF} is a system variable). + @end table + + + @node Building and Debugging 64-bit Applications + @subsection Building and Debugging 64-bit Applications + + @noindent + In a 64-bit application, all the sources involved must be compiled with the + @option{-m64} command-line option, and a specific GNAT library (compiled with + this option) is required. + The easiest way to build a 64bit application is to add + @option{-m64 --RTS=m64} to the @command{gnatmake} flags. + + To debug these applications, dwarf-2 debug information is required, so you + have to add @option{-gdwarf-2} to your gnatmake arguments. + In addition, a special + version of gdb, called @command{gdb64}, needs to be used. + + To summarize, building and debugging a ``Hello World'' program in 64-bit mode + amounts to: + + @smallexample + $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb + $ gdb64 hello + @end smallexample + + + + @node IRIX-Specific Considerations + @section IRIX-Specific Considerations + @cindex IRIX thread library + + @noindent + On SGI IRIX, the thread library depends on which compiler is used. + The @emph{o32 ABI} compiler comes with a run-time library based on the + user-level @code{athread} + library. Thus kernel-level capabilities such as nonblocking system + calls or time slicing can only be achieved reliably by specifying different + @code{sprocs} via the pragma @code{Task_Info} + @cindex pragma Task_Info (and IRIX threads) + and the + @code{System.Task_Info} package. + @cindex @code{System.Task_Info} package (and IRIX threads) + See the @cite{GNAT Reference Manual} for further information. + + The @emph{n32 ABI} compiler comes with a run-time library based on the + kernel POSIX threads and thus does not have the limitations mentioned above. + + + @node Linux-Specific Considerations + @section Linux-Specific Considerations + @cindex Linux threads libraries + + @noindent + The default thread library under GNU/Linux has the following disadvantages + compared to other native thread libraries: + + @itemize @bullet + @item The size of the task's stack is limited to 2 megabytes. + @item The signal model is not POSIX compliant, which means that to send a + signal to the process, you need to send the signal to all threads, + e.g. by using @code{killpg()}. + @end itemize + + + + @c ******************************* + @node Example of Binder Output File + @appendix Example of Binder Output File + + @noindent + This Appendix displays the source code for @command{gnatbind}'s output + file generated for a simple ``Hello World'' program. + Comments have been added for clarification purposes. + + + @smallexample @c adanocomment + @iftex + @leftskip=0cm + @end iftex + -- The package is called Ada_Main unless this name is actually used + -- as a unit name in the partition, in which case some other unique + -- name is used. + + with System; + package ada_main is + + Elab_Final_Code : Integer; + pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); + + -- The main program saves the parameters (argument count, + -- argument values, environment pointer) in global variables + -- for later access by other units including + -- Ada.Command_Line. + + gnat_argc : Integer; + gnat_argv : System.Address; + gnat_envp : System.Address; + + -- The actual variables are stored in a library routine. This + -- is useful for some shared library situations, where there + -- are problems if variables are not in the library. + + pragma Import (C, gnat_argc); + pragma Import (C, gnat_argv); + pragma Import (C, gnat_envp); + + -- The exit status is similarly an external location + + gnat_exit_status : Integer; + pragma Import (C, gnat_exit_status); + + GNAT_Version : constant String := + "GNAT Version: 3.15w (20010315)"; + pragma Export (C, GNAT_Version, "__gnat_version"); + + -- This is the generated adafinal routine that performs + -- finalization at the end of execution. In the case where + -- Ada is the main program, this main program makes a call + -- to adafinal at program termination. + + procedure adafinal; + pragma Export (C, adafinal, "adafinal"); + + -- This is the generated adainit routine that performs + -- initialization at the start of execution. In the case + -- where Ada is the main program, this main program makes + -- a call to adainit at program startup. + + procedure adainit; + pragma Export (C, adainit, "adainit"); + + -- This routine is called at the start of execution. It is + -- a dummy routine that is used by the debugger to breakpoint + -- at the start of execution. + + procedure Break_Start; + pragma Import (C, Break_Start, "__gnat_break_start"); + + -- This is the actual generated main program (it would be + -- suppressed if the no main program switch were used). As + -- required by standard system conventions, this program has + -- the external name main. + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer; + pragma Export (C, main, "main"); + + -- The following set of constants give the version + -- identification values for every unit in the bound + -- partition. This identification is computed from all + -- dependent semantic units, and corresponds to the + -- string that would be returned by use of the + -- Body_Version or Version attributes. + + type Version_32 is mod 2 ** 32; + u00001 : constant Version_32 := 16#7880BEB3#; + u00002 : constant Version_32 := 16#0D24CBD0#; + u00003 : constant Version_32 := 16#3283DBEB#; + u00004 : constant Version_32 := 16#2359F9ED#; + u00005 : constant Version_32 := 16#664FB847#; + u00006 : constant Version_32 := 16#68E803DF#; + u00007 : constant Version_32 := 16#5572E604#; + u00008 : constant Version_32 := 16#46B173D8#; + u00009 : constant Version_32 := 16#156A40CF#; + u00010 : constant Version_32 := 16#033DABE0#; + u00011 : constant Version_32 := 16#6AB38FEA#; + u00012 : constant Version_32 := 16#22B6217D#; + u00013 : constant Version_32 := 16#68A22947#; + u00014 : constant Version_32 := 16#18CC4A56#; + u00015 : constant Version_32 := 16#08258E1B#; + u00016 : constant Version_32 := 16#367D5222#; + u00017 : constant Version_32 := 16#20C9ECA4#; + u00018 : constant Version_32 := 16#50D32CB6#; + u00019 : constant Version_32 := 16#39A8BB77#; + u00020 : constant Version_32 := 16#5CF8FA2B#; + u00021 : constant Version_32 := 16#2F1EB794#; + u00022 : constant Version_32 := 16#31AB6444#; + u00023 : constant Version_32 := 16#1574B6E9#; + u00024 : constant Version_32 := 16#5109C189#; + u00025 : constant Version_32 := 16#56D770CD#; + u00026 : constant Version_32 := 16#02F9DE3D#; + u00027 : constant Version_32 := 16#08AB6B2C#; + u00028 : constant Version_32 := 16#3FA37670#; + u00029 : constant Version_32 := 16#476457A0#; + u00030 : constant Version_32 := 16#731E1B6E#; + u00031 : constant Version_32 := 16#23C2E789#; + u00032 : constant Version_32 := 16#0F1BD6A1#; + u00033 : constant Version_32 := 16#7C25DE96#; + u00034 : constant Version_32 := 16#39ADFFA2#; + u00035 : constant Version_32 := 16#571DE3E7#; + u00036 : constant Version_32 := 16#5EB646AB#; + u00037 : constant Version_32 := 16#4249379B#; + u00038 : constant Version_32 := 16#0357E00A#; + u00039 : constant Version_32 := 16#3784FB72#; + u00040 : constant Version_32 := 16#2E723019#; + u00041 : constant Version_32 := 16#623358EA#; + u00042 : constant Version_32 := 16#107F9465#; + u00043 : constant Version_32 := 16#6843F68A#; + u00044 : constant Version_32 := 16#63305874#; + u00045 : constant Version_32 := 16#31E56CE1#; + u00046 : constant Version_32 := 16#02917970#; + u00047 : constant Version_32 := 16#6CCBA70E#; + u00048 : constant Version_32 := 16#41CD4204#; + u00049 : constant Version_32 := 16#572E3F58#; + u00050 : constant Version_32 := 16#20729FF5#; + u00051 : constant Version_32 := 16#1D4F93E8#; + u00052 : constant Version_32 := 16#30B2EC3D#; + u00053 : constant Version_32 := 16#34054F96#; + u00054 : constant Version_32 := 16#5A199860#; + u00055 : constant Version_32 := 16#0E7F912B#; + u00056 : constant Version_32 := 16#5760634A#; + u00057 : constant Version_32 := 16#5D851835#; + + -- The following Export pragmas export the version numbers + -- with symbolic names ending in B (for body) or S + -- (for spec) so that they can be located in a link. The + -- information provided here is sufficient to track down + -- the exact versions of units used in a given build. + + pragma Export (C, u00001, "helloB"); + pragma Export (C, u00002, "system__standard_libraryB"); + pragma Export (C, u00003, "system__standard_libraryS"); + pragma Export (C, u00004, "adaS"); + pragma Export (C, u00005, "ada__text_ioB"); + pragma Export (C, u00006, "ada__text_ioS"); + pragma Export (C, u00007, "ada__exceptionsB"); + pragma Export (C, u00008, "ada__exceptionsS"); + pragma Export (C, u00009, "gnatS"); + pragma Export (C, u00010, "gnat__heap_sort_aB"); + pragma Export (C, u00011, "gnat__heap_sort_aS"); + pragma Export (C, u00012, "systemS"); + pragma Export (C, u00013, "system__exception_tableB"); + pragma Export (C, u00014, "system__exception_tableS"); + pragma Export (C, u00015, "gnat__htableB"); + pragma Export (C, u00016, "gnat__htableS"); + pragma Export (C, u00017, "system__exceptionsS"); + pragma Export (C, u00018, "system__machine_state_operationsB"); + pragma Export (C, u00019, "system__machine_state_operationsS"); + pragma Export (C, u00020, "system__machine_codeS"); + pragma Export (C, u00021, "system__storage_elementsB"); + pragma Export (C, u00022, "system__storage_elementsS"); + pragma Export (C, u00023, "system__secondary_stackB"); + pragma Export (C, u00024, "system__secondary_stackS"); + pragma Export (C, u00025, "system__parametersB"); + pragma Export (C, u00026, "system__parametersS"); + pragma Export (C, u00027, "system__soft_linksB"); + pragma Export (C, u00028, "system__soft_linksS"); + pragma Export (C, u00029, "system__stack_checkingB"); + pragma Export (C, u00030, "system__stack_checkingS"); + pragma Export (C, u00031, "system__tracebackB"); + pragma Export (C, u00032, "system__tracebackS"); + pragma Export (C, u00033, "ada__streamsS"); + pragma Export (C, u00034, "ada__tagsB"); + pragma Export (C, u00035, "ada__tagsS"); + pragma Export (C, u00036, "system__string_opsB"); + pragma Export (C, u00037, "system__string_opsS"); + pragma Export (C, u00038, "interfacesS"); + pragma Export (C, u00039, "interfaces__c_streamsB"); + pragma Export (C, u00040, "interfaces__c_streamsS"); + pragma Export (C, u00041, "system__file_ioB"); + pragma Export (C, u00042, "system__file_ioS"); + pragma Export (C, u00043, "ada__finalizationB"); + pragma Export (C, u00044, "ada__finalizationS"); + pragma Export (C, u00045, "system__finalization_rootB"); + pragma Export (C, u00046, "system__finalization_rootS"); + pragma Export (C, u00047, "system__finalization_implementationB"); + pragma Export (C, u00048, "system__finalization_implementationS"); + pragma Export (C, u00049, "system__string_ops_concat_3B"); + pragma Export (C, u00050, "system__string_ops_concat_3S"); + pragma Export (C, u00051, "system__stream_attributesB"); + pragma Export (C, u00052, "system__stream_attributesS"); + pragma Export (C, u00053, "ada__io_exceptionsS"); + pragma Export (C, u00054, "system__unsigned_typesS"); + pragma Export (C, u00055, "system__file_control_blockS"); + pragma Export (C, u00056, "ada__finalization__list_controllerB"); + pragma Export (C, u00057, "ada__finalization__list_controllerS"); + + -- BEGIN ELABORATION ORDER + -- ada (spec) + -- gnat (spec) + -- gnat.heap_sort_a (spec) + -- gnat.heap_sort_a (body) + -- gnat.htable (spec) + -- gnat.htable (body) + -- interfaces (spec) + -- system (spec) + -- system.machine_code (spec) + -- system.parameters (spec) + -- system.parameters (body) + -- interfaces.c_streams (spec) + -- interfaces.c_streams (body) + -- system.standard_library (spec) + -- ada.exceptions (spec) + -- system.exception_table (spec) + -- system.exception_table (body) + -- ada.io_exceptions (spec) + -- system.exceptions (spec) + -- system.storage_elements (spec) + -- system.storage_elements (body) + -- system.machine_state_operations (spec) + -- system.machine_state_operations (body) + -- system.secondary_stack (spec) + -- system.stack_checking (spec) + -- system.soft_links (spec) + -- system.soft_links (body) + -- system.stack_checking (body) + -- system.secondary_stack (body) + -- system.standard_library (body) + -- system.string_ops (spec) + -- system.string_ops (body) + -- ada.tags (spec) + -- ada.tags (body) + -- ada.streams (spec) + -- system.finalization_root (spec) + -- system.finalization_root (body) + -- system.string_ops_concat_3 (spec) + -- system.string_ops_concat_3 (body) + -- system.traceback (spec) + -- system.traceback (body) + -- ada.exceptions (body) + -- system.unsigned_types (spec) + -- system.stream_attributes (spec) + -- system.stream_attributes (body) + -- system.finalization_implementation (spec) + -- system.finalization_implementation (body) + -- ada.finalization (spec) + -- ada.finalization (body) + -- ada.finalization.list_controller (spec) + -- ada.finalization.list_controller (body) + -- system.file_control_block (spec) + -- system.file_io (spec) + -- system.file_io (body) + -- ada.text_io (spec) + -- ada.text_io (body) + -- hello (body) + -- END ELABORATION ORDER + + end ada_main; + + -- The following source file name pragmas allow the generated file + -- names to be unique for different main programs. They are needed + -- since the package name will always be Ada_Main. + + pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads"); + pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb"); + + -- Generated package body for Ada_Main starts here + + package body ada_main is + + -- The actual finalization is performed by calling the + -- library routine in System.Standard_Library.Adafinal + + procedure Do_Finalize; + pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); + + ------------- + -- adainit -- + ------------- + + @findex adainit + procedure adainit is + + -- These booleans are set to True once the associated unit has + -- been elaborated. It is also used to avoid elaborating the + -- same unit twice. + + E040 : Boolean; + pragma Import (Ada, E040, "interfaces__c_streams_E"); + + E008 : Boolean; + pragma Import (Ada, E008, "ada__exceptions_E"); + + E014 : Boolean; + pragma Import (Ada, E014, "system__exception_table_E"); + + E053 : Boolean; + pragma Import (Ada, E053, "ada__io_exceptions_E"); + + E017 : Boolean; + pragma Import (Ada, E017, "system__exceptions_E"); + + E024 : Boolean; + pragma Import (Ada, E024, "system__secondary_stack_E"); + + E030 : Boolean; + pragma Import (Ada, E030, "system__stack_checking_E"); + + E028 : Boolean; + pragma Import (Ada, E028, "system__soft_links_E"); + + E035 : Boolean; + pragma Import (Ada, E035, "ada__tags_E"); + + E033 : Boolean; + pragma Import (Ada, E033, "ada__streams_E"); + + E046 : Boolean; + pragma Import (Ada, E046, "system__finalization_root_E"); + + E048 : Boolean; + pragma Import (Ada, E048, "system__finalization_implementation_E"); + + E044 : Boolean; + pragma Import (Ada, E044, "ada__finalization_E"); + + E057 : Boolean; + pragma Import (Ada, E057, "ada__finalization__list_controller_E"); + + E055 : Boolean; + pragma Import (Ada, E055, "system__file_control_block_E"); + + E042 : Boolean; + pragma Import (Ada, E042, "system__file_io_E"); + + E006 : Boolean; + pragma Import (Ada, E006, "ada__text_io_E"); + + -- Set_Globals is a library routine that stores away the + -- value of the indicated set of global values in global + -- variables within the library. + + procedure Set_Globals + (Main_Priority : Integer; + Time_Slice_Value : Integer; + WC_Encoding : Character; + Locking_Policy : Character; + Queuing_Policy : Character; + Task_Dispatching_Policy : Character; + Adafinal : System.Address; + Unreserve_All_Interrupts : Integer; + Exception_Tracebacks : Integer); + @findex __gnat_set_globals + pragma Import (C, Set_Globals, "__gnat_set_globals"); + + -- SDP_Table_Build is a library routine used to build the + -- exception tables. See unit Ada.Exceptions in files + -- a-except.ads/adb for full details of how zero cost + -- exception handling works. This procedure, the call to + -- it, and the two following tables are all omitted if the + -- build is in longjmp/setjump exception mode. + + @findex SDP_Table_Build + @findex Zero Cost Exceptions + procedure SDP_Table_Build + (SDP_Addresses : System.Address; + SDP_Count : Natural; + Elab_Addresses : System.Address; + Elab_Addr_Count : Natural); + pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); + + -- Table of Unit_Exception_Table addresses. Used for zero + -- cost exception handling to build the top level table. + + ST : aliased constant array (1 .. 23) of System.Address := ( + Hello'UET_Address, + Ada.Text_Io'UET_Address, + Ada.Exceptions'UET_Address, + Gnat.Heap_Sort_A'UET_Address, + System.Exception_Table'UET_Address, + System.Machine_State_Operations'UET_Address, + System.Secondary_Stack'UET_Address, + System.Parameters'UET_Address, + System.Soft_Links'UET_Address, + System.Stack_Checking'UET_Address, + System.Traceback'UET_Address, + Ada.Streams'UET_Address, + Ada.Tags'UET_Address, + System.String_Ops'UET_Address, + Interfaces.C_Streams'UET_Address, + System.File_Io'UET_Address, + Ada.Finalization'UET_Address, + System.Finalization_Root'UET_Address, + System.Finalization_Implementation'UET_Address, + System.String_Ops_Concat_3'UET_Address, + System.Stream_Attributes'UET_Address, + System.File_Control_Block'UET_Address, + Ada.Finalization.List_Controller'UET_Address); + + -- Table of addresses of elaboration routines. Used for + -- zero cost exception handling to make sure these + -- addresses are included in the top level procedure + -- address table. + + EA : aliased constant array (1 .. 23) of System.Address := ( + adainit'Code_Address, + Do_Finalize'Code_Address, + Ada.Exceptions'Elab_Spec'Address, + System.Exceptions'Elab_Spec'Address, + Interfaces.C_Streams'Elab_Spec'Address, + System.Exception_Table'Elab_Body'Address, + Ada.Io_Exceptions'Elab_Spec'Address, + System.Stack_Checking'Elab_Spec'Address, + System.Soft_Links'Elab_Body'Address, + System.Secondary_Stack'Elab_Body'Address, + Ada.Tags'Elab_Spec'Address, + Ada.Tags'Elab_Body'Address, + Ada.Streams'Elab_Spec'Address, + System.Finalization_Root'Elab_Spec'Address, + Ada.Exceptions'Elab_Body'Address, + System.Finalization_Implementation'Elab_Spec'Address, + System.Finalization_Implementation'Elab_Body'Address, + Ada.Finalization'Elab_Spec'Address, + Ada.Finalization.List_Controller'Elab_Spec'Address, + System.File_Control_Block'Elab_Spec'Address, + System.File_Io'Elab_Body'Address, + Ada.Text_Io'Elab_Spec'Address, + Ada.Text_Io'Elab_Body'Address); + + -- Start of processing for adainit + + begin + + -- Call SDP_Table_Build to build the top level procedure + -- table for zero cost exception handling (omitted in + -- longjmp/setjump mode). + + SDP_Table_Build (ST'Address, 23, EA'Address, 23); + + -- Call Set_Globals to record various information for + -- this partition. The values are derived by the binder + -- from information stored in the ali files by the compiler. + + @findex __gnat_set_globals + Set_Globals + (Main_Priority => -1, + -- Priority of main program, -1 if no pragma Priority used + + Time_Slice_Value => -1, + -- Time slice from Time_Slice pragma, -1 if none used + + WC_Encoding => 'b', + -- Wide_Character encoding used, default is brackets + + Locking_Policy => ' ', + -- Locking_Policy used, default of space means not + -- specified, otherwise it is the first character of + -- the policy name. + + Queuing_Policy => ' ', + -- Queuing_Policy used, default of space means not + -- specified, otherwise it is the first character of + -- the policy name. + + Task_Dispatching_Policy => ' ', + -- Task_Dispatching_Policy used, default of space means + -- not specified, otherwise first character of the + -- policy name. + + Adafinal => System.Null_Address, + -- Address of Adafinal routine, not used anymore + + Unreserve_All_Interrupts => 0, + -- Set true if pragma Unreserve_All_Interrupts was used + + Exception_Tracebacks => 0); + -- Indicates if exception tracebacks are enabled + + Elab_Final_Code := 1; + + -- Now we have the elaboration calls for all units in the partition. + -- The Elab_Spec and Elab_Body attributes generate references to the + -- implicit elaboration procedures generated by the compiler for + -- each unit that requires elaboration. + + if not E040 then + Interfaces.C_Streams'Elab_Spec; + end if; + E040 := True; + if not E008 then + Ada.Exceptions'Elab_Spec; + end if; + if not E014 then + System.Exception_Table'Elab_Body; + E014 := True; + end if; + if not E053 then + Ada.Io_Exceptions'Elab_Spec; + E053 := True; + end if; + if not E017 then + System.Exceptions'Elab_Spec; + E017 := True; + end if; + if not E030 then + System.Stack_Checking'Elab_Spec; + end if; + if not E028 then + System.Soft_Links'Elab_Body; + E028 := True; + end if; + E030 := True; + if not E024 then + System.Secondary_Stack'Elab_Body; + E024 := True; + end if; + if not E035 then + Ada.Tags'Elab_Spec; + end if; + if not E035 then + Ada.Tags'Elab_Body; + E035 := True; + end if; + if not E033 then + Ada.Streams'Elab_Spec; + E033 := True; + end if; + if not E046 then + System.Finalization_Root'Elab_Spec; + end if; + E046 := True; + if not E008 then + Ada.Exceptions'Elab_Body; + E008 := True; + end if; + if not E048 then + System.Finalization_Implementation'Elab_Spec; + end if; + if not E048 then + System.Finalization_Implementation'Elab_Body; + E048 := True; + end if; + if not E044 then + Ada.Finalization'Elab_Spec; + end if; + E044 := True; + if not E057 then + Ada.Finalization.List_Controller'Elab_Spec; + end if; + E057 := True; + if not E055 then + System.File_Control_Block'Elab_Spec; + E055 := True; + end if; + if not E042 then + System.File_Io'Elab_Body; + E042 := True; + end if; + if not E006 then + Ada.Text_Io'Elab_Spec; + end if; + if not E006 then + Ada.Text_Io'Elab_Body; + E006 := True; + end if; + + Elab_Final_Code := 0; + end adainit; + + -------------- + -- adafinal -- + -------------- + + @findex adafinal + procedure adafinal is + begin + Do_Finalize; + end adafinal; + + ---------- + -- main -- + ---------- + + -- main is actually a function, as in the ANSI C standard, + -- defined to return the exit status. The three parameters + -- are the argument count, argument values and environment + -- pointer. + + @findex Main Program + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + -- The initialize routine performs low level system + -- initialization using a standard library routine which + -- sets up signal handling and performs any other + -- required setup. The routine can be found in file + -- a-init.c. + + @findex __gnat_initialize + procedure initialize; + pragma Import (C, initialize, "__gnat_initialize"); + + -- The finalize routine performs low level system + -- finalization using a standard library routine. The + -- routine is found in file a-final.c and in the standard + -- distribution is a dummy routine that does nothing, so + -- really this is a hook for special user finalization. + + @findex __gnat_finalize + procedure finalize; + pragma Import (C, finalize, "__gnat_finalize"); + + -- We get to the main program of the partition by using + -- pragma Import because if we try to with the unit and + -- call it Ada style, then not only do we waste time + -- recompiling it, but also, we don't really know the right + -- switches (e.g. identifier character set) to be used + -- to compile it. + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, "_ada_hello"); + + -- Start of processing for main + + begin + -- Save global variables + + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + -- Call low level system initialization + + Initialize; + + -- Call our generated Ada initialization routine + + adainit; + + -- This is the point at which we want the debugger to get + -- control + + Break_Start; + + -- Now we call the main program of the partition + + Ada_Main_Program; + + -- Perform Ada finalization + + adafinal; + + -- Perform low level system finalization + + Finalize; + + -- Return the proper exit status + return (gnat_exit_status); + end; + + -- This section is entirely comments, so it has no effect on the + -- compilation of the Ada_Main package. It provides the list of + -- object files and linker options, as well as some standard + -- libraries needed for the link. The gnatlink utility parses + -- this b~hello.adb file to read these comment lines to generate + -- the appropriate command line arguments for the call to the + -- system linker. The BEGIN/END lines are used for sentinels for + -- this parsing operation. + + -- The exact file names will of course depend on the environment, + -- host/target and location of files on the host system. + + @findex Object file list + -- BEGIN Object file/option list + -- ./hello.o + -- -L./ + -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ + -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a + -- END Object file/option list + + end ada_main; + @end smallexample + + @noindent + The Ada code in the above example is exactly what is generated by the + binder. We have added comments to more clearly indicate the function + of each part of the generated @code{Ada_Main} package. + + The code is standard Ada in all respects, and can be processed by any + tools that handle Ada. In particular, it is possible to use the debugger + in Ada mode to debug the generated @code{Ada_Main} package. For example, + suppose that for reasons that you do not understand, your program is crashing + during elaboration of the body of @code{Ada.Text_IO}. To locate this bug, + you can place a breakpoint on the call: + + @smallexample @c ada + Ada.Text_Io'Elab_Body; + @end smallexample + + @noindent + and trace the elaboration routine for this package to find out where + the problem might be (more usually of course you would be debugging + elaboration code in your own application). + + + @node Elaboration Order Handling in GNAT + @appendix Elaboration Order Handling in GNAT + @cindex Order of elaboration + @cindex Elaboration control + + @menu + * Elaboration Code in Ada 95:: + * Checking the Elaboration Order in Ada 95:: + * Controlling the Elaboration Order in Ada 95:: + * Controlling Elaboration in GNAT - Internal Calls:: + * Controlling Elaboration in GNAT - External Calls:: + * Default Behavior in GNAT - Ensuring Safety:: + * Treatment of Pragma Elaborate:: + * Elaboration Issues for Library Tasks:: + * Mixing Elaboration Models:: + * What to Do If the Default Elaboration Behavior Fails:: + * Elaboration for Access-to-Subprogram Values:: + * Summary of Procedures for Elaboration Control:: + * Other Elaboration Order Considerations:: + @end menu + + @noindent + This chapter describes the handling of elaboration code in Ada 95 and + in GNAT, and discusses how the order of elaboration of program units can + be controlled in GNAT, either automatically or with explicit programming + features. + + @node Elaboration Code in Ada 95 + @section Elaboration Code in Ada 95 + + @noindent + Ada 95 provides rather general mechanisms for executing code at elaboration + time, that is to say before the main program starts executing. Such code arises + in three contexts: + + @table @asis + @item Initializers for variables. + Variables declared at the library level, in package specs or bodies, can + require initialization that is performed at elaboration time, as in: + @smallexample @c ada + @cartouche + Sqrt_Half : Float := Sqrt (0.5); + @end cartouche + @end smallexample + + @item Package initialization code + Code in a @code{BEGIN-END} section at the outer level of a package body is + executed as part of the package body elaboration code. + + @item Library level task allocators + Tasks that are declared using task allocators at the library level + start executing immediately and hence can execute at elaboration time. + @end table + + @noindent + Subprogram calls are possible in any of these contexts, which means that + any arbitrary part of the program may be executed as part of the elaboration + code. It is even possible to write a program which does all its work at + elaboration time, with a null main program, although stylistically this + would usually be considered an inappropriate way to structure + a program. + + An important concern arises in the context of elaboration code: + we have to be sure that it is executed in an appropriate order. What we + have is a series of elaboration code sections, potentially one section + for each unit in the program. It is important that these execute + in the correct order. Correctness here means that, taking the above + example of the declaration of @code{Sqrt_Half}, + if some other piece of + elaboration code references @code{Sqrt_Half}, + then it must run after the + section of elaboration code that contains the declaration of + @code{Sqrt_Half}. + + There would never be any order of elaboration problem if we made a rule + that whenever you @code{with} a unit, you must elaborate both the spec and body + of that unit before elaborating the unit doing the @code{with}'ing: + + @smallexample @c ada + @group + @cartouche + with Unit_1; + package Unit_2 is ... + @end cartouche + @end group + @end smallexample + + @noindent + would require that both the body and spec of @code{Unit_1} be elaborated + before the spec of @code{Unit_2}. However, a rule like that would be far too + restrictive. In particular, it would make it impossible to have routines + in separate packages that were mutually recursive. + + You might think that a clever enough compiler could look at the actual + elaboration code and determine an appropriate correct order of elaboration, + but in the general case, this is not possible. Consider the following + example. + + In the body of @code{Unit_1}, we have a procedure @code{Func_1} + that references + the variable @code{Sqrt_1}, which is declared in the elaboration code + of the body of @code{Unit_1}: + + @smallexample @c ada + @cartouche + Sqrt_1 : Float := Sqrt (0.1); + @end cartouche + @end smallexample + + @noindent + The elaboration code of the body of @code{Unit_1} also contains: + + @smallexample @c ada + @group + @cartouche + if expression_1 = 1 then + Q := Unit_2.Func_2; + end if; + @end cartouche + @end group + @end smallexample + + @noindent + @code{Unit_2} is exactly parallel, + it has a procedure @code{Func_2} that references + the variable @code{Sqrt_2}, which is declared in the elaboration code of + the body @code{Unit_2}: + + @smallexample @c ada + @cartouche + Sqrt_2 : Float := Sqrt (0.1); + @end cartouche + @end smallexample + + @noindent + The elaboration code of the body of @code{Unit_2} also contains: + + @smallexample @c ada + @group + @cartouche + if expression_2 = 2 then + Q := Unit_1.Func_1; + end if; + @end cartouche + @end group + @end smallexample + + @noindent + Now the question is, which of the following orders of elaboration is + acceptable: + + @smallexample + @group + Spec of Unit_1 + Spec of Unit_2 + Body of Unit_1 + Body of Unit_2 + @end group + @end smallexample + + @noindent + or + + @smallexample + @group + Spec of Unit_2 + Spec of Unit_1 + Body of Unit_2 + Body of Unit_1 + @end group + @end smallexample + + @noindent + If you carefully analyze the flow here, you will see that you cannot tell + at compile time the answer to this question. + If @code{expression_1} is not equal to 1, + and @code{expression_2} is not equal to 2, + then either order is acceptable, because neither of the function calls is + executed. If both tests evaluate to true, then neither order is acceptable + and in fact there is no correct order. + + If one of the two expressions is true, and the other is false, then one + of the above orders is correct, and the other is incorrect. For example, + if @code{expression_1} = 1 and @code{expression_2} /= 2, + then the call to @code{Func_2} + will occur, but not the call to @code{Func_1.} + This means that it is essential + to elaborate the body of @code{Unit_1} before + the body of @code{Unit_2}, so the first + order of elaboration is correct and the second is wrong. + + By making @code{expression_1} and @code{expression_2} + depend on input data, or perhaps + the time of day, we can make it impossible for the compiler or binder + to figure out which of these expressions will be true, and hence it + is impossible to guarantee a safe order of elaboration at run time. + + @node Checking the Elaboration Order in Ada 95 + @section Checking the Elaboration Order in Ada 95 + + @noindent + In some languages that involve the same kind of elaboration problems, + e.g. Java and C++, the programmer is expected to worry about these + ordering problems himself, and it is common to + write a program in which an incorrect elaboration order gives + surprising results, because it references variables before they + are initialized. + Ada 95 is designed to be a safe language, and a programmer-beware approach is + clearly not sufficient. Consequently, the language provides three lines + of defense: + + @table @asis + @item Standard rules + Some standard rules restrict the possible choice of elaboration + order. In particular, if you @code{with} a unit, then its spec is always + elaborated before the unit doing the @code{with}. Similarly, a parent + spec is always elaborated before the child spec, and finally + a spec is always elaborated before its corresponding body. + + @item Dynamic elaboration checks + @cindex Elaboration checks + @cindex Checks, elaboration + Dynamic checks are made at run time, so that if some entity is accessed + before it is elaborated (typically by means of a subprogram call) + then the exception (@code{Program_Error}) is raised. + + @item Elaboration control + Facilities are provided for the programmer to specify the desired order + of elaboration. + @end table + + Let's look at these facilities in more detail. First, the rules for + dynamic checking. One possible rule would be simply to say that the + exception is raised if you access a variable which has not yet been + elaborated. The trouble with this approach is that it could require + expensive checks on every variable reference. Instead Ada 95 has two + rules which are a little more restrictive, but easier to check, and + easier to state: + + @table @asis + @item Restrictions on calls + A subprogram can only be called at elaboration time if its body + has been elaborated. The rules for elaboration given above guarantee + that the spec of the subprogram has been elaborated before the + call, but not the body. If this rule is violated, then the + exception @code{Program_Error} is raised. + + @item Restrictions on instantiations + A generic unit can only be instantiated if the body of the generic + unit has been elaborated. Again, the rules for elaboration given above + guarantee that the spec of the generic unit has been elaborated + before the instantiation, but not the body. If this rule is + violated, then the exception @code{Program_Error} is raised. + @end table + + @noindent + The idea is that if the body has been elaborated, then any variables + it references must have been elaborated; by checking for the body being + elaborated we guarantee that none of its references causes any + trouble. As we noted above, this is a little too restrictive, because a + subprogram that has no non-local references in its body may in fact be safe + to call. However, it really would be unsafe to rely on this, because + it would mean that the caller was aware of details of the implementation + in the body. This goes against the basic tenets of Ada. + + A plausible implementation can be described as follows. + A Boolean variable is associated with each subprogram + and each generic unit. This variable is initialized to False, and is set to + True at the point body is elaborated. Every call or instantiation checks the + variable, and raises @code{Program_Error} if the variable is False. + + Note that one might think that it would be good enough to have one Boolean + variable for each package, but that would not deal with cases of trying + to call a body in the same package as the call + that has not been elaborated yet. + Of course a compiler may be able to do enough analysis to optimize away + some of the Boolean variables as unnecessary, and @code{GNAT} indeed + does such optimizations, but still the easiest conceptual model is to + think of there being one variable per subprogram. + + @node Controlling the Elaboration Order in Ada 95 + @section Controlling the Elaboration Order in Ada 95 + + @noindent + In the previous section we discussed the rules in Ada 95 which ensure + that @code{Program_Error} is raised if an incorrect elaboration order is + chosen. This prevents erroneous executions, but we need mechanisms to + specify a correct execution and avoid the exception altogether. + To achieve this, Ada 95 provides a number of features for controlling + the order of elaboration. We discuss these features in this section. + + First, there are several ways of indicating to the compiler that a given + unit has no elaboration problems: + + @table @asis + @item packages that do not require a body + In Ada 95, a library package that does not require a body does not permit + a body. This means that if we have a such a package, as in: + + @smallexample @c ada + @group + @cartouche + package Definitions is + generic + type m is new integer; + package Subp is + type a is array (1 .. 10) of m; + type b is array (1 .. 20) of m; + end Subp; + end Definitions; + @end cartouche + @end group + @end smallexample + + @noindent + A package that @code{with}'s @code{Definitions} may safely instantiate + @code{Definitions.Subp} because the compiler can determine that there + definitely is no package body to worry about in this case + + @item pragma Pure + @cindex pragma Pure + @findex Pure + Places sufficient restrictions on a unit to guarantee that + no call to any subprogram in the unit can result in an + elaboration problem. This means that the compiler does not need + to worry about the point of elaboration of such units, and in + particular, does not need to check any calls to any subprograms + in this unit. + + @item pragma Preelaborate + @findex Preelaborate + @cindex pragma Preelaborate + This pragma places slightly less stringent restrictions on a unit than + does pragma Pure, + but these restrictions are still sufficient to ensure that there + are no elaboration problems with any calls to the unit. + + @item pragma Elaborate_Body + @findex Elaborate_Body + @cindex pragma Elaborate_Body + This pragma requires that the body of a unit be elaborated immediately + after its spec. Suppose a unit @code{A} has such a pragma, + and unit @code{B} does + a @code{with} of unit @code{A}. Recall that the standard rules require + the spec of unit @code{A} + to be elaborated before the @code{with}'ing unit; given the pragma in + @code{A}, we also know that the body of @code{A} + will be elaborated before @code{B}, so + that calls to @code{A} are safe and do not need a check. + @end table + + @noindent + Note that, + unlike pragma @code{Pure} and pragma @code{Preelaborate}, + the use of + @code{Elaborate_Body} does not guarantee that the program is + free of elaboration problems, because it may not be possible + to satisfy the requested elaboration order. + Let's go back to the example with @code{Unit_1} and @code{Unit_2}. + If a programmer + marks @code{Unit_1} as @code{Elaborate_Body}, + and not @code{Unit_2,} then the order of + elaboration will be: + + @smallexample + @group + Spec of Unit_2 + Spec of Unit_1 + Body of Unit_1 + Body of Unit_2 + @end group + @end smallexample + + @noindent + Now that means that the call to @code{Func_1} in @code{Unit_2} + need not be checked, + it must be safe. But the call to @code{Func_2} in + @code{Unit_1} may still fail if + @code{Expression_1} is equal to 1, + and the programmer must still take + responsibility for this not being the case. + + If all units carry a pragma @code{Elaborate_Body}, then all problems are + eliminated, except for calls entirely within a body, which are + in any case fully under programmer control. However, using the pragma + everywhere is not always possible. + In particular, for our @code{Unit_1}/@code{Unit_2} example, if + we marked both of them as having pragma @code{Elaborate_Body}, then + clearly there would be no possible elaboration order. + + The above pragmas allow a server to guarantee safe use by clients, and + clearly this is the preferable approach. Consequently a good rule in + Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible, + and if this is not possible, + mark them as @code{Elaborate_Body} if possible. + As we have seen, there are situations where neither of these + three pragmas can be used. + So we also provide methods for clients to control the + order of elaboration of the servers on which they depend: + + @table @asis + @item pragma Elaborate (unit) + @findex Elaborate + @cindex pragma Elaborate + This pragma is placed in the context clause, after a @code{with} clause, + and it requires that the body of the named unit be elaborated before + the unit in which the pragma occurs. The idea is to use this pragma + if the current unit calls at elaboration time, directly or indirectly, + some subprogram in the named unit. + + @item pragma Elaborate_All (unit) + @findex Elaborate_All + @cindex pragma Elaborate_All + This is a stronger version of the Elaborate pragma. Consider the + following example: + + @smallexample + Unit A @code{with}'s unit B and calls B.Func in elab code + Unit B @code{with}'s unit C, and B.Func calls C.Func + @end smallexample + + @noindent + Now if we put a pragma @code{Elaborate (B)} + in unit @code{A}, this ensures that the + body of @code{B} is elaborated before the call, but not the + body of @code{C}, so + the call to @code{C.Func} could still cause @code{Program_Error} to + be raised. + + The effect of a pragma @code{Elaborate_All} is stronger, it requires + not only that the body of the named unit be elaborated before the + unit doing the @code{with}, but also the bodies of all units that the + named unit uses, following @code{with} links transitively. For example, + if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, + then it requires + not only that the body of @code{B} be elaborated before @code{A}, + but also the + body of @code{C}, because @code{B} @code{with}'s @code{C}. + @end table + + @noindent + We are now in a position to give a usage rule in Ada 95 for avoiding + elaboration problems, at least if dynamic dispatching and access to + subprogram values are not used. We will handle these cases separately + later. + + The rule is simple. If a unit has elaboration code that can directly or + indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate + a generic unit in a @code{with}'ed unit, + then if the @code{with}'ed unit does not have + pragma @code{Pure} or @code{Preelaborate}, then the client should have + a pragma @code{Elaborate_All} + for the @code{with}'ed unit. By following this rule a client is + assured that calls can be made without risk of an exception. + If this rule is not followed, then a program may be in one of four + states: + + @table @asis + @item No order exists + No order of elaboration exists which follows the rules, taking into + account any @code{Elaborate}, @code{Elaborate_All}, + or @code{Elaborate_Body} pragmas. In + this case, an Ada 95 compiler must diagnose the situation at bind + time, and refuse to build an executable program. + + @item One or more orders exist, all incorrect + One or more acceptable elaboration orders exists, and all of them + generate an elaboration order problem. In this case, the binder + can build an executable program, but @code{Program_Error} will be raised + when the program is run. + + @item Several orders exist, some right, some incorrect + One or more acceptable elaboration orders exists, and some of them + work, and some do not. The programmer has not controlled + the order of elaboration, so the binder may or may not pick one of + the correct orders, and the program may or may not raise an + exception when it is run. This is the worst case, because it means + that the program may fail when moved to another compiler, or even + another version of the same compiler. + + @item One or more orders exists, all correct + One ore more acceptable elaboration orders exist, and all of them + work. In this case the program runs successfully. This state of + affairs can be guaranteed by following the rule we gave above, but + may be true even if the rule is not followed. + @end table + + @noindent + Note that one additional advantage of following our Elaborate_All rule + is that the program continues to stay in the ideal (all orders OK) state + even if maintenance + changes some bodies of some subprograms. Conversely, if a program that does + not follow this rule happens to be safe at some point, this state of affairs + may deteriorate silently as a result of maintenance changes. + + You may have noticed that the above discussion did not mention + the use of @code{Elaborate_Body}. This was a deliberate omission. If you + @code{with} an @code{Elaborate_Body} unit, it still may be the case that + code in the body makes calls to some other unit, so it is still necessary + to use @code{Elaborate_All} on such units. + + @node Controlling Elaboration in GNAT - Internal Calls + @section Controlling Elaboration in GNAT - Internal Calls + + @noindent + In the case of internal calls, i.e. calls within a single package, the + programmer has full control over the order of elaboration, and it is up + to the programmer to elaborate declarations in an appropriate order. For + example writing: + + @smallexample @c ada + @group + @cartouche + function One return Float; + + Q : Float := One; + + function One return Float is + begin + return 1.0; + end One; + @end cartouche + @end group + @end smallexample + + @noindent + will obviously raise @code{Program_Error} at run time, because function + One will be called before its body is elaborated. In this case GNAT will + generate a warning that the call will raise @code{Program_Error}: + + @smallexample + @group + @cartouche + 1. procedure y is + 2. function One return Float; + 3. + 4. Q : Float := One; + | + >>> warning: cannot call "One" before body is elaborated + >>> warning: Program_Error will be raised at run time + + 5. + 6. function One return Float is + 7. begin + 8. return 1.0; + 9. end One; + 10. + 11. begin + 12. null; + 13. end; + @end cartouche + @end group + @end smallexample + + @noindent + Note that in this particular case, it is likely that the call is safe, because + the function @code{One} does not access any global variables. + Nevertheless in Ada 95, we do not want the validity of the check to depend on + the contents of the body (think about the separate compilation case), so this + is still wrong, as we discussed in the previous sections. + + The error is easily corrected by rearranging the declarations so that the + body of One appears before the declaration containing the call + (note that in Ada 95, + declarations can appear in any order, so there is no restriction that + would prevent this reordering, and if we write: + + @smallexample @c ada + @group + @cartouche + function One return Float; + + function One return Float is + begin + return 1.0; + end One; + + Q : Float := One; + @end cartouche + @end group + @end smallexample + + @noindent + then all is well, no warning is generated, and no + @code{Program_Error} exception + will be raised. + Things are more complicated when a chain of subprograms is executed: + + @smallexample @c ada + @group + @cartouche + function A return Integer; + function B return Integer; + function C return Integer; + + function B return Integer is begin return A; end; + function C return Integer is begin return B; end; + + X : Integer := C; + + function A return Integer is begin return 1; end; + @end cartouche + @end group + @end smallexample + + @noindent + Now the call to @code{C} + at elaboration time in the declaration of @code{X} is correct, because + the body of @code{C} is already elaborated, + and the call to @code{B} within the body of + @code{C} is correct, but the call + to @code{A} within the body of @code{B} is incorrect, because the body + of @code{A} has not been elaborated, so @code{Program_Error} + will be raised on the call to @code{A}. + In this case GNAT will generate a + warning that @code{Program_Error} may be + raised at the point of the call. Let's look at the warning: + + @smallexample + @group + @cartouche + 1. procedure x is + 2. function A return Integer; + 3. function B return Integer; + 4. function C return Integer; + 5. + 6. function B return Integer is begin return A; end; + | + >>> warning: call to "A" before body is elaborated may + raise Program_Error + >>> warning: "B" called at line 7 + >>> warning: "C" called at line 9 + + 7. function C return Integer is begin return B; end; + 8. + 9. X : Integer := C; + 10. + 11. function A return Integer is begin return 1; end; + 12. + 13. begin + 14. null; + 15. end; + @end cartouche + @end group + @end smallexample + + @noindent + Note that the message here says ``may raise'', instead of the direct case, + where the message says ``will be raised''. That's because whether + @code{A} is + actually called depends in general on run-time flow of control. + For example, if the body of @code{B} said + + @smallexample @c ada + @group + @cartouche + function B return Integer is + begin + if some-condition-depending-on-input-data then + return A; + else + return 1; + end if; + end B; + @end cartouche + @end group + @end smallexample + + @noindent + then we could not know until run time whether the incorrect call to A would + actually occur, so @code{Program_Error} might + or might not be raised. It is possible for a compiler to + do a better job of analyzing bodies, to + determine whether or not @code{Program_Error} + might be raised, but it certainly + couldn't do a perfect job (that would require solving the halting problem + and is provably impossible), and because this is a warning anyway, it does + not seem worth the effort to do the analysis. Cases in which it + would be relevant are rare. + + In practice, warnings of either of the forms given + above will usually correspond to + real errors, and should be examined carefully and eliminated. + In the rare case where a warning is bogus, it can be suppressed by any of + the following methods: + + @itemize @bullet + @item + Compile with the @option{-gnatws} switch set + + @item + Suppress @code{Elaboration_Check} for the called subprogram + + @item + Use pragma @code{Warnings_Off} to turn warnings off for the call + @end itemize + + @noindent + For the internal elaboration check case, + GNAT by default generates the + necessary run-time checks to ensure + that @code{Program_Error} is raised if any + call fails an elaboration check. Of course this can only happen if a + warning has been issued as described above. The use of pragma + @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress + some of these checks, meaning that it may be possible (but is not + guaranteed) for a program to be able to call a subprogram whose body + is not yet elaborated, without raising a @code{Program_Error} exception. + + @node Controlling Elaboration in GNAT - External Calls + @section Controlling Elaboration in GNAT - External Calls + + @noindent + The previous section discussed the case in which the execution of a + particular thread of elaboration code occurred entirely within a + single unit. This is the easy case to handle, because a programmer + has direct and total control over the order of elaboration, and + furthermore, checks need only be generated in cases which are rare + and which the compiler can easily detect. + The situation is more complex when separate compilation is taken into account. + Consider the following: + + @smallexample @c ada + @cartouche + @group + package Math is + function Sqrt (Arg : Float) return Float; + end Math; + + package body Math is + function Sqrt (Arg : Float) return Float is + begin + ... + end Sqrt; + end Math; + @end group + @group + with Math; + package Stuff is + X : Float := Math.Sqrt (0.5); + end Stuff; + + with Stuff; + procedure Main is + begin + ... + end Main; + @end group + @end cartouche + @end smallexample + + @noindent + where @code{Main} is the main program. When this program is executed, the + elaboration code must first be executed, and one of the jobs of the + binder is to determine the order in which the units of a program are + to be elaborated. In this case we have four units: the spec and body + of @code{Math}, + the spec of @code{Stuff} and the body of @code{Main}). + In what order should the four separate sections of elaboration code + be executed? + + There are some restrictions in the order of elaboration that the binder + can choose. In particular, if unit U has a @code{with} + for a package @code{X}, then you + are assured that the spec of @code{X} + is elaborated before U , but you are + not assured that the body of @code{X} + is elaborated before U. + This means that in the above case, the binder is allowed to choose the + order: + + @smallexample + spec of Math + spec of Stuff + body of Math + body of Main + @end smallexample + + @noindent + but that's not good, because now the call to @code{Math.Sqrt} + that happens during + the elaboration of the @code{Stuff} + spec happens before the body of @code{Math.Sqrt} is + elaborated, and hence causes @code{Program_Error} exception to be raised. + At first glance, one might say that the binder is misbehaving, because + obviously you want to elaborate the body of something you @code{with} + first, but + that is not a general rule that can be followed in all cases. Consider + + @smallexample @c ada + @group + @cartouche + package X is ... + + package Y is ... + + with X; + package body Y is ... + + with Y; + package body X is ... + @end cartouche + @end group + @end smallexample + + @noindent + This is a common arrangement, and, apart from the order of elaboration + problems that might arise in connection with elaboration code, this works fine. + A rule that says that you must first elaborate the body of anything you + @code{with} cannot work in this case: + the body of @code{X} @code{with}'s @code{Y}, + which means you would have to + elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, + which means + you have to elaborate the body of @code{X} first, but ... and we have a + loop that cannot be broken. + + It is true that the binder can in many cases guess an order of elaboration + that is unlikely to cause a @code{Program_Error} + exception to be raised, and it tries to do so (in the + above example of @code{Math/Stuff/Spec}, the GNAT binder will + by default + elaborate the body of @code{Math} right after its spec, so all will be well). + + However, a program that blindly relies on the binder to be helpful can + get into trouble, as we discussed in the previous sections, so + GNAT + provides a number of facilities for assisting the programmer in + developing programs that are robust with respect to elaboration order. + + @node Default Behavior in GNAT - Ensuring Safety + @section Default Behavior in GNAT - Ensuring Safety + + @noindent + The default behavior in GNAT ensures elaboration safety. In its + default mode GNAT implements the + rule we previously described as the right approach. Let's restate it: + + @itemize + @item + @emph{If a unit has elaboration code that can directly or indirectly make a + call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit + in a @code{with}'ed unit, then if the @code{with}'ed unit + does not have pragma @code{Pure} or + @code{Preelaborate}, then the client should have an + @code{Elaborate_All} for the @code{with}'ed unit.} + @end itemize + + @noindent + By following this rule a client is assured that calls and instantiations + can be made without risk of an exception. + + In this mode GNAT traces all calls that are potentially made from + elaboration code, and puts in any missing implicit @code{Elaborate_All} + pragmas. + The advantage of this approach is that no elaboration problems + are possible if the binder can find an elaboration order that is + consistent with these implicit @code{Elaborate_All} pragmas. The + disadvantage of this approach is that no such order may exist. + + If the binder does not generate any diagnostics, then it means that it + has found an elaboration order that is guaranteed to be safe. However, + the binder may still be relying on implicitly generated + @code{Elaborate_All} pragmas so portability to other compilers than + GNAT is not guaranteed. + + If it is important to guarantee portability, then the compilations should + use the + @option{-gnatwl} + (warn on elaboration problems) switch. This will cause warning messages + to be generated indicating the missing @code{Elaborate_All} pragmas. + Consider the following source program: + + @smallexample @c ada + @group + @cartouche + with k; + package j is + m : integer := k.r; + end; + @end cartouche + @end group + @end smallexample + + @noindent + where it is clear that there + should be a pragma @code{Elaborate_All} + for unit @code{k}. An implicit pragma will be generated, and it is + likely that the binder will be able to honor it. However, if you want + to port this program to some other Ada compiler than GNAT. + it is safer to include the pragma explicitly in the source. If this + unit is compiled with the + @option{-gnatwl} + switch, then the compiler outputs a warning: + + @smallexample + @group + @cartouche + 1. with k; + 2. package j is + 3. m : integer := k.r; + | + >>> warning: call to "r" may raise Program_Error + >>> warning: missing pragma Elaborate_All for "k" + + 4. end; + @end cartouche + @end group + @end smallexample + + @noindent + and these warnings can be used as a guide for supplying manually + the missing pragmas. It is usually a bad idea to use this warning + option during development. That's because it will warn you when + you need to put in a pragma, but cannot warn you when it is time + to take it out. So the use of pragma Elaborate_All may lead to + unnecessary dependencies and even false circularities. + + This default mode is more restrictive than the Ada Reference + Manual, and it is possible to construct programs which will compile + using the dynamic model described there, but will run into a + circularity using the safer static model we have described. + + Of course any Ada compiler must be able to operate in a mode + consistent with the requirements of the Ada Reference Manual, + and in particular must have the capability of implementing the + standard dynamic model of elaboration with run-time checks. + + In GNAT, this standard mode can be achieved either by the use of + the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake}) + command, or by the use of the configuration pragma: + + @smallexample @c ada + pragma Elaboration_Checks (RM); + @end smallexample + + @noindent + Either approach will cause the unit affected to be compiled using the + standard dynamic run-time elaboration checks described in the Ada + Reference Manual. The static model is generally preferable, since it + is clearly safer to rely on compile and link time checks rather than + run-time checks. However, in the case of legacy code, it may be + difficult to meet the requirements of the static model. This + issue is further discussed in + @ref{What to Do If the Default Elaboration Behavior Fails}. + + Note that the static model provides a strict subset of the allowed + behavior and programs of the Ada Reference Manual, so if you do + adhere to the static model and no circularities exist, + then you are assured that your program will + work using the dynamic model, providing that you remove any + pragma Elaborate statements from the source. + + @node Treatment of Pragma Elaborate + @section Treatment of Pragma Elaborate + @cindex Pragma Elaborate + + @noindent + The use of @code{pragma Elaborate} + should generally be avoided in Ada 95 programs. + The reason for this is that there is no guarantee that transitive calls + will be properly handled. Indeed at one point, this pragma was placed + in Annex J (Obsolescent Features), on the grounds that it is never useful. + + Now that's a bit restrictive. In practice, the case in which + @code{pragma Elaborate} is useful is when the caller knows that there + are no transitive calls, or that the called unit contains all necessary + transitive @code{pragma Elaborate} statements, and legacy code often + contains such uses. + + Strictly speaking the static mode in GNAT should ignore such pragmas, + since there is no assurance at compile time that the necessary safety + conditions are met. In practice, this would cause GNAT to be incompatible + with correctly written Ada 83 code that had all necessary + @code{pragma Elaborate} statements in place. Consequently, we made the + decision that GNAT in its default mode will believe that if it encounters + a @code{pragma Elaborate} then the programmer knows what they are doing, + and it will trust that no elaboration errors can occur. + + The result of this decision is two-fold. First to be safe using the + static mode, you should remove all @code{pragma Elaborate} statements. + Second, when fixing circularities in existing code, you can selectively + use @code{pragma Elaborate} statements to convince the static mode of + GNAT that it need not generate an implicit @code{pragma Elaborate_All} + statement. + + When using the static mode with @option{-gnatwl}, any use of + @code{pragma Elaborate} will generate a warning about possible + problems. + + @node Elaboration Issues for Library Tasks + @section Elaboration Issues for Library Tasks + @cindex Library tasks, elaboration issues + @cindex Elaboration of library tasks + + @noindent + In this section we examine special elaboration issues that arise for + programs that declare library level tasks. + + Generally the model of execution of an Ada program is that all units are + elaborated, and then execution of the program starts. However, the + declaration of library tasks definitely does not fit this model. The + reason for this is that library tasks start as soon as they are declared + (more precisely, as soon as the statement part of the enclosing package + body is reached), that is to say before elaboration + of the program is complete. This means that if such a task calls a + subprogram, or an entry in another task, the callee may or may not be + elaborated yet, and in the standard + Reference Manual model of dynamic elaboration checks, you can even + get timing dependent Program_Error exceptions, since there can be + a race between the elaboration code and the task code. + + The static model of elaboration in GNAT seeks to avoid all such + dynamic behavior, by being conservative, and the conservative + approach in this particular case is to assume that all the code + in a task body is potentially executed at elaboration time if + a task is declared at the library level. + + This can definitely result in unexpected circularities. Consider + the following example + + @smallexample @c ada + package Decls is + task Lib_Task is + entry Start; + end Lib_Task; + + type My_Int is new Integer; + + function Ident (M : My_Int) return My_Int; + end Decls; + + with Utils; + package body Decls is + task body Lib_Task is + begin + accept Start; + Utils.Put_Val (2); + end Lib_Task; + + function Ident (M : My_Int) return My_Int is + begin + return M; + end Ident; + end Decls; + + with Decls; + package Utils is + procedure Put_Val (Arg : Decls.My_Int); + end Utils; + + with Text_IO; + package body Utils is + procedure Put_Val (Arg : Decls.My_Int) is + begin + Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); + end Put_Val; + end Utils; + + with Decls; + procedure Main is + begin + Decls.Lib_Task.Start; + end; + @end smallexample + + @noindent + If the above example is compiled in the default static elaboration + mode, then a circularity occurs. The circularity comes from the call + @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since + this call occurs in elaboration code, we need an implicit pragma + @code{Elaborate_All} for @code{Utils}. This means that not only must + the spec and body of @code{Utils} be elaborated before the body + of @code{Decls}, but also the spec and body of any unit that is + @code{with'ed} by the body of @code{Utils} must also be elaborated before + the body of @code{Decls}. This is the transitive implication of + pragma @code{Elaborate_All} and it makes sense, because in general + the body of @code{Put_Val} might have a call to something in a + @code{with'ed} unit. + + In this case, the body of Utils (actually its spec) @code{with's} + @code{Decls}. Unfortunately this means that the body of @code{Decls} + must be elaborated before itself, in case there is a call from the + body of @code{Utils}. + + Here is the exact chain of events we are worrying about: + + @enumerate + @item + In the body of @code{Decls} a call is made from within the body of a library + task to a subprogram in the package @code{Utils}. Since this call may + occur at elaboration time (given that the task is activated at elaboration + time), we have to assume the worst, i.e. that the + call does happen at elaboration time. + + @item + This means that the body and spec of @code{Util} must be elaborated before + the body of @code{Decls} so that this call does not cause an access before + elaboration. + + @item + Within the body of @code{Util}, specifically within the body of + @code{Util.Put_Val} there may be calls to any unit @code{with}'ed + by this package. + + @item + One such @code{with}'ed package is package @code{Decls}, so there + might be a call to a subprogram in @code{Decls} in @code{Put_Val}. + In fact there is such a call in this example, but we would have to + assume that there was such a call even if it were not there, since + we are not supposed to write the body of @code{Decls} knowing what + is in the body of @code{Utils}; certainly in the case of the + static elaboration model, the compiler does not know what is in + other bodies and must assume the worst. + + @item + This means that the spec and body of @code{Decls} must also be + elaborated before we elaborate the unit containing the call, but + that unit is @code{Decls}! This means that the body of @code{Decls} + must be elaborated before itself, and that's a circularity. + @end enumerate + + @noindent + Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in + the body of @code{Decls} you will get a true Ada Reference Manual + circularity that makes the program illegal. + + In practice, we have found that problems with the static model of + elaboration in existing code often arise from library tasks, so + we must address this particular situation. + + Note that if we compile and run the program above, using the dynamic model of + elaboration (that is to say use the @option{-gnatE} switch), + then it compiles, binds, + links, and runs, printing the expected result of 2. Therefore in some sense + the circularity here is only apparent, and we need to capture + the properties of this program that distinguish it from other library-level + tasks that have real elaboration problems. + + We have four possible answers to this question: + + @itemize @bullet + + @item + Use the dynamic model of elaboration. + + If we use the @option{-gnatE} switch, then as noted above, the program works. + Why is this? If we examine the task body, it is apparent that the task cannot + proceed past the + @code{accept} statement until after elaboration has been completed, because + the corresponding entry call comes from the main program, not earlier. + This is why the dynamic model works here. But that's really giving + up on a precise analysis, and we prefer to take this approach only if we cannot + solve the + problem in any other manner. So let us examine two ways to reorganize + the program to avoid the potential elaboration problem. + + @item + Split library tasks into separate packages. + + Write separate packages, so that library tasks are isolated from + other declarations as much as possible. Let us look at a variation on + the above program. + + @smallexample @c ada + package Decls1 is + task Lib_Task is + entry Start; + end Lib_Task; + end Decls1; + + with Utils; + package body Decls1 is + task body Lib_Task is + begin + accept Start; + Utils.Put_Val (2); + end Lib_Task; + end Decls1; + + package Decls2 is + type My_Int is new Integer; + function Ident (M : My_Int) return My_Int; + end Decls2; + + with Utils; + package body Decls2 is + function Ident (M : My_Int) return My_Int is + begin + return M; + end Ident; + end Decls2; + + with Decls2; + package Utils is + procedure Put_Val (Arg : Decls2.My_Int); + end Utils; + + with Text_IO; + package body Utils is + procedure Put_Val (Arg : Decls2.My_Int) is + begin + Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); + end Put_Val; + end Utils; + + with Decls1; + procedure Main is + begin + Decls1.Lib_Task.Start; + end; + @end smallexample + + @noindent + All we have done is to split @code{Decls} into two packages, one + containing the library task, and one containing everything else. Now + there is no cycle, and the program compiles, binds, links and executes + using the default static model of elaboration. + + @item + Declare separate task types. + + A significant part of the problem arises because of the use of the + single task declaration form. This means that the elaboration of + the task type, and the elaboration of the task itself (i.e. the + creation of the task) happen at the same time. A good rule + of style in Ada 95 is to always create explicit task types. By + following the additional step of placing task objects in separate + packages from the task type declaration, many elaboration problems + are avoided. Here is another modified example of the example program: + + @smallexample @c ada + package Decls is + task type Lib_Task_Type is + entry Start; + end Lib_Task_Type; + + type My_Int is new Integer; + + function Ident (M : My_Int) return My_Int; + end Decls; + + with Utils; + package body Decls is + task body Lib_Task_Type is + begin + accept Start; + Utils.Put_Val (2); + end Lib_Task_Type; + + function Ident (M : My_Int) return My_Int is + begin + return M; + end Ident; + end Decls; + + with Decls; + package Utils is + procedure Put_Val (Arg : Decls.My_Int); + end Utils; + + with Text_IO; + package body Utils is + procedure Put_Val (Arg : Decls.My_Int) is + begin + Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); + end Put_Val; + end Utils; + + with Decls; + package Declst is + Lib_Task : Decls.Lib_Task_Type; + end Declst; + + with Declst; + procedure Main is + begin + Declst.Lib_Task.Start; + end; + @end smallexample + + @noindent + What we have done here is to replace the @code{task} declaration in + package @code{Decls} with a @code{task type} declaration. Then we + introduce a separate package @code{Declst} to contain the actual + task object. This separates the elaboration issues for + the @code{task type} + declaration, which causes no trouble, from the elaboration issues + of the task object, which is also unproblematic, since it is now independent + of the elaboration of @code{Utils}. + This separation of concerns also corresponds to + a generally sound engineering principle of separating declarations + from instances. This version of the program also compiles, binds, links, + and executes, generating the expected output. + + @item + Use No_Entry_Calls_In_Elaboration_Code restriction. + @cindex No_Entry_Calls_In_Elaboration_Code + + The previous two approaches described how a program can be restructured + to avoid the special problems caused by library task bodies. in practice, + however, such restructuring may be difficult to apply to existing legacy code, + so we must consider solutions that do not require massive rewriting. + + Let us consider more carefully why our original sample program works + under the dynamic model of elaboration. The reason is that the code + in the task body blocks immediately on the @code{accept} + statement. Now of course there is nothing to prohibit elaboration + code from making entry calls (for example from another library level task), + so we cannot tell in isolation that + the task will not execute the accept statement during elaboration. + + However, in practice it is very unusual to see elaboration code + make any entry calls, and the pattern of tasks starting + at elaboration time and then immediately blocking on @code{accept} or + @code{select} statements is very common. What this means is that + the compiler is being too pessimistic when it analyzes the + whole package body as though it might be executed at elaboration + time. + + If we know that the elaboration code contains no entry calls, (a very safe + assumption most of the time, that could almost be made the default + behavior), then we can compile all units of the program under control + of the following configuration pragma: + + @smallexample + pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); + @end smallexample + + @noindent + This pragma can be placed in the @file{gnat.adc} file in the usual + manner. If we take our original unmodified program and compile it + in the presence of a @file{gnat.adc} containing the above pragma, + then once again, we can compile, bind, link, and execute, obtaining + the expected result. In the presence of this pragma, the compiler does + not trace calls in a task body, that appear after the first @code{accept} + or @code{select} statement, and therefore does not report a potential + circularity in the original program. + + The compiler will check to the extent it can that the above + restriction is not violated, but it is not always possible to do a + complete check at compile time, so it is important to use this + pragma only if the stated restriction is in fact met, that is to say + no task receives an entry call before elaboration of all units is completed. + + @end itemize + + @node Mixing Elaboration Models + @section Mixing Elaboration Models + @noindent + So far, we have assumed that the entire program is either compiled + using the dynamic model or static model, ensuring consistency. It + is possible to mix the two models, but rules have to be followed + if this mixing is done to ensure that elaboration checks are not + omitted. + + The basic rule is that @emph{a unit compiled with the static model cannot + be @code{with'ed} by a unit compiled with the dynamic model}. The + reason for this is that in the static model, a unit assumes that + its clients guarantee to use (the equivalent of) pragma + @code{Elaborate_All} so that no elaboration checks are required + in inner subprograms, and this assumption is violated if the + client is compiled with dynamic checks. + + The precise rule is as follows. A unit that is compiled with dynamic + checks can only @code{with} a unit that meets at least one of the + following criteria: + + @itemize @bullet + + @item + The @code{with'ed} unit is itself compiled with dynamic elaboration + checks (that is with the @option{-gnatE} switch. + + @item + The @code{with'ed} unit is an internal GNAT implementation unit from + the System, Interfaces, Ada, or GNAT hierarchies. + + @item + The @code{with'ed} unit has pragma Preelaborate or pragma Pure. + + @item + The @code{with'ing} unit (that is the client) has an explicit pragma + @code{Elaborate_All} for the @code{with'ed} unit. + + @end itemize + + @noindent + If this rule is violated, that is if a unit with dynamic elaboration + checks @code{with's} a unit that does not meet one of the above four + criteria, then the binder (@code{gnatbind}) will issue a warning + similar to that in the following example: + + @smallexample + warning: "x.ads" has dynamic elaboration checks and with's + warning: "y.ads" which has static elaboration checks + @end smallexample + + @noindent + These warnings indicate that the rule has been violated, and that as a result + elaboration checks may be missed in the resulting executable file. + This warning may be suppressed using the @option{-ws} binder switch + in the usual manner. + + One useful application of this mixing rule is in the case of a subsystem + which does not itself @code{with} units from the remainder of the + application. In this case, the entire subsystem can be compiled with + dynamic checks to resolve a circularity in the subsystem, while + allowing the main application that uses this subsystem to be compiled + using the more reliable default static model. + + @node What to Do If the Default Elaboration Behavior Fails + @section What to Do If the Default Elaboration Behavior Fails + + @noindent + If the binder cannot find an acceptable order, it outputs detailed + diagnostics. For example: + @smallexample + @group + @iftex + @leftskip=0cm + @end iftex + error: elaboration circularity detected + info: "proc (body)" must be elaborated before "pack (body)" + info: reason: Elaborate_All probably needed in unit "pack (body)" + info: recompile "pack (body)" with -gnatwl + info: for full details + info: "proc (body)" + info: is needed by its spec: + info: "proc (spec)" + info: which is withed by: + info: "pack (body)" + info: "pack (body)" must be elaborated before "proc (body)" + info: reason: pragma Elaborate in unit "proc (body)" + @end group + + @end smallexample + + @noindent + In this case we have a cycle that the binder cannot break. On the one + hand, there is an explicit pragma Elaborate in @code{proc} for + @code{pack}. This means that the body of @code{pack} must be elaborated + before the body of @code{proc}. On the other hand, there is elaboration + code in @code{pack} that calls a subprogram in @code{proc}. This means + that for maximum safety, there should really be a pragma + Elaborate_All in @code{pack} for @code{proc} which would require that + the body of @code{proc} be elaborated before the body of + @code{pack}. Clearly both requirements cannot be satisfied. + Faced with a circularity of this kind, you have three different options. + + @table @asis + @item Fix the program + The most desirable option from the point of view of long-term maintenance + is to rearrange the program so that the elaboration problems are avoided. + One useful technique is to place the elaboration code into separate + child packages. Another is to move some of the initialization code to + explicitly called subprograms, where the program controls the order + of initialization explicitly. Although this is the most desirable option, + it may be impractical and involve too much modification, especially in + the case of complex legacy code. + + @item Perform dynamic checks + If the compilations are done using the + @option{-gnatE} + (dynamic elaboration check) switch, then GNAT behaves in + a quite different manner. Dynamic checks are generated for all calls + that could possibly result in raising an exception. With this switch, + the compiler does not generate implicit @code{Elaborate_All} pragmas. + The behavior then is exactly as specified in the Ada 95 Reference Manual. + The binder will generate an executable program that may or may not + raise @code{Program_Error}, and then it is the programmer's job to ensure + that it does not raise an exception. Note that it is important to + compile all units with the switch, it cannot be used selectively. + + @item Suppress checks + The drawback of dynamic checks is that they generate a + significant overhead at run time, both in space and time. If you + are absolutely sure that your program cannot raise any elaboration + exceptions, and you still want to use the dynamic elaboration model, + then you can use the configuration pragma + @code{Suppress (Elaboration_Check)} to suppress all such checks. For + example this pragma could be placed in the @file{gnat.adc} file. + + @item Suppress checks selectively + When you know that certain calls in elaboration code cannot possibly + lead to an elaboration error, and the binder nevertheless generates warnings + on those calls and inserts Elaborate_All pragmas that lead to elaboration + circularities, it is possible to remove those warnings locally and obtain + a program that will bind. Clearly this can be unsafe, and it is the + responsibility of the programmer to make sure that the resulting program has + no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can + be used with different granularity to suppress warnings and break + elaboration circularities: + + @itemize @bullet + @item + Place the pragma that names the called subprogram in the declarative part + that contains the call. + + @item + Place the pragma in the declarative part, without naming an entity. This + disables warnings on all calls in the corresponding declarative region. + + @item + Place the pragma in the package spec that declares the called subprogram, + and name the subprogram. This disables warnings on all elaboration calls to + that subprogram. + + @item + Place the pragma in the package spec that declares the called subprogram, + without naming any entity. This disables warnings on all elaboration calls to + all subprograms declared in this spec. + + @item Use Pragma Elaborate + As previously described in section @xref{Treatment of Pragma Elaborate}, + GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly + that no elaboration checks are required on calls to the designated unit. + There may be cases in which the caller knows that no transitive calls + can occur, so that a @code{pragma Elaborate} will be sufficient in a + case where @code{pragma Elaborate_All} would cause a circularity. + @end itemize + + @noindent + These five cases are listed in order of decreasing safety, and therefore + require increasing programmer care in their application. Consider the + following program: + + @smallexample @c adanocomment + package Pack1 is + function F1 return Integer; + X1 : Integer; + end Pack1; + + package Pack2 is + function F2 return Integer; + function Pure (x : integer) return integer; + -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) + -- pragma Suppress (Elaboration_Check); -- (4) + end Pack2; + + with Pack2; + package body Pack1 is + function F1 return Integer is + begin + return 100; + end F1; + Val : integer := Pack2.Pure (11); -- Elab. call (1) + begin + declare + -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) + -- pragma Suppress(Elaboration_Check); -- (2) + begin + X1 := Pack2.F2 + 1; -- Elab. call (2) + end; + end Pack1; + + with Pack1; + package body Pack2 is + function F2 return Integer is + begin + return Pack1.F1; + end F2; + function Pure (x : integer) return integer is + begin + return x ** 3 - 3 * x; + end; + end Pack2; + + with Pack1, Ada.Text_IO; + procedure Proc3 is + begin + Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 + end Proc3; + @end smallexample + In the absence of any pragmas, an attempt to bind this program produces + the following diagnostics: + @smallexample + @group + @iftex + @leftskip=.5cm + @end iftex + error: elaboration circularity detected + info: "pack1 (body)" must be elaborated before "pack1 (body)" + info: reason: Elaborate_All probably needed in unit "pack1 (body)" + info: recompile "pack1 (body)" with -gnatwl for full details + info: "pack1 (body)" + info: must be elaborated along with its spec: + info: "pack1 (spec)" + info: which is withed by: + info: "pack2 (body)" + info: which must be elaborated along with its spec: + info: "pack2 (spec)" + info: which is withed by: + info: "pack1 (body)" + @end group + @end smallexample + The sources of the circularity are the two calls to @code{Pack2.Pure} and + @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to + F2 is safe, even though F2 calls F1, because the call appears after the + elaboration of the body of F1. Therefore the pragma (1) is safe, and will + remove the warning on the call. It is also possible to use pragma (2) + because there are no other potentially unsafe calls in the block. + + @noindent + The call to @code{Pure} is safe because this function does not depend on the + state of @code{Pack2}. Therefore any call to this function is safe, and it + is correct to place pragma (3) in the corresponding package spec. + + @noindent + Finally, we could place pragma (4) in the spec of @code{Pack2} to disable + warnings on all calls to functions declared therein. Note that this is not + necessarily safe, and requires more detailed examination of the subprogram + bodies involved. In particular, a call to @code{F2} requires that @code{F1} + be already elaborated. + @end table + + @noindent + It is hard to generalize on which of these four approaches should be + taken. Obviously if it is possible to fix the program so that the default + treatment works, this is preferable, but this may not always be practical. + It is certainly simple enough to use + @option{-gnatE} + but the danger in this case is that, even if the GNAT binder + finds a correct elaboration order, it may not always do so, + and certainly a binder from another Ada compiler might not. A + combination of testing and analysis (for which the warnings generated + with the + @option{-gnatwl} + switch can be useful) must be used to ensure that the program is free + of errors. One switch that is useful in this testing is the + @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^} + switch for + @code{gnatbind}. + Normally the binder tries to find an order that has the best chance of + of avoiding elaboration problems. With this switch, the binder + plays a devil's advocate role, and tries to choose the order that + has the best chance of failing. If your program works even with this + switch, then it has a better chance of being error free, but this is still + not a guarantee. + + For an example of this approach in action, consider the C-tests (executable + tests) from the ACVC suite. If these are compiled and run with the default + treatment, then all but one of them succeed without generating any error + diagnostics from the binder. However, there is one test that fails, and + this is not surprising, because the whole point of this test is to ensure + that the compiler can handle cases where it is impossible to determine + a correct order statically, and it checks that an exception is indeed + raised at run time. + + This one test must be compiled and run using the + @option{-gnatE} + switch, and then it passes. Alternatively, the entire suite can + be run using this switch. It is never wrong to run with the dynamic + elaboration switch if your code is correct, and we assume that the + C-tests are indeed correct (it is less efficient, but efficiency is + not a factor in running the ACVC tests.) + + @node Elaboration for Access-to-Subprogram Values + @section Elaboration for Access-to-Subprogram Values + @cindex Access-to-subprogram + + @noindent + The introduction of access-to-subprogram types in Ada 95 complicates + the handling of elaboration. The trouble is that it becomes + impossible to tell at compile time which procedure + is being called. This means that it is not possible for the binder + to analyze the elaboration requirements in this case. + + If at the point at which the access value is created + (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}), + the body of the subprogram is + known to have been elaborated, then the access value is safe, and its use + does not require a check. This may be achieved by appropriate arrangement + of the order of declarations if the subprogram is in the current unit, + or, if the subprogram is in another unit, by using pragma + @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body} + on the referenced unit. + + If the referenced body is not known to have been elaborated at the point + the access value is created, then any use of the access value must do a + dynamic check, and this dynamic check will fail and raise a + @code{Program_Error} exception if the body has not been elaborated yet. + GNAT will generate the necessary checks, and in addition, if the + @option{-gnatwl} + switch is set, will generate warnings that such checks are required. + + The use of dynamic dispatching for tagged types similarly generates + a requirement for dynamic checks, and premature calls to any primitive + operation of a tagged type before the body of the operation has been + elaborated, will result in the raising of @code{Program_Error}. + + @node Summary of Procedures for Elaboration Control + @section Summary of Procedures for Elaboration Control + @cindex Elaboration control + + @noindent + First, compile your program with the default options, using none of + the special elaboration control switches. If the binder successfully + binds your program, then you can be confident that, apart from issues + raised by the use of access-to-subprogram types and dynamic dispatching, + the program is free of elaboration errors. If it is important that the + program be portable, then use the + @option{-gnatwl} + switch to generate warnings about missing @code{Elaborate_All} + pragmas, and supply the missing pragmas. + + If the program fails to bind using the default static elaboration + handling, then you can fix the program to eliminate the binder + message, or recompile the entire program with the + @option{-gnatE} switch to generate dynamic elaboration checks, + and, if you are sure there really are no elaboration problems, + use a global pragma @code{Suppress (Elaboration_Check)}. + + @node Other Elaboration Order Considerations + @section Other Elaboration Order Considerations + @noindent + This section has been entirely concerned with the issue of finding a valid + elaboration order, as defined by the Ada Reference Manual. In a case + where several elaboration orders are valid, the task is to find one + of the possible valid elaboration orders (and the static model in GNAT + will ensure that this is achieved). + + The purpose of the elaboration rules in the Ada Reference Manual is to + make sure that no entity is accessed before it has been elaborated. For + a subprogram, this means that the spec and body must have been elaborated + before the subprogram is called. For an object, this means that the object + must have been elaborated before its value is read or written. A violation + of either of these two requirements is an access before elaboration order, + and this section has been all about avoiding such errors. + + In the case where more than one order of elaboration is possible, in the + sense that access before elaboration errors are avoided, then any one of + the orders is ``correct'' in the sense that it meets the requirements of + the Ada Reference Manual, and no such error occurs. + + However, it may be the case for a given program, that there are + constraints on the order of elaboration that come not from consideration + of avoiding elaboration errors, but rather from extra-lingual logic + requirements. Consider this example: + + @smallexample @c ada + with Init_Constants; + package Constants is + X : Integer := 0; + Y : Integer := 0; + end Constants; + + package Init_Constants is + procedure P; -- require a body + end Init_Constants; + + with Constants; + package body Init_Constants is + procedure P is begin null; end; + begin + Constants.X := 3; + Constants.Y := 4; + end Init_Constants; + + with Constants; + package Calc is + Z : Integer := Constants.X + Constants.Y; + end Calc; + + with Calc; + with Text_IO; use Text_IO; + procedure Main is + begin + Put_Line (Calc.Z'Img); + end Main; + @end smallexample + + @noindent + In this example, there is more than one valid order of elaboration. For + example both the following are correct orders: + + @smallexample + Init_Constants spec + Constants spec + Calc spec + Init_Constants body + Main body + + and + + Init_Constants spec + Init_Constants body + Constants spec + Calc spec + Main body + @end smallexample + + @noindent + There is no language rule to prefer one or the other, both are correct + from an order of elaboration point of view. But the programmatic effects + of the two orders are very different. In the first, the elaboration routine + of @code{Calc} initializes @code{Z} to zero, and then the main program + runs with this value of zero. But in the second order, the elaboration + routine of @code{Calc} runs after the body of Init_Constants has set + @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} + runs. + + One could perhaps by applying pretty clever non-artificial intelligence + to the situation guess that it is more likely that the second order of + elaboration is the one desired, but there is no formal linguistic reason + to prefer one over the other. In fact in this particular case, GNAT will + prefer the second order, because of the rule that bodies are elaborated + as soon as possible, but it's just luck that this is what was wanted + (if indeed the second order was preferred). + + If the program cares about the order of elaboration routines in a case like + this, it is important to specify the order required. In this particular + case, that could have been achieved by adding to the spec of Calc: + + @smallexample @c ada + pragma Elaborate_All (Constants); + @end smallexample + + @noindent + which requires that the body (if any) and spec of @code{Constants}, + as well as the body and spec of any unit @code{with}'ed by + @code{Constants} be elaborated before @code{Calc} is elaborated. + + Clearly no automatic method can always guess which alternative you require, + and if you are working with legacy code that had constraints of this kind + which were not properly specified by adding @code{Elaborate} or + @code{Elaborate_All} pragmas, then indeed it is possible that two different + compilers can choose different orders. + + The @code{gnatbind} + @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking + out problems. This switch causes bodies to be elaborated as late as possible + instead of as early as possible. In the example above, it would have forced + the choice of the first elaboration order. If you get different results + when using this switch, and particularly if one set of results is right, + and one is wrong as far as you are concerned, it shows that you have some + missing @code{Elaborate} pragmas. For the example above, we have the + following output: + + @smallexample + gnatmake -f -q main + main + 7 + gnatmake -f -q main -bargs -p + main + 0 + @end smallexample + + @noindent + It is of course quite unlikely that both these results are correct, so + it is up to you in a case like this to investigate the source of the + difference, by looking at the two elaboration orders that are chosen, + and figuring out which is correct, and then adding the necessary + @code{Elaborate_All} pragmas to ensure the desired order. + + + @node Inline Assembler + @appendix Inline Assembler + + @noindent + If you need to write low-level software that interacts directly + with the hardware, Ada provides two ways to incorporate assembly + language code into your program. First, you can import and invoke + external routines written in assembly language, an Ada feature fully + supported by GNAT. However, for small sections of code it may be simpler + or more efficient to include assembly language statements directly + in your Ada source program, using the facilities of the implementation-defined + package @code{System.Machine_Code}, which incorporates the gcc + Inline Assembler. The Inline Assembler approach offers a number of advantages, + including the following: + + @itemize @bullet + @item No need to use non-Ada tools + @item Consistent interface over different targets + @item Automatic usage of the proper calling conventions + @item Access to Ada constants and variables + @item Definition of intrinsic routines + @item Possibility of inlining a subprogram comprising assembler code + @item Code optimizer can take Inline Assembler code into account + @end itemize + + This chapter presents a series of examples to show you how to use + the Inline Assembler. Although it focuses on the Intel x86, + the general approach applies also to other processors. + It is assumed that you are familiar with Ada + and with assembly language programming. + + @menu + * Basic Assembler Syntax:: + * A Simple Example of Inline Assembler:: + * Output Variables in Inline Assembler:: + * Input Variables in Inline Assembler:: + * Inlining Inline Assembler Code:: + * Other Asm Functionality:: + * A Complete Example:: + @end menu + + @c --------------------------------------------------------------------------- + @node Basic Assembler Syntax + @section Basic Assembler Syntax + + @noindent + The assembler used by GNAT and gcc is based not on the Intel assembly + language, but rather on a language that descends from the AT&T Unix + assembler @emph{as} (and which is often referred to as ``AT&T syntax''). + The following table summarizes the main features of @emph{as} syntax + and points out the differences from the Intel conventions. + See the gcc @emph{as} and @emph{gas} (an @emph{as} macro + pre-processor) documentation for further information. + + @table @asis + @item Register names + gcc / @emph{as}: Prefix with ``%''; for example @code{%eax} + @* + Intel: No extra punctuation; for example @code{eax} + + @item Immediate operand + gcc / @emph{as}: Prefix with ``$''; for example @code{$4} + @* + Intel: No extra punctuation; for example @code{4} + + @item Address + gcc / @emph{as}: Prefix with ``$''; for example @code{$loc} + @* + Intel: No extra punctuation; for example @code{loc} + + @item Memory contents + gcc / @emph{as}: No extra punctuation; for example @code{loc} + @* + Intel: Square brackets; for example @code{[loc]} + + @item Register contents + gcc / @emph{as}: Parentheses; for example @code{(%eax)} + @* + Intel: Square brackets; for example @code{[eax]} + + @item Hexadecimal numbers + gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} + @* + Intel: Trailing ``h''; for example @code{A0h} + + @item Operand size + gcc / @emph{as}: Explicit in op code; for example @code{movw} to move + a 16-bit word + @* + Intel: Implicit, deduced by assembler; for example @code{mov} + + @item Instruction repetition + gcc / @emph{as}: Split into two lines; for example + @* + @code{rep} + @* + @code{stosl} + @* + Intel: Keep on one line; for example @code{rep stosl} + + @item Order of operands + gcc / @emph{as}: Source first; for example @code{movw $4, %eax} + @* + Intel: Destination first; for example @code{mov eax, 4} + @end table + + @c --------------------------------------------------------------------------- + @node A Simple Example of Inline Assembler + @section A Simple Example of Inline Assembler + + @noindent + The following example will generate a single assembly language statement, + @code{nop}, which does nothing. Despite its lack of run-time effect, + the example will be useful in illustrating the basics of + the Inline Assembler facility. + + @smallexample @c ada + @group + with System.Machine_Code; use System.Machine_Code; + procedure Nothing is + begin + Asm ("nop"); + end Nothing; + @end group + @end smallexample + + @code{Asm} is a procedure declared in package @code{System.Machine_Code}; + here it takes one parameter, a @emph{template string} that must be a static + expression and that will form the generated instruction. + @code{Asm} may be regarded as a compile-time procedure that parses + the template string and additional parameters (none here), + from which it generates a sequence of assembly language instructions. + + The examples in this chapter will illustrate several of the forms + for invoking @code{Asm}; a complete specification of the syntax + is found in the @cite{GNAT Reference Manual}. + + Under the standard GNAT conventions, the @code{Nothing} procedure + should be in a file named @file{nothing.adb}. + You can build the executable in the usual way: + @smallexample + gnatmake nothing + @end smallexample + However, the interesting aspect of this example is not its run-time behavior + but rather the generated assembly code. + To see this output, invoke the compiler as follows: + @smallexample + gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb} + @end smallexample + where the options are: + + @table @code + @item -c + compile only (no bind or link) + @item -S + generate assembler listing + @item -fomit-frame-pointer + do not set up separate stack frames + @item -gnatp + do not add runtime checks + @end table + + This gives a human-readable assembler version of the code. The resulting + file will have the same name as the Ada source file, but with a @code{.s} + extension. In our example, the file @file{nothing.s} has the following + contents: + + @smallexample + @group + .file "nothing.adb" + gcc2_compiled.: + ___gnu_compiled_ada: + .text + .align 4 + .globl __ada_nothing + __ada_nothing: + #APP + nop + #NO_APP + jmp L1 + .align 2,0x90 + L1: + ret + @end group + @end smallexample + + The assembly code you included is clearly indicated by + the compiler, between the @code{#APP} and @code{#NO_APP} + delimiters. The character before the 'APP' and 'NOAPP' + can differ on different targets. For example, GNU/Linux uses '#APP' while + on NT you will see '/APP'. + + If you make a mistake in your assembler code (such as using the + wrong size modifier, or using a wrong operand for the instruction) GNAT + will report this error in a temporary file, which will be deleted when + the compilation is finished. Generating an assembler file will help + in such cases, since you can assemble this file separately using the + @emph{as} assembler that comes with gcc. + + Assembling the file using the command + + @smallexample + as @file{nothing.s} + @end smallexample + @noindent + will give you error messages whose lines correspond to the assembler + input file, so you can easily find and correct any mistakes you made. + If there are no errors, @emph{as} will generate an object file + @file{nothing.out}. + + @c --------------------------------------------------------------------------- + @node Output Variables in Inline Assembler + @section Output Variables in Inline Assembler + + @noindent + The examples in this section, showing how to access the processor flags, + illustrate how to specify the destination operands for assembly language + statements. + + @smallexample @c ada + @group + with Interfaces; use Interfaces; + with Ada.Text_IO; use Ada.Text_IO; + with System.Machine_Code; use System.Machine_Code; + procedure Get_Flags is + Flags : Unsigned_32; + use ASCII; + begin + Asm ("pushfl" & LF & HT & -- push flags on stack + "popl %%eax" & LF & HT & -- load eax with flags + "movl %%eax, %0", -- store flags in variable + Outputs => Unsigned_32'Asm_Output ("=g", Flags)); + Put_Line ("Flags register:" & Flags'Img); + end Get_Flags; + @end group + @end smallexample + + In order to have a nicely aligned assembly listing, we have separated + multiple assembler statements in the Asm template string with linefeed + (ASCII.LF) and horizontal tab (ASCII.HT) characters. + The resulting section of the assembly output file is: + + @smallexample + @group + #APP + pushfl + popl %eax + movl %eax, -40(%ebp) + #NO_APP + @end group + @end smallexample + + It would have been legal to write the Asm invocation as: + + @smallexample + Asm ("pushfl popl %%eax movl %%eax, %0") + @end smallexample + + but in the generated assembler file, this would come out as: + + @smallexample + #APP + pushfl popl %eax movl %eax, -40(%ebp) + #NO_APP + @end smallexample + + which is not so convenient for the human reader. + + We use Ada comments + at the end of each line to explain what the assembler instructions + actually do. This is a useful convention. + + When writing Inline Assembler instructions, you need to precede each register + and variable name with a percent sign. Since the assembler already requires + a percent sign at the beginning of a register name, you need two consecutive + percent signs for such names in the Asm template string, thus @code{%%eax}. + In the generated assembly code, one of the percent signs will be stripped off. + + Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output + variables: operands you later define using @code{Input} or @code{Output} + parameters to @code{Asm}. + An output variable is illustrated in + the third statement in the Asm template string: + @smallexample + movl %%eax, %0 + @end smallexample + The intent is to store the contents of the eax register in a variable that can + be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not + necessarily work, since the compiler might optimize by using a register + to hold Flags, and the expansion of the @code{movl} instruction would not be + aware of this optimization. The solution is not to store the result directly + but rather to advise the compiler to choose the correct operand form; + that is the purpose of the @code{%0} output variable. + + Information about the output variable is supplied in the @code{Outputs} + parameter to @code{Asm}: + @smallexample + Outputs => Unsigned_32'Asm_Output ("=g", Flags)); + @end smallexample + + The output is defined by the @code{Asm_Output} attribute of the target type; + the general format is + @smallexample + Type'Asm_Output (constraint_string, variable_name) + @end smallexample + + The constraint string directs the compiler how + to store/access the associated variable. In the example + @smallexample + Unsigned_32'Asm_Output ("=m", Flags); + @end smallexample + the @code{"m"} (memory) constraint tells the compiler that the variable + @code{Flags} should be stored in a memory variable, thus preventing + the optimizer from keeping it in a register. In contrast, + @smallexample + Unsigned_32'Asm_Output ("=r", Flags); + @end smallexample + uses the @code{"r"} (register) constraint, telling the compiler to + store the variable in a register. + + If the constraint is preceded by the equal character (@strong{=}), it tells + the compiler that the variable will be used to store data into it. + + In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint, + allowing the optimizer to choose whatever it deems best. + + There are a fairly large number of constraints, but the ones that are + most useful (for the Intel x86 processor) are the following: + + @table @code + @item = + output constraint + @item g + global (i.e. can be stored anywhere) + @item m + in memory + @item I + a constant + @item a + use eax + @item b + use ebx + @item c + use ecx + @item d + use edx + @item S + use esi + @item D + use edi + @item r + use one of eax, ebx, ecx or edx + @item q + use one of eax, ebx, ecx, edx, esi or edi + @end table + + The full set of constraints is described in the gcc and @emph{as} + documentation; note that it is possible to combine certain constraints + in one constraint string. + + You specify the association of an output variable with an assembler operand + through the @code{%}@emph{n} notation, where @emph{n} is a non-negative + integer. Thus in + @smallexample @c ada + @group + Asm ("pushfl" & LF & HT & -- push flags on stack + "popl %%eax" & LF & HT & -- load eax with flags + "movl %%eax, %0", -- store flags in variable + Outputs => Unsigned_32'Asm_Output ("=g", Flags)); + @end group + @end smallexample + @noindent + @code{%0} will be replaced in the expanded code by the appropriate operand, + whatever + the compiler decided for the @code{Flags} variable. + + In general, you may have any number of output variables: + @itemize @bullet + @item + Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. + @item + Specify the @code{Outputs} parameter as a parenthesized comma-separated list + of @code{Asm_Output} attributes + @end itemize + + For example: + @smallexample @c ada + @group + Asm ("movl %%eax, %0" & LF & HT & + "movl %%ebx, %1" & LF & HT & + "movl %%ecx, %2", + Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A + Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B + Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C + @end group + @end smallexample + @noindent + where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables + in the Ada program. + + As a variation on the @code{Get_Flags} example, we can use the constraints + string to direct the compiler to store the eax register into the @code{Flags} + variable, instead of including the store instruction explicitly in the + @code{Asm} template string: + + @smallexample @c ada + @group + with Interfaces; use Interfaces; + with Ada.Text_IO; use Ada.Text_IO; + with System.Machine_Code; use System.Machine_Code; + procedure Get_Flags_2 is + Flags : Unsigned_32; + use ASCII; + begin + Asm ("pushfl" & LF & HT & -- push flags on stack + "popl %%eax", -- save flags in eax + Outputs => Unsigned_32'Asm_Output ("=a", Flags)); + Put_Line ("Flags register:" & Flags'Img); + end Get_Flags_2; + @end group + @end smallexample + + @noindent + The @code{"a"} constraint tells the compiler that the @code{Flags} + variable will come from the eax register. Here is the resulting code: + + @smallexample + @group + #APP + pushfl + popl %eax + #NO_APP + movl %eax,-40(%ebp) + @end group + @end smallexample + + @noindent + The compiler generated the store of eax into Flags after + expanding the assembler code. + + Actually, there was no need to pop the flags into the eax register; + more simply, we could just pop the flags directly into the program variable: + + @smallexample @c ada + @group + with Interfaces; use Interfaces; + with Ada.Text_IO; use Ada.Text_IO; + with System.Machine_Code; use System.Machine_Code; + procedure Get_Flags_3 is + Flags : Unsigned_32; + use ASCII; + begin + Asm ("pushfl" & LF & HT & -- push flags on stack + "pop %0", -- save flags in Flags + Outputs => Unsigned_32'Asm_Output ("=g", Flags)); + Put_Line ("Flags register:" & Flags'Img); + end Get_Flags_3; + @end group + @end smallexample + + @c --------------------------------------------------------------------------- + @node Input Variables in Inline Assembler + @section Input Variables in Inline Assembler + + @noindent + The example in this section illustrates how to specify the source operands + for assembly language statements. + The program simply increments its input value by 1: + + @smallexample @c ada + @group + with Interfaces; use Interfaces; + with Ada.Text_IO; use Ada.Text_IO; + with System.Machine_Code; use System.Machine_Code; + procedure Increment is + + function Incr (Value : Unsigned_32) return Unsigned_32 is + Result : Unsigned_32; + begin + Asm ("incl %0", + Inputs => Unsigned_32'Asm_Input ("a", Value), + Outputs => Unsigned_32'Asm_Output ("=a", Result)); + return Result; + end Incr; + + Value : Unsigned_32; + + begin + Value := 5; + Put_Line ("Value before is" & Value'Img); + Value := Incr (Value); + Put_Line ("Value after is" & Value'Img); + end Increment; + @end group + @end smallexample + + The @code{Outputs} parameter to @code{Asm} specifies + that the result will be in the eax register and that it is to be stored + in the @code{Result} variable. + + The @code{Inputs} parameter looks much like the @code{Outputs} parameter, + but with an @code{Asm_Input} attribute. + The @code{"="} constraint, indicating an output value, is not present. + + You can have multiple input variables, in the same way that you can have more + than one output variable. + + The parameter count (%0, %1) etc, now starts at the first input + statement, and continues with the output statements. + When both parameters use the same variable, the + compiler will treat them as the same %n operand, which is the case here. + + Just as the @code{Outputs} parameter causes the register to be stored into the + target variable after execution of the assembler statements, so does the + @code{Inputs} parameter cause its variable to be loaded into the register + before execution of the assembler statements. + + Thus the effect of the @code{Asm} invocation is: + @enumerate + @item load the 32-bit value of @code{Value} into eax + @item execute the @code{incl %eax} instruction + @item store the contents of eax into the @code{Result} variable + @end enumerate + + The resulting assembler file (with @option{-O2} optimization) contains: + @smallexample + @group + _increment__incr.1: + subl $4,%esp + movl 8(%esp),%eax + #APP + incl %eax + #NO_APP + movl %eax,%edx + movl %ecx,(%esp) + addl $4,%esp + ret + @end group + @end smallexample + + @c --------------------------------------------------------------------------- + @node Inlining Inline Assembler Code + @section Inlining Inline Assembler Code + + @noindent + For a short subprogram such as the @code{Incr} function in the previous + section, the overhead of the call and return (creating / deleting the stack + frame) can be significant, compared to the amount of code in the subprogram + body. A solution is to apply Ada's @code{Inline} pragma to the subprogram, + which directs the compiler to expand invocations of the subprogram at the + point(s) of call, instead of setting up a stack frame for out-of-line calls. + Here is the resulting program: + + @smallexample @c ada + @group + with Interfaces; use Interfaces; + with Ada.Text_IO; use Ada.Text_IO; + with System.Machine_Code; use System.Machine_Code; + procedure Increment_2 is + + function Incr (Value : Unsigned_32) return Unsigned_32 is + Result : Unsigned_32; + begin + Asm ("incl %0", + Inputs => Unsigned_32'Asm_Input ("a", Value), + Outputs => Unsigned_32'Asm_Output ("=a", Result)); + return Result; + end Incr; + pragma Inline (Increment); + + Value : Unsigned_32; + + begin + Value := 5; + Put_Line ("Value before is" & Value'Img); + Value := Increment (Value); + Put_Line ("Value after is" & Value'Img); + end Increment_2; + @end group + @end smallexample + + Compile the program with both optimization (@option{-O2}) and inlining + enabled (@option{-gnatpn} instead of @option{-gnatp}). + + The @code{Incr} function is still compiled as usual, but at the + point in @code{Increment} where our function used to be called: + + @smallexample + @group + pushl %edi + call _increment__incr.1 + @end group + @end smallexample + + @noindent + the code for the function body directly appears: + + @smallexample + @group + movl %esi,%eax + #APP + incl %eax + #NO_APP + movl %eax,%edx + @end group + @end smallexample + + @noindent + thus saving the overhead of stack frame setup and an out-of-line call. + + @c --------------------------------------------------------------------------- + @node Other Asm Functionality + @section Other @code{Asm} Functionality + + @noindent + This section describes two important parameters to the @code{Asm} + procedure: @code{Clobber}, which identifies register usage; + and @code{Volatile}, which inhibits unwanted optimizations. + + @menu + * The Clobber Parameter:: + * The Volatile Parameter:: + @end menu + + @c --------------------------------------------------------------------------- + @node The Clobber Parameter + @subsection The @code{Clobber} Parameter + + @noindent + One of the dangers of intermixing assembly language and a compiled language + such as Ada is that the compiler needs to be aware of which registers are + being used by the assembly code. In some cases, such as the earlier examples, + the constraint string is sufficient to indicate register usage (e.g., + @code{"a"} for + the eax register). But more generally, the compiler needs an explicit + identification of the registers that are used by the Inline Assembly + statements. + + Using a register that the compiler doesn't know about + could be a side effect of an instruction (like @code{mull} + storing its result in both eax and edx). + It can also arise from explicit register usage in your + assembly code; for example: + @smallexample + @group + Asm ("movl %0, %%ebx" & LF & HT & + "movl %%ebx, %1", + Inputs => Unsigned_32'Asm_Input ("g", Var_In), + Outputs => Unsigned_32'Asm_Output ("=g", Var_Out)); + @end group + @end smallexample + @noindent + where the compiler (since it does not analyze the @code{Asm} template string) + does not know you are using the ebx register. + + In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, + to identify the registers that will be used by your assembly code: + + @smallexample + @group + Asm ("movl %0, %%ebx" & LF & HT & + "movl %%ebx, %1", + Inputs => Unsigned_32'Asm_Input ("g", Var_In), + Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), + Clobber => "ebx"); + @end group + @end smallexample + + The Clobber parameter is a static string expression specifying the + register(s) you are using. Note that register names are @emph{not} prefixed + by a percent sign. Also, if more than one register is used then their names + are separated by commas; e.g., @code{"eax, ebx"} + + The @code{Clobber} parameter has several additional uses: + @enumerate + @item Use ``register'' name @code{cc} to indicate that flags might have changed + @item Use ``register'' name @code{memory} if you changed a memory location + @end enumerate + + @c --------------------------------------------------------------------------- + @node The Volatile Parameter + @subsection The @code{Volatile} Parameter + @cindex Volatile parameter + + @noindent + Compiler optimizations in the presence of Inline Assembler may sometimes have + unwanted effects. For example, when an @code{Asm} invocation with an input + variable is inside a loop, the compiler might move the loading of the input + variable outside the loop, regarding it as a one-time initialization. + + If this effect is not desired, you can disable such optimizations by setting + the @code{Volatile} parameter to @code{True}; for example: + + @smallexample @c ada + @group + Asm ("movl %0, %%ebx" & LF & HT & + "movl %%ebx, %1", + Inputs => Unsigned_32'Asm_Input ("g", Var_In), + Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), + Clobber => "ebx", + Volatile => True); + @end group + @end smallexample + + By default, @code{Volatile} is set to @code{False} unless there is no + @code{Outputs} parameter. + + Although setting @code{Volatile} to @code{True} prevents unwanted + optimizations, it will also disable other optimizations that might be + important for efficiency. In general, you should set @code{Volatile} + to @code{True} only if the compiler's optimizations have created + problems. + + @c --------------------------------------------------------------------------- + @node A Complete Example + @section A Complete Example + + @noindent + This section contains a complete program illustrating a realistic usage + of GNAT's Inline Assembler capabilities. It comprises a main procedure + @code{Check_CPU} and a package @code{Intel_CPU}. + The package declares a collection of functions that detect the properties + of the 32-bit x86 processor that is running the program. + The main procedure invokes these functions and displays the information. + + The Intel_CPU package could be enhanced by adding functions to + detect the type of x386 co-processor, the processor caching options and + special operations such as the SIMD extensions. + + Although the Intel_CPU package has been written for 32-bit Intel + compatible CPUs, it is OS neutral. It has been tested on DOS, + Windows/NT and GNU/Linux. + + @menu + * Check_CPU Procedure:: + * Intel_CPU Package Specification:: + * Intel_CPU Package Body:: + @end menu + + @c --------------------------------------------------------------------------- + @node Check_CPU Procedure + @subsection @code{Check_CPU} Procedure + @cindex Check_CPU procedure + + @smallexample @c adanocomment + --------------------------------------------------------------------- + -- -- + -- Uses the Intel_CPU package to identify the CPU the program is -- + -- running on, and some of the features it supports. -- + -- -- + --------------------------------------------------------------------- + + with Intel_CPU; -- Intel CPU detection functions + with Ada.Text_IO; -- Standard text I/O + with Ada.Command_Line; -- To set the exit status + + procedure Check_CPU is + + Type_Found : Boolean := False; + -- Flag to indicate that processor was identified + + Features : Intel_CPU.Processor_Features; + -- The processor features + + Signature : Intel_CPU.Processor_Signature; + -- The processor type signature + + begin + + ----------------------------------- + -- Display the program banner. -- + ----------------------------------- + + Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name & + ": check Intel CPU version and features, v1.0"); + Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever"); + Ada.Text_IO.New_Line; + + ----------------------------------------------------------------------- + -- We can safely start with the assumption that we are on at least -- + -- a x386 processor. If the CPUID instruction is present, then we -- + -- have a later processor type. -- + ----------------------------------------------------------------------- + + if Intel_CPU.Has_CPUID = False then + + -- No CPUID instruction, so we assume this is indeed a x386 + -- processor. We can still check if it has a FP co-processor. + if Intel_CPU.Has_FPU then + Ada.Text_IO.Put_Line + ("x386-type processor with a FP co-processor"); + else + Ada.Text_IO.Put_Line + ("x386-type processor without a FP co-processor"); + end if; -- check for FPU + + -- Program done + Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); + return; + + end if; -- check for CPUID + + ----------------------------------------------------------------------- + -- If CPUID is supported, check if this is a true Intel processor, -- + -- if it is not, display a warning. -- + ----------------------------------------------------------------------- + + if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then + Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor"); + Ada.Text_IO.Put_Line ("*** Some information may be incorrect"); + end if; -- check if Intel + + ---------------------------------------------------------------------- + -- With the CPUID instruction present, we can assume at least a -- + -- x486 processor. If the CPUID support level is < 1 then we have -- + -- to leave it at that. -- + ---------------------------------------------------------------------- + + if Intel_CPU.CPUID_Level < 1 then + + -- Ok, this is a x486 processor. we still can get the Vendor ID + Ada.Text_IO.Put_Line ("x486-type processor"); + Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID); + + -- We can also check if there is a FPU present + if Intel_CPU.Has_FPU then + Ada.Text_IO.Put_Line ("Floating-Point support"); + else + Ada.Text_IO.Put_Line ("No Floating-Point support"); + end if; -- check for FPU + + -- Program done + Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); + return; + + end if; -- check CPUID level + + --------------------------------------------------------------------- + -- With a CPUID level of 1 we can use the processor signature to -- + -- determine it's exact type. -- + --------------------------------------------------------------------- + + Signature := Intel_CPU.Signature; + + ---------------------------------------------------------------------- + -- Ok, now we go into a lot of messy comparisons to get the -- + -- processor type. For clarity, no attememt to try to optimize the -- + -- comparisons has been made. Note that since Intel_CPU does not -- + -- support getting cache info, we cannot distinguish between P5 -- + -- and Celeron types yet. -- + ---------------------------------------------------------------------- + + -- x486SL + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0100# and + Signature.Model = 2#0100# then + Type_Found := True; + Ada.Text_IO.Put_Line ("x486SL processor"); + end if; + + -- x486DX2 Write-Back + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0100# and + Signature.Model = 2#0111# then + Type_Found := True; + Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor"); + end if; + + -- x486DX4 + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0100# and + Signature.Model = 2#1000# then + Type_Found := True; + Ada.Text_IO.Put_Line ("x486DX4 processor"); + end if; + + -- x486DX4 Overdrive + if Signature.Processor_Type = 2#01# and + Signature.Family = 2#0100# and + Signature.Model = 2#1000# then + Type_Found := True; + Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor"); + end if; + + -- Pentium (60, 66) + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0101# and + Signature.Model = 2#0001# then + Type_Found := True; + Ada.Text_IO.Put_Line ("Pentium processor (60, 66)"); + end if; + + -- Pentium (75, 90, 100, 120, 133, 150, 166, 200) + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0101# and + Signature.Model = 2#0010# then + Type_Found := True; + Ada.Text_IO.Put_Line + ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)"); + end if; + + -- Pentium OverDrive (60, 66) + if Signature.Processor_Type = 2#01# and + Signature.Family = 2#0101# and + Signature.Model = 2#0001# then + Type_Found := True; + Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)"); + end if; + + -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200) + if Signature.Processor_Type = 2#01# and + Signature.Family = 2#0101# and + Signature.Model = 2#0010# then + Type_Found := True; + Ada.Text_IO.Put_Line + ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)"); + end if; + + -- Pentium OverDrive processor for x486 processor-based systems + if Signature.Processor_Type = 2#01# and + Signature.Family = 2#0101# and + Signature.Model = 2#0011# then + Type_Found := True; + Ada.Text_IO.Put_Line + ("Pentium OverDrive processor for x486 processor-based systems"); + end if; + + -- Pentium processor with MMX technology (166, 200) + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0101# and + Signature.Model = 2#0100# then + Type_Found := True; + Ada.Text_IO.Put_Line + ("Pentium processor with MMX technology (166, 200)"); + end if; + + -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133) + if Signature.Processor_Type = 2#01# and + Signature.Family = 2#0101# and + Signature.Model = 2#0100# then + Type_Found := True; + Ada.Text_IO.Put_Line + ("Pentium OverDrive processor with MMX " & + "technology for Pentium processor (75, 90, 100, 120, 133)"); + end if; + + -- Pentium Pro processor + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0110# and + Signature.Model = 2#0001# then + Type_Found := True; + Ada.Text_IO.Put_Line ("Pentium Pro processor"); + end if; + + -- Pentium II processor, model 3 + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0110# and + Signature.Model = 2#0011# then + Type_Found := True; + Ada.Text_IO.Put_Line ("Pentium II processor, model 3"); + end if; + + -- Pentium II processor, model 5 or Celeron processor + if Signature.Processor_Type = 2#00# and + Signature.Family = 2#0110# and + Signature.Model = 2#0101# then + Type_Found := True; + Ada.Text_IO.Put_Line + ("Pentium II processor, model 5 or Celeron processor"); + end if; + + -- Pentium Pro OverDrive processor + if Signature.Processor_Type = 2#01# and + Signature.Family = 2#0110# and + Signature.Model = 2#0011# then + Type_Found := True; + Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor"); + end if; + + -- If no type recognized, we have an unknown. Display what + -- we _do_ know + if Type_Found = False then + Ada.Text_IO.Put_Line ("Unknown processor"); + end if; + + ----------------------------------------- + -- Display processor stepping level. -- + ----------------------------------------- + + Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img); + + --------------------------------- + -- Display vendor ID string. -- + --------------------------------- + + Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID); + + ------------------------------------ + -- Get the processors features. -- + ------------------------------------ + + Features := Intel_CPU.Features; + + ----------------------------- + -- Check for a FPU unit. -- + ----------------------------- + + if Features.FPU = True then + Ada.Text_IO.Put_Line ("Floating-Point unit available"); + else + Ada.Text_IO.Put_Line ("no Floating-Point unit"); + end if; -- check for FPU + + -------------------------------- + -- List processor features. -- + -------------------------------- + + Ada.Text_IO.Put_Line ("Supported features: "); + + -- Virtual Mode Extension + if Features.VME = True then + Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension"); + end if; + + -- Debugging Extension + if Features.DE = True then + Ada.Text_IO.Put_Line (" DE - Debugging Extension"); + end if; + + -- Page Size Extension + if Features.PSE = True then + Ada.Text_IO.Put_Line (" PSE - Page Size Extension"); + end if; + + -- Time Stamp Counter + if Features.TSC = True then + Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter"); + end if; + + -- Model Specific Registers + if Features.MSR = True then + Ada.Text_IO.Put_Line (" MSR - Model Specific Registers"); + end if; + + -- Physical Address Extension + if Features.PAE = True then + Ada.Text_IO.Put_Line (" PAE - Physical Address Extension"); + end if; + + -- Machine Check Extension + if Features.MCE = True then + Ada.Text_IO.Put_Line (" MCE - Machine Check Extension"); + end if; + + -- CMPXCHG8 instruction supported + if Features.CX8 = True then + Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction"); + end if; + + -- on-chip APIC hardware support + if Features.APIC = True then + Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support"); + end if; + + -- Fast System Call + if Features.SEP = True then + Ada.Text_IO.Put_Line (" SEP - Fast System Call"); + end if; + + -- Memory Type Range Registers + if Features.MTRR = True then + Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers"); + end if; + + -- Page Global Enable + if Features.PGE = True then + Ada.Text_IO.Put_Line (" PGE - Page Global Enable"); + end if; + + -- Machine Check Architecture + if Features.MCA = True then + Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture"); + end if; + + -- Conditional Move Instruction Supported + if Features.CMOV = True then + Ada.Text_IO.Put_Line + (" CMOV - Conditional Move Instruction Supported"); + end if; + + -- Page Attribute Table + if Features.PAT = True then + Ada.Text_IO.Put_Line (" PAT - Page Attribute Table"); + end if; + + -- 36-bit Page Size Extension + if Features.PSE_36 = True then + Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension"); + end if; + + -- MMX technology supported + if Features.MMX = True then + Ada.Text_IO.Put_Line (" MMX - MMX technology supported"); + end if; + + -- Fast FP Save and Restore + if Features.FXSR = True then + Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore"); + end if; + + --------------------- + -- Program done. -- + --------------------- + + Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); + + exception + + when others => + Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); + raise; + + end Check_CPU; + @end smallexample + + @c --------------------------------------------------------------------------- + @node Intel_CPU Package Specification + @subsection @code{Intel_CPU} Package Specification + @cindex Intel_CPU package specification + + @smallexample @c adanocomment + ------------------------------------------------------------------------- + -- -- + -- file: intel_cpu.ads -- + -- -- + -- ********************************************* -- + -- * WARNING: for 32-bit Intel processors only * -- + -- ********************************************* -- + -- -- + -- This package contains a number of subprograms that are useful in -- + -- determining the Intel x86 CPU (and the features it supports) on -- + -- which the program is running. -- + -- -- + -- The package is based upon the information given in the Intel -- + -- Application Note AP-485: "Intel Processor Identification and the -- + -- CPUID Instruction" as of April 1998. This application note can be -- + -- found on www.intel.com. -- + -- -- + -- It currently deals with 32-bit processors only, will not detect -- + -- features added after april 1998, and does not guarantee proper -- + -- results on Intel-compatible processors. -- + -- -- + -- Cache info and x386 fpu type detection are not supported. -- + -- -- + -- This package does not use any privileged instructions, so should -- + -- work on any OS running on a 32-bit Intel processor. -- + -- -- + ------------------------------------------------------------------------- + + with Interfaces; use Interfaces; + -- for using unsigned types + + with System.Machine_Code; use System.Machine_Code; + -- for using inline assembler code + + with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; + -- for inserting control characters + + package Intel_CPU is + + ---------------------- + -- Processor bits -- + ---------------------- + + subtype Num_Bits is Natural range 0 .. 31; + -- the number of processor bits (32) + + -------------------------- + -- Processor register -- + -------------------------- + + -- define a processor register type for easy access to + -- the individual bits + + type Processor_Register is array (Num_Bits) of Boolean; + pragma Pack (Processor_Register); + for Processor_Register'Size use 32; + + ------------------------- + -- Unsigned register -- + ------------------------- + + -- define a processor register type for easy access to + -- the individual bytes + + type Unsigned_Register is + record + L1 : Unsigned_8; + H1 : Unsigned_8; + L2 : Unsigned_8; + H2 : Unsigned_8; + end record; + + for Unsigned_Register use + record + L1 at 0 range 0 .. 7; + H1 at 0 range 8 .. 15; + L2 at 0 range 16 .. 23; + H2 at 0 range 24 .. 31; + end record; + + for Unsigned_Register'Size use 32; + + --------------------------------- + -- Intel processor vendor ID -- + --------------------------------- + + Intel_Processor : constant String (1 .. 12) := "GenuineIntel"; + -- indicates an Intel manufactured processor + + ------------------------------------ + -- Processor signature register -- + ------------------------------------ + + -- a register type to hold the processor signature + + type Processor_Signature is + record + Stepping : Natural range 0 .. 15; + Model : Natural range 0 .. 15; + Family : Natural range 0 .. 15; + Processor_Type : Natural range 0 .. 3; + Reserved : Natural range 0 .. 262143; + end record; + + for Processor_Signature use + record + Stepping at 0 range 0 .. 3; + Model at 0 range 4 .. 7; + Family at 0 range 8 .. 11; + Processor_Type at 0 range 12 .. 13; + Reserved at 0 range 14 .. 31; + end record; + + for Processor_Signature'Size use 32; + + ----------------------------------- + -- Processor features register -- + ----------------------------------- + + -- a processor register to hold the processor feature flags + + type Processor_Features is + record + FPU : Boolean; -- floating point unit on chip + VME : Boolean; -- virtual mode extension + DE : Boolean; -- debugging extension + PSE : Boolean; -- page size extension + TSC : Boolean; -- time stamp counter + MSR : Boolean; -- model specific registers + PAE : Boolean; -- physical address extension + MCE : Boolean; -- machine check extension + CX8 : Boolean; -- cmpxchg8 instruction + APIC : Boolean; -- on-chip apic hardware + Res_1 : Boolean; -- reserved for extensions + SEP : Boolean; -- fast system call + MTRR : Boolean; -- memory type range registers + PGE : Boolean; -- page global enable + MCA : Boolean; -- machine check architecture + CMOV : Boolean; -- conditional move supported + PAT : Boolean; -- page attribute table + PSE_36 : Boolean; -- 36-bit page size extension + Res_2 : Natural range 0 .. 31; -- reserved for extensions + MMX : Boolean; -- MMX technology supported + FXSR : Boolean; -- fast FP save and restore + Res_3 : Natural range 0 .. 127; -- reserved for extensions + end record; + + for Processor_Features use + record + FPU at 0 range 0 .. 0; + VME at 0 range 1 .. 1; + DE at 0 range 2 .. 2; + PSE at 0 range 3 .. 3; + TSC at 0 range 4 .. 4; + MSR at 0 range 5 .. 5; + PAE at 0 range 6 .. 6; + MCE at 0 range 7 .. 7; + CX8 at 0 range 8 .. 8; + APIC at 0 range 9 .. 9; + Res_1 at 0 range 10 .. 10; + SEP at 0 range 11 .. 11; + MTRR at 0 range 12 .. 12; + PGE at 0 range 13 .. 13; + MCA at 0 range 14 .. 14; + CMOV at 0 range 15 .. 15; + PAT at 0 range 16 .. 16; + PSE_36 at 0 range 17 .. 17; + Res_2 at 0 range 18 .. 22; + MMX at 0 range 23 .. 23; + FXSR at 0 range 24 .. 24; + Res_3 at 0 range 25 .. 31; + end record; + + for Processor_Features'Size use 32; + + ------------------- + -- Subprograms -- + ------------------- + + function Has_FPU return Boolean; + -- return True if a FPU is found + -- use only if CPUID is not supported + + function Has_CPUID return Boolean; + -- return True if the processor supports the CPUID instruction + + function CPUID_Level return Natural; + -- return the CPUID support level (0, 1 or 2) + -- can only be called if the CPUID instruction is supported + + function Vendor_ID return String; + -- return the processor vendor identification string + -- can only be called if the CPUID instruction is supported + + function Signature return Processor_Signature; + -- return the processor signature + -- can only be called if the CPUID instruction is supported + + function Features return Processor_Features; + -- return the processors features + -- can only be called if the CPUID instruction is supported + + private + + ------------------------ + -- EFLAGS bit names -- + ------------------------ + + ID_Flag : constant Num_Bits := 21; + -- ID flag bit + + end Intel_CPU; + @end smallexample + + @c --------------------------------------------------------------------------- + @node Intel_CPU Package Body + @subsection @code{Intel_CPU} Package Body + @cindex Intel_CPU package body + + @smallexample @c adanocomment + package body Intel_CPU is + + --------------------------- + -- Detect FPU presence -- + --------------------------- + + -- There is a FPU present if we can set values to the FPU Status + -- and Control Words. + + function Has_FPU return Boolean is + + Register : Unsigned_16; + -- processor register to store a word + + begin + + -- check if we can change the status word + Asm ( + + -- the assembler code + "finit" & LF & HT & -- reset status word + "movw $0x5A5A, %%ax" & LF & HT & -- set value status word + "fnstsw %0" & LF & HT & -- save status word + "movw %%ax, %0", -- store status word + + -- output stored in Register + -- register must be a memory location + Outputs => Unsigned_16'Asm_output ("=m", Register), + + -- tell compiler that we used eax + Clobber => "eax"); + + -- if the status word is zero, there is no FPU + if Register = 0 then + return False; -- no status word + end if; -- check status word value + + -- check if we can get the control word + Asm ( + + -- the assembler code + "fnstcw %0", -- save the control word + + -- output into Register + -- register must be a memory location + Outputs => Unsigned_16'Asm_output ("=m", Register)); + + -- check the relevant bits + if (Register and 16#103F#) /= 16#003F# then + return False; -- no control word + end if; -- check control word value + + -- FPU found + return True; + + end Has_FPU; + + -------------------------------- + -- Detect CPUID instruction -- + -------------------------------- + + -- The processor supports the CPUID instruction if it is possible + -- to change the value of ID flag bit in the EFLAGS register. + + function Has_CPUID return Boolean is + + Original_Flags, Modified_Flags : Processor_Register; + -- EFLAG contents before and after changing the ID flag + + begin + + -- try flipping the ID flag in the EFLAGS register + Asm ( + + -- the assembler code + "pushfl" & LF & HT & -- push EFLAGS on stack + "pop %%eax" & LF & HT & -- pop EFLAGS into eax + "movl %%eax, %0" & LF & HT & -- save EFLAGS content + "xor $0x200000, %%eax" & LF & HT & -- flip ID flag + "push %%eax" & LF & HT & -- push EFLAGS on stack + "popfl" & LF & HT & -- load EFLAGS register + "pushfl" & LF & HT & -- push EFLAGS on stack + "pop %1", -- save EFLAGS content + + -- output values, may be anything + -- Original_Flags is %0 + -- Modified_Flags is %1 + Outputs => + (Processor_Register'Asm_output ("=g", Original_Flags), + Processor_Register'Asm_output ("=g", Modified_Flags)), + + -- tell compiler eax is destroyed + Clobber => "eax"); + + -- check if CPUID is supported + if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then + return True; -- ID flag was modified + else + return False; -- ID flag unchanged + end if; -- check for CPUID + + end Has_CPUID; + + ------------------------------- + -- Get CPUID support level -- + ------------------------------- + + function CPUID_Level return Natural is + + Level : Unsigned_32; + -- returned support level + + begin + + -- execute CPUID, storing the results in the Level register + Asm ( + + -- the assembler code + "cpuid", -- execute CPUID + + -- zero is stored in eax + -- returning the support level in eax + Inputs => Unsigned_32'Asm_input ("a", 0), + + -- eax is stored in Level + Outputs => Unsigned_32'Asm_output ("=a", Level), + + -- tell compiler ebx, ecx and edx registers are destroyed + Clobber => "ebx, ecx, edx"); + + -- return the support level + return Natural (Level); + + end CPUID_Level; + + -------------------------------- + -- Get CPU Vendor ID String -- + -------------------------------- + + -- The vendor ID string is returned in the ebx, ecx and edx register + -- after executing the CPUID instruction with eax set to zero. + -- In case of a true Intel processor the string returned is + -- "GenuineIntel" + + function Vendor_ID return String is + + Ebx, Ecx, Edx : Unsigned_Register; + -- registers containing the vendor ID string + + Vendor_ID : String (1 .. 12); + -- the vendor ID string + + begin + + -- execute CPUID, storing the results in the processor registers + Asm ( + + -- the assembler code + "cpuid", -- execute CPUID + + -- zero stored in eax + -- vendor ID string returned in ebx, ecx and edx + Inputs => Unsigned_32'Asm_input ("a", 0), + + -- ebx is stored in Ebx + -- ecx is stored in Ecx + -- edx is stored in Edx + Outputs => (Unsigned_Register'Asm_output ("=b", Ebx), + Unsigned_Register'Asm_output ("=c", Ecx), + Unsigned_Register'Asm_output ("=d", Edx))); + + -- now build the vendor ID string + Vendor_ID( 1) := Character'Val (Ebx.L1); + Vendor_ID( 2) := Character'Val (Ebx.H1); + Vendor_ID( 3) := Character'Val (Ebx.L2); + Vendor_ID( 4) := Character'Val (Ebx.H2); + Vendor_ID( 5) := Character'Val (Edx.L1); + Vendor_ID( 6) := Character'Val (Edx.H1); + Vendor_ID( 7) := Character'Val (Edx.L2); + Vendor_ID( 8) := Character'Val (Edx.H2); + Vendor_ID( 9) := Character'Val (Ecx.L1); + Vendor_ID(10) := Character'Val (Ecx.H1); + Vendor_ID(11) := Character'Val (Ecx.L2); + Vendor_ID(12) := Character'Val (Ecx.H2); + + -- return string + return Vendor_ID; + + end Vendor_ID; + + ------------------------------- + -- Get processor signature -- + ------------------------------- + + function Signature return Processor_Signature is + + Result : Processor_Signature; + -- processor signature returned + + begin + + -- execute CPUID, storing the results in the Result variable + Asm ( + + -- the assembler code + "cpuid", -- execute CPUID + + -- one is stored in eax + -- processor signature returned in eax + Inputs => Unsigned_32'Asm_input ("a", 1), + + -- eax is stored in Result + Outputs => Processor_Signature'Asm_output ("=a", Result), + + -- tell compiler that ebx, ecx and edx are also destroyed + Clobber => "ebx, ecx, edx"); + + -- return processor signature + return Result; + + end Signature; + + ------------------------------ + -- Get processor features -- + ------------------------------ + + function Features return Processor_Features is + + Result : Processor_Features; + -- processor features returned + + begin + + -- execute CPUID, storing the results in the Result variable + Asm ( + + -- the assembler code + "cpuid", -- execute CPUID + + -- one stored in eax + -- processor features returned in edx + Inputs => Unsigned_32'Asm_input ("a", 1), + + -- edx is stored in Result + Outputs => Processor_Features'Asm_output ("=d", Result), + + -- tell compiler that ebx and ecx are also destroyed + Clobber => "ebx, ecx"); + + -- return processor signature + return Result; + + end Features; + + end Intel_CPU; + @end smallexample + @c END OF INLINE ASSEMBLER CHAPTER + @c =============================== + + + + @c *********************************** + @c * Compatibility and Porting Guide * + @c *********************************** + @node Compatibility and Porting Guide + @appendix Compatibility and Porting Guide + + @noindent + This chapter describes the compatibility issues that may arise between + GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT + can expedite porting + applications developed in other Ada environments. + + @menu + * Compatibility with Ada 83:: + * Implementation-dependent characteristics:: + * Compatibility with DEC Ada 83:: + * Compatibility with Other Ada 95 Systems:: + * Representation Clauses:: + @end menu + + @node Compatibility with Ada 83 + @section Compatibility with Ada 83 + @cindex Compatibility (between Ada 83 and Ada 95) + + @noindent + Ada 95 is designed to be highly upwards compatible with Ada 83. In + particular, the design intention is that the difficulties associated + with moving from Ada 83 to Ada 95 should be no greater than those + that occur when moving from one Ada 83 system to another. + + However, there are a number of points at which there are minor + incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains + full details of these issues, + and should be consulted for a complete treatment. + In practice the + following subsections treat the most likely issues to be encountered. + + @menu + * Legal Ada 83 programs that are illegal in Ada 95:: + * More deterministic semantics:: + * Changed semantics:: + * Other language compatibility issues:: + @end menu + + @node Legal Ada 83 programs that are illegal in Ada 95 + @subsection Legal Ada 83 programs that are illegal in Ada 95 + + @table @asis + @item Character literals + Some uses of character literals are ambiguous. Since Ada 95 has introduced + @code{Wide_Character} as a new predefined character type, some uses of + character literals that were legal in Ada 83 are illegal in Ada 95. + For example: + @smallexample @c ada + for Char in 'A' .. 'Z' loop ... end loop; + @end smallexample + @noindent + The problem is that @code{'A'} and @code{'Z'} could be from either + @code{Character} or @code{Wide_Character}. The simplest correction + is to make the type explicit; e.g.: + @smallexample @c ada + for Char in Character range 'A' .. 'Z' loop ... end loop; + @end smallexample + + @item New reserved words + The identifiers @code{abstract}, @code{aliased}, @code{protected}, + @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95. + Existing Ada 83 code using any of these identifiers must be edited to + use some alternative name. + + @item Freezing rules + The rules in Ada 95 are slightly different with regard to the point at + which entities are frozen, and representation pragmas and clauses are + not permitted past the freeze point. This shows up most typically in + the form of an error message complaining that a representation item + appears too late, and the appropriate corrective action is to move + the item nearer to the declaration of the entity to which it refers. + + A particular case is that representation pragmas + @ifset vms + (including the + extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure}) + @end ifset + cannot be applied to a subprogram body. If necessary, a separate subprogram + declaration must be introduced to which the pragma can be applied. + + @item Optional bodies for library packages + In Ada 83, a package that did not require a package body was nevertheless + allowed to have one. This lead to certain surprises in compiling large + systems (situations in which the body could be unexpectedly ignored by the + binder). In Ada 95, if a package does not require a body then it is not + permitted to have a body. To fix this problem, simply remove a redundant + body if it is empty, or, if it is non-empty, introduce a dummy declaration + into the spec that makes the body required. One approach is to add a private + part to the package declaration (if necessary), and define a parameterless + procedure called @code{Requires_Body}, which must then be given a dummy + procedure body in the package body, which then becomes required. + Another approach (assuming that this does not introduce elaboration + circularities) is to add an @code{Elaborate_Body} pragma to the package spec, + since one effect of this pragma is to require the presence of a package body. + + @item @code{Numeric_Error} is now the same as @code{Constraint_Error} + In Ada 95, the exception @code{Numeric_Error} is a renaming of + @code{Constraint_Error}. + This means that it is illegal to have separate exception handlers for + the two exceptions. The fix is simply to remove the handler for the + @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise + @code{Constraint_Error} in place of @code{Numeric_Error} in all cases). + + @item Indefinite subtypes in generics + In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String}) + as the actual for a generic formal private type, but then the instantiation + would be illegal if there were any instances of declarations of variables + of this type in the generic body. In Ada 95, to avoid this clear violation + of the methodological principle known as the ``contract model'', + the generic declaration explicitly indicates whether + or not such instantiations are permitted. If a generic formal parameter + has explicit unknown discriminants, indicated by using @code{(<>)} after the + type name, then it can be instantiated with indefinite types, but no + stand-alone variables can be declared of this type. Any attempt to declare + such a variable will result in an illegality at the time the generic is + declared. If the @code{(<>)} notation is not used, then it is illegal + to instantiate the generic with an indefinite type. + This is the potential incompatibility issue when porting Ada 83 code to Ada 95. + It will show up as a compile time error, and + the fix is usually simply to add the @code{(<>)} to the generic declaration. + @end table + + @node More deterministic semantics + @subsection More deterministic semantics + + @table @asis + @item Conversions + Conversions from real types to integer types round away from 0. In Ada 83 + the conversion Integer(2.5) could deliver either 2 or 3 as its value. This + implementation freedom was intended to support unbiased rounding in + statistical applications, but in practice it interfered with portability. + In Ada 95 the conversion semantics are unambiguous, and rounding away from 0 + is required. Numeric code may be affected by this change in semantics. + Note, though, that this issue is no worse than already existed in Ada 83 + when porting code from one vendor to another. + + @item Tasking + The Real-Time Annex introduces a set of policies that define the behavior of + features that were implementation dependent in Ada 83, such as the order in + which open select branches are executed. + @end table + + @node Changed semantics + @subsection Changed semantics + + @noindent + The worst kind of incompatibility is one where a program that is legal in + Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not + possible in Ada 83. Fortunately this is extremely rare, but the one + situation that you should be alert to is the change in the predefined type + @code{Character} from 7-bit ASCII to 8-bit Latin-1. + + @table @asis + @item range of @code{Character} + The range of @code{Standard.Character} is now the full 256 characters + of Latin-1, whereas in most Ada 83 implementations it was restricted + to 128 characters. Although some of the effects of + this change will be manifest in compile-time rejection of legal + Ada 83 programs it is possible for a working Ada 83 program to have + a different effect in Ada 95, one that was not permitted in Ada 83. + As an example, the expression + @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now + delivers @code{255} as its value. + In general, you should look at the logic of any + character-processing Ada 83 program and see whether it needs to be adapted + to work correctly with Latin-1. Note that the predefined Ada 95 API has a + character handling package that may be relevant if code needs to be adapted + to account for the additional Latin-1 elements. + The desirable fix is to + modify the program to accommodate the full character set, but in some cases + it may be convenient to define a subtype or derived type of Character that + covers only the restricted range. + @cindex Latin-1 + @end table + + @node Other language compatibility issues + @subsection Other language compatibility issues + @table @asis + @item @option{-gnat83 switch} + All implementations of GNAT provide a switch that causes GNAT to operate + in Ada 83 mode. In this mode, some but not all compatibility problems + of the type described above are handled automatically. For example, the + new Ada 95 reserved words are treated simply as identifiers as in Ada 83. + However, + in practice, it is usually advisable to make the necessary modifications + to the program to remove the need for using this switch. + See @ref{Compiling Ada 83 Programs}. + + @item Support for removed Ada 83 pragmas and attributes + A number of pragmas and attributes from Ada 83 have been removed from Ada 95, + generally because they have been replaced by other mechanisms. Ada 95 + compilers are allowed, but not required, to implement these missing + elements. In contrast with some other Ada 95 compilers, GNAT implements all + such pragmas and attributes, eliminating this compatibility concern. These + include @code{pragma Interface} and the floating point type attributes + (@code{Emax}, @code{Mantissa}, etc.), among other items. + @end table + + + @node Implementation-dependent characteristics + @section Implementation-dependent characteristics + @noindent + Although the Ada language defines the semantics of each construct as + precisely as practical, in some situations (for example for reasons of + efficiency, or where the effect is heavily dependent on the host or target + platform) the implementation is allowed some freedom. In porting Ada 83 + code to GNAT, you need to be aware of whether / how the existing code + exercised such implementation dependencies. Such characteristics fall into + several categories, and GNAT offers specific support in assisting the + transition from certain Ada 83 compilers. + + @menu + * Implementation-defined pragmas:: + * Implementation-defined attributes:: + * Libraries:: + * Elaboration order:: + * Target-specific aspects:: + @end menu + + + @node Implementation-defined pragmas + @subsection Implementation-defined pragmas + + @noindent + Ada compilers are allowed to supplement the language-defined pragmas, and + these are a potential source of non-portability. All GNAT-defined pragmas + are described in the GNAT Reference Manual, and these include several that + are specifically intended to correspond to other vendors' Ada 83 pragmas. + For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful. + For + compatibility with DEC Ada 83, GNAT supplies the pragmas + @code{Extend_System}, @code{Ident}, @code{Inline_Generic}, + @code{Interface_Name}, @code{Passive}, @code{Suppress_All}, + and @code{Volatile}. + Other relevant pragmas include @code{External} and @code{Link_With}. + Some vendor-specific + Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are + recognized, thus + avoiding compiler rejection of units that contain such pragmas; they are not + relevant in a GNAT context and hence are not otherwise implemented. + + @node Implementation-defined attributes + @subsection Implementation-defined attributes + + Analogous to pragmas, the set of attributes may be extended by an + implementation. All GNAT-defined attributes are described in the + @cite{GNAT Reference Manual}, and these include several that are specifically + intended + to correspond to other vendors' Ada 83 attributes. For migrating from VADS, + the attribute @code{VADS_Size} may be useful. For compatibility with DEC + Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and + @code{Type_Class}. + + @node Libraries + @subsection Libraries + @noindent + Vendors may supply libraries to supplement the standard Ada API. If Ada 83 + code uses vendor-specific libraries then there are several ways to manage + this in Ada 95: + @enumerate + @item + If the source code for the libraries (specifications and bodies) are + available, then the libraries can be migrated in the same way as the + application. + @item + If the source code for the specifications but not the bodies are + available, then you can reimplement the bodies. + @item + Some new Ada 95 features obviate the need for library support. For + example most Ada 83 vendors supplied a package for unsigned integers. The + Ada 95 modular type feature is the preferred way to handle this need, so + instead of migrating or reimplementing the unsigned integer package it may + be preferable to retrofit the application using modular types. + @end enumerate + + @node Elaboration order + @subsection Elaboration order + @noindent + The implementation can choose any elaboration order consistent with the unit + dependency relationship. This freedom means that some orders can result in + Program_Error being raised due to an ``Access Before Elaboration'': an attempt + to invoke a subprogram its body has been elaborated, or to instantiate a + generic before the generic body has been elaborated. By default GNAT + attempts to choose a safe order (one that will not encounter access before + elaboration problems) by implicitly inserting Elaborate_All pragmas where + needed. However, this can lead to the creation of elaboration circularities + and a resulting rejection of the program by gnatbind. This issue is + thoroughly described in @ref{Elaboration Order Handling in GNAT}. + In brief, there are several + ways to deal with this situation: + + @itemize @bullet + @item + Modify the program to eliminate the circularities, e.g. by moving + elaboration-time code into explicitly-invoked procedures + @item + Constrain the elaboration order by including explicit @code{Elaborate_Body} or + @code{Elaborate} pragmas, and then inhibit the generation of implicit + @code{Elaborate_All} + pragmas either globally (as an effect of the @option{-gnatE} switch) or locally + (by selectively suppressing elaboration checks via pragma + @code{Suppress(Elaboration_Check)} when it is safe to do so). + @end itemize + + @node Target-specific aspects + @subsection Target-specific aspects + @noindent + Low-level applications need to deal with machine addresses, data + representations, interfacing with assembler code, and similar issues. If + such an Ada 83 application is being ported to different target hardware (for + example where the byte endianness has changed) then you will need to + carefully examine the program logic; the porting effort will heavily depend + on the robustness of the original design. Moreover, Ada 95 is sometimes + incompatible with typical Ada 83 compiler practices regarding implicit + packing, the meaning of the Size attribute, and the size of access values. + GNAT's approach to these issues is described in @ref{Representation Clauses}. + + + @node Compatibility with Other Ada 95 Systems + @section Compatibility with Other Ada 95 Systems + + @noindent + Providing that programs avoid the use of implementation dependent and + implementation defined features of Ada 95, as documented in the Ada 95 + reference manual, there should be a high degree of portability between + GNAT and other Ada 95 systems. The following are specific items which + have proved troublesome in moving GNAT programs to other Ada 95 + compilers, but do not affect porting code to GNAT@. + + @table @asis + @item Ada 83 Pragmas and Attributes + Ada 95 compilers are allowed, but not required, to implement the missing + Ada 83 pragmas and attributes that are no longer defined in Ada 95. + GNAT implements all such pragmas and attributes, eliminating this as + a compatibility concern, but some other Ada 95 compilers reject these + pragmas and attributes. + + @item Special-needs Annexes + GNAT implements the full set of special needs annexes. At the + current time, it is the only Ada 95 compiler to do so. This means that + programs making use of these features may not be portable to other Ada + 95 compilation systems. + + @item Representation Clauses + Some other Ada 95 compilers implement only the minimal set of + representation clauses required by the Ada 95 reference manual. GNAT goes + far beyond this minimal set, as described in the next section. + @end table + + @node Representation Clauses + @section Representation Clauses + + @noindent + The Ada 83 reference manual was quite vague in describing both the minimal + required implementation of representation clauses, and also their precise + effects. The Ada 95 reference manual is much more explicit, but the minimal + set of capabilities required in Ada 95 is quite limited. + + GNAT implements the full required set of capabilities described in the + Ada 95 reference manual, but also goes much beyond this, and in particular + an effort has been made to be compatible with existing Ada 83 usage to the + greatest extent possible. + + A few cases exist in which Ada 83 compiler behavior is incompatible with + requirements in the Ada 95 reference manual. These are instances of + intentional or accidental dependence on specific implementation dependent + characteristics of these Ada 83 compilers. The following is a list of + the cases most likely to arise in existing legacy Ada 83 code. + + @table @asis + @item Implicit Packing + Some Ada 83 compilers allowed a Size specification to cause implicit + packing of an array or record. This could cause expensive implicit + conversions for change of representation in the presence of derived + types, and the Ada design intends to avoid this possibility. + Subsequent AI's were issued to make it clear that such implicit + change of representation in response to a Size clause is inadvisable, + and this recommendation is represented explicitly in the Ada 95 RM + as implementation advice that is followed by GNAT@. + The problem will show up as an error + message rejecting the size clause. The fix is simply to provide + the explicit pragma @code{Pack}, or for more fine tuned control, provide + a Component_Size clause. + + @item Meaning of Size Attribute + The Size attribute in Ada 95 for discrete types is defined as being the + minimal number of bits required to hold values of the type. For example, + on a 32-bit machine, the size of Natural will typically be 31 and not + 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and + some 32 in this situation. This problem will usually show up as a compile + time error, but not always. It is a good idea to check all uses of the + 'Size attribute when porting Ada 83 code. The GNAT specific attribute + Object_Size can provide a useful way of duplicating the behavior of + some Ada 83 compiler systems. + + @item Size of Access Types + A common assumption in Ada 83 code is that an access type is in fact a pointer, + and that therefore it will be the same size as a System.Address value. This + assumption is true for GNAT in most cases with one exception. For the case of + a pointer to an unconstrained array type (where the bounds may vary from one + value of the access type to another), the default is to use a ``fat pointer'', + which is represented as two separate pointers, one to the bounds, and one to + the array. This representation has a number of advantages, including improved + efficiency. However, it may cause some difficulties in porting existing Ada 83 + code which makes the assumption that, for example, pointers fit in 32 bits on + a machine with 32-bit addressing. + + To get around this problem, GNAT also permits the use of ``thin pointers'' for + access types in this case (where the designated type is an unconstrained array + type). These thin pointers are indeed the same size as a System.Address value. + To specify a thin pointer, use a size clause for the type, for example: + + @smallexample @c ada + type X is access all String; + for X'Size use Standard'Address_Size; + @end smallexample + + @noindent + which will cause the type X to be represented using a single pointer. + When using this representation, the bounds are right behind the array. + This representation is slightly less efficient, and does not allow quite + such flexibility in the use of foreign pointers or in using the + Unrestricted_Access attribute to create pointers to non-aliased objects. + But for any standard portable use of the access type it will work in + a functionally correct manner and allow porting of existing code. + Note that another way of forcing a thin pointer representation + is to use a component size clause for the element size in an array, + or a record representation clause for an access field in a record. + @end table + + @node Compatibility with DEC Ada 83 + @section Compatibility with DEC Ada 83 + + @noindent + The VMS version of GNAT fully implements all the pragmas and attributes + provided by DEC Ada 83, as well as providing the standard DEC Ada 83 + libraries, including Starlet. In addition, data layouts and parameter + passing conventions are highly compatible. This means that porting + existing DEC Ada 83 code to GNAT in VMS systems should be easier than + most other porting efforts. The following are some of the most + significant differences between GNAT and DEC Ada 83. + + @table @asis + @item Default floating-point representation + In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83, + it is VMS format. GNAT does implement the necessary pragmas + (Long_Float, Float_Representation) for changing this default. + + @item System + The package System in GNAT exactly corresponds to the definition in the + Ada 95 reference manual, which means that it excludes many of the + DEC Ada 83 extensions. However, a separate package Aux_DEC is provided + that contains the additional definitions, and a special pragma, + Extend_System allows this package to be treated transparently as an + extension of package System. + + @item To_Address + The definitions provided by Aux_DEC are exactly compatible with those + in the DEC Ada 83 version of System, with one exception. + DEC Ada provides the following declarations: + + @smallexample @c ada + TO_ADDRESS (INTEGER) + TO_ADDRESS (UNSIGNED_LONGWORD) + TO_ADDRESS (universal_integer) + @end smallexample + + @noindent + The version of TO_ADDRESS taking a universal integer argument is in fact + an extension to Ada 83 not strictly compatible with the reference manual. + In GNAT, we are constrained to be exactly compatible with the standard, + and this means we cannot provide this capability. In DEC Ada 83, the + point of this definition is to deal with a call like: + + @smallexample @c ada + TO_ADDRESS (16#12777#); + @end smallexample + + @noindent + Normally, according to the Ada 83 standard, one would expect this to be + ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms + of TO_ADDRESS@. However, in DEC Ada 83, there is no ambiguity, since the + definition using universal_integer takes precedence. + + In GNAT, since the version with universal_integer cannot be supplied, it is + not possible to be 100% compatible. Since there are many programs using + numeric constants for the argument to TO_ADDRESS, the decision in GNAT was + to change the name of the function in the UNSIGNED_LONGWORD case, so the + declarations provided in the GNAT version of AUX_Dec are: + + @smallexample @c ada + function To_Address (X : Integer) return Address; + pragma Pure_Function (To_Address); + + function To_Address_Long (X : Unsigned_Longword) + return Address; + pragma Pure_Function (To_Address_Long); + @end smallexample + + @noindent + This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must + change the name to TO_ADDRESS_LONG@. + + @item Task_Id values + The Task_Id values assigned will be different in the two systems, and GNAT + does not provide a specified value for the Task_Id of the environment task, + which in GNAT is treated like any other declared task. + @end table + + For full details on these and other less significant compatibility issues, + see appendix E of the Digital publication entitled @cite{DEC Ada, Technical + Overview and Comparison on DIGITAL Platforms}. + + For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and + attributes are recognized, although only a subset of them can sensibly + be implemented. The description of pragmas in this reference manual + indicates whether or not they are applicable to non-VMS systems. + + + + @ifset unw + @node Microsoft Windows Topics + @appendix Microsoft Windows Topics + @cindex Windows NT + @cindex Windows 95 + @cindex Windows 98 + + @noindent + This chapter describes topics that are specific to the Microsoft Windows + platforms (NT, 95 and 98). + + @menu + * Using GNAT on Windows:: + * Using a network installation of GNAT:: + * CONSOLE and WINDOWS subsystems:: + * Temporary Files:: + * Mixed-Language Programming on Windows:: + * Windows Calling Conventions:: + * Introduction to Dynamic Link Libraries (DLLs):: + * Using DLLs with GNAT:: + * Building DLLs with GNAT:: + * GNAT and Windows Resources:: + * Debugging a DLL:: + * GNAT and COM/DCOM Objects:: + @end menu + + @node Using GNAT on Windows + @section Using GNAT on Windows + + @noindent + One of the strengths of the GNAT technology is that its tool set + (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the + @code{gdb} debugger, etc.) is used in the same way regardless of the + platform. + + On Windows this tool set is complemented by a number of Microsoft-specific + tools that have been provided to facilitate interoperability with Windows + when this is required. With these tools: + + @itemize @bullet + + @item + You can build applications using the @code{CONSOLE} or @code{WINDOWS} + subsystems. + + @item + You can use any Dynamically Linked Library (DLL) in your Ada code (both + relocatable and non-relocatable DLLs are supported). + + @item + You can build Ada DLLs for use in other applications. These applications + can be written in a language other than Ada (e.g., C, C++, etc). Again both + relocatable and non-relocatable Ada DLLs are supported. + + @item + You can include Windows resources in your Ada application. + + @item + You can use or create COM/DCOM objects. + @end itemize + + @noindent + Immediately below are listed all known general GNAT-for-Windows restrictions. + Other restrictions about specific features like Windows Resources and DLLs + are listed in separate sections below. + + @itemize @bullet + + @item + It is not possible to use @code{GetLastError} and @code{SetLastError} + when tasking, protected records, or exceptions are used. In these + cases, in order to implement Ada semantics, the GNAT run-time system + calls certain Win32 routines that set the last error variable to 0 upon + success. It should be possible to use @code{GetLastError} and + @code{SetLastError} when tasking, protected record, and exception + features are not used, but it is not guaranteed to work. + @end itemize + + @node Using a network installation of GNAT + @section Using a network installation of GNAT + + @noindent + Make sure the system on which GNAT is installed is accessible from the + current machine, i.e. the install location is shared over the network. + Shared resources are accessed on Windows by means of UNC paths, which + have the format @code{\\server\sharename\path} + + In order to use such a network installation, simply add the UNC path of the + @file{bin} directory of your GNAT installation in front of your PATH. For + example, if GNAT is installed in @file{\GNAT} directory of a share location + called @file{c-drive} on a machine @file{LOKI}, the following command will + make it available: + + @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%} + + Be aware that every compilation using the network installation results in the + transfer of large amounts of data across the network and will likely cause + serious performance penalty. + + @node CONSOLE and WINDOWS subsystems + @section CONSOLE and WINDOWS subsystems + @cindex CONSOLE Subsystem + @cindex WINDOWS Subsystem + @cindex -mwindows + + @noindent + There are two main subsystems under Windows. The @code{CONSOLE} subsystem + (which is the default subsystem) will always create a console when + launching the application. This is not something desirable when the + application has a Windows GUI. To get rid of this console the + application must be using the @code{WINDOWS} subsystem. To do so + the @option{-mwindows} linker option must be specified. + + @smallexample + $ gnatmake winprog -largs -mwindows + @end smallexample + + @node Temporary Files + @section Temporary Files + @cindex Temporary files + + @noindent + It is possible to control where temporary files gets created by setting + the TMP environment variable. The file will be created: + + @itemize + @item Under the directory pointed to by the TMP environment variable if + this directory exists. + + @item Under c:\temp, if the TMP environment variable is not set (or not + pointing to a directory) and if this directory exists. + + @item Under the current working directory otherwise. + @end itemize + + @noindent + This allows you to determine exactly where the temporary + file will be created. This is particularly useful in networked + environments where you may not have write access to some + directories. + + @node Mixed-Language Programming on Windows + @section Mixed-Language Programming on Windows + + @noindent + Developing pure Ada applications on Windows is no different than on + other GNAT-supported platforms. However, when developing or porting an + application that contains a mix of Ada and C/C++, the choice of your + Windows C/C++ development environment conditions your overall + interoperability strategy. + + If you use @code{gcc} to compile the non-Ada part of your application, + there are no Windows-specific restrictions that affect the overall + interoperability with your Ada code. If you plan to use + Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of + the following limitations: + + @itemize @bullet + @item + You cannot link your Ada code with an object or library generated with + Microsoft tools if these use the @code{.tls} section (Thread Local + Storage section) since the GNAT linker does not yet support this section. + + @item + You cannot link your Ada code with an object or library generated with + Microsoft tools if these use I/O routines other than those provided in + the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time + uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O + libraries can cause a conflict with @code{msvcrt.dll} services. For + instance Visual C++ I/O stream routines conflict with those in + @code{msvcrt.dll}. + @end itemize + + @noindent + If you do want to use the Microsoft tools for your non-Ada code and hit one + of the above limitations, you have two choices: + + @enumerate + @item + Encapsulate your non Ada code in a DLL to be linked with your Ada + application. In this case, use the Microsoft or whatever environment to + build the DLL and use GNAT to build your executable + (@pxref{Using DLLs with GNAT}). + + @item + Or you can encapsulate your Ada code in a DLL to be linked with the + other part of your application. In this case, use GNAT to build the DLL + (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever + environment to build your executable. + @end enumerate + + @node Windows Calling Conventions + @section Windows Calling Conventions + @findex Stdcall + @findex APIENTRY + + @menu + * C Calling Convention:: + * Stdcall Calling Convention:: + * DLL Calling Convention:: + @end menu + + @noindent + When a subprogram @code{F} (caller) calls a subprogram @code{G} + (callee), there are several ways to push @code{G}'s parameters on the + stack and there are several possible scenarios to clean up the stack + upon @code{G}'s return. A calling convention is an agreed upon software + protocol whereby the responsibilities between the caller (@code{F}) and + the callee (@code{G}) are clearly defined. Several calling conventions + are available for Windows: + + @itemize @bullet + @item + @code{C} (Microsoft defined) + + @item + @code{Stdcall} (Microsoft defined) + + @item + @code{DLL} (GNAT specific) + @end itemize + + @node C Calling Convention + @subsection @code{C} Calling Convention + + @noindent + This is the default calling convention used when interfacing to C/C++ + routines compiled with either @code{gcc} or Microsoft Visual C++. + + In the @code{C} calling convention subprogram parameters are pushed on the + stack by the caller from right to left. The caller itself is in charge of + cleaning up the stack after the call. In addition, the name of a routine + with @code{C} calling convention is mangled by adding a leading underscore. + + The name to use on the Ada side when importing (or exporting) a routine + with @code{C} calling convention is the name of the routine. For + instance the C function: + + @smallexample + int get_val (long); + @end smallexample + + @noindent + should be imported from Ada as follows: + + @smallexample @c ada + @group + function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; + pragma Import (C, Get_Val, External_Name => "get_val"); + @end group + @end smallexample + + @noindent + Note that in this particular case the @code{External_Name} parameter could + have been omitted since, when missing, this parameter is taken to be the + name of the Ada entity in lower case. When the @code{Link_Name} parameter + is missing, as in the above example, this parameter is set to be the + @code{External_Name} with a leading underscore. + + When importing a variable defined in C, you should always use the @code{C} + calling convention unless the object containing the variable is part of a + DLL (in which case you should use the @code{DLL} calling convention, + @pxref{DLL Calling Convention}). + + @node Stdcall Calling Convention + @subsection @code{Stdcall} Calling Convention + + @noindent + This convention, which was the calling convention used for Pascal + programs, is used by Microsoft for all the routines in the Win32 API for + efficiency reasons. It must be used to import any routine for which this + convention was specified. + + In the @code{Stdcall} calling convention subprogram parameters are pushed + on the stack by the caller from right to left. The callee (and not the + caller) is in charge of cleaning the stack on routine exit. In addition, + the name of a routine with @code{Stdcall} calling convention is mangled by + adding a leading underscore (as for the @code{C} calling convention) and a + trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in + bytes) of the parameters passed to the routine. + + The name to use on the Ada side when importing a C routine with a + @code{Stdcall} calling convention is the name of the C routine. The leading + underscore and trailing @code{@@}@code{@i{nn}} are added automatically by + the compiler. For instance the Win32 function: + + @smallexample + @b{APIENTRY} int get_val (long); + @end smallexample + + @noindent + should be imported from Ada as follows: + + @smallexample @c ada + @group + function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; + pragma Import (Stdcall, Get_Val); + -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4" + @end group + @end smallexample + + @noindent + As for the @code{C} calling convention, when the @code{External_Name} + parameter is missing, it is taken to be the name of the Ada entity in lower + case. If instead of writing the above import pragma you write: + + @smallexample @c ada + @group + function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; + pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val"); + @end group + @end smallexample + + @noindent + then the imported routine is @code{_retrieve_val@@4}. However, if instead + of specifying the @code{External_Name} parameter you specify the + @code{Link_Name} as in the following example: + + @smallexample @c ada + @group + function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; + pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val"); + @end group + @end smallexample + + @noindent + then the imported routine is @code{retrieve_val@@4}, that is, there is no + trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always + added at the end of the @code{Link_Name} by the compiler. + + @noindent + Note, that in some special cases a DLL's entry point name lacks a trailing + @code{@@}@code{@i{nn}} while the exported name generated for a call has it. + The @code{gnatdll} tool, which creates the import library for the DLL, is able + to handle those cases (see the description of the switches in + @pxref{Using gnatdll} section). + + @node DLL Calling Convention + @subsection @code{DLL} Calling Convention + + @noindent + This convention, which is GNAT-specific, must be used when you want to + import in Ada a variables defined in a DLL. For functions and procedures + this convention is equivalent to the @code{Stdcall} convention. As an + example, if a DLL contains a variable defined as: + + @smallexample + int my_var; + @end smallexample + + @noindent + then, to access this variable from Ada you should write: + + @smallexample @c ada + @group + My_Var : Interfaces.C.int; + pragma Import (DLL, My_Var); + @end group + @end smallexample + + The remarks concerning the @code{External_Name} and @code{Link_Name} + parameters given in the previous sections equally apply to the @code{DLL} + calling convention. + + @node Introduction to Dynamic Link Libraries (DLLs) + @section Introduction to Dynamic Link Libraries (DLLs) + @findex DLL + + @noindent + A Dynamically Linked Library (DLL) is a library that can be shared by + several applications running under Windows. A DLL can contain any number of + routines and variables. + + One advantage of DLLs is that you can change and enhance them without + forcing all the applications that depend on them to be relinked or + recompiled. However, you should be aware than all calls to DLL routines are + slower since, as you will understand below, such calls are indirect. + + To illustrate the remainder of this section, suppose that an application + wants to use the services of a DLL @file{API.dll}. To use the services + provided by @file{API.dll} you must statically link against an import + library which contains a jump table with an entry for each routine and + variable exported by the DLL. In the Microsoft world this import library is + called @file{API.lib}. When using GNAT this import library is called either + @file{libAPI.a} or @file{libapi.a} (names are case insensitive). + + After you have statically linked your application with the import library + and you run your application, here is what happens: + + @enumerate + @item + Your application is loaded into memory. + + @item + The DLL @file{API.dll} is mapped into the address space of your + application. This means that: + + @itemize @bullet + @item + The DLL will use the stack of the calling thread. + + @item + The DLL will use the virtual address space of the calling process. + + @item + The DLL will allocate memory from the virtual address space of the calling + process. + + @item + Handles (pointers) can be safely exchanged between routines in the DLL + routines and routines in the application using the DLL. + @end itemize + + @item + The entries in the @file{libAPI.a} or @file{API.lib} jump table which is + part of your application are initialized with the addresses of the routines + and variables in @file{API.dll}. + + @item + If present in @file{API.dll}, routines @code{DllMain} or + @code{DllMainCRTStartup} are invoked. These routines typically contain + the initialization code needed for the well-being of the routines and + variables exported by the DLL. + @end enumerate + + @noindent + There is an additional point which is worth mentioning. In the Windows + world there are two kind of DLLs: relocatable and non-relocatable + DLLs. Non-relocatable DLLs can only be loaded at a very specific address + in the target application address space. If the addresses of two + non-relocatable DLLs overlap and these happen to be used by the same + application, a conflict will occur and the application will run + incorrectly. Hence, when possible, it is always preferable to use and + build relocatable DLLs. Both relocatable and non-relocatable DLLs are + supported by GNAT. Note that the @option{-s} linker option (see GNU Linker + User's Guide) removes the debugging symbols from the DLL but the DLL can + still be relocated. + + As a side note, an interesting difference between Microsoft DLLs and + Unix shared libraries, is the fact that on most Unix systems all public + routines are exported by default in a Unix shared library, while under + Windows the exported routines must be listed explicitly in a definition + file (@pxref{The Definition File}). + + @node Using DLLs with GNAT + @section Using DLLs with GNAT + + @menu + * Creating an Ada Spec for the DLL Services:: + * Creating an Import Library:: + @end menu + + @noindent + To use the services of a DLL, say @file{API.dll}, in your Ada application + you must have: + + @enumerate + @item + The Ada spec for the routines and/or variables you want to access in + @file{API.dll}. If not available this Ada spec must be built from the C/C++ + header files provided with the DLL. + + @item + The import library (@file{libAPI.a} or @file{API.lib}). As previously + mentioned an import library is a statically linked library containing the + import table which will be filled at load time to point to the actual + @file{API.dll} routines. Sometimes you don't have an import library for the + DLL you want to use. The following sections will explain how to build one. + + @item + The actual DLL, @file{API.dll}. + @end enumerate + + @noindent + Once you have all the above, to compile an Ada application that uses the + services of @file{API.dll} and whose main subprogram is @code{My_Ada_App}, + you simply issue the command + + @smallexample + $ gnatmake my_ada_app -largs -lAPI + @end smallexample + + @noindent + The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command + tells the GNAT linker to look first for a library named @file{API.lib} + (Microsoft-style name) and if not found for a library named @file{libAPI.a} + (GNAT-style name). Note that if the Ada package spec for @file{API.dll} + contains the following pragma + + @smallexample @c ada + pragma Linker_Options ("-lAPI"); + @end smallexample + + @noindent + you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake} + command. + + If any one of the items above is missing you will have to create it + yourself. The following sections explain how to do so using as an + example a fictitious DLL called @file{API.dll}. + + @node Creating an Ada Spec for the DLL Services + @subsection Creating an Ada Spec for the DLL Services + + @noindent + A DLL typically comes with a C/C++ header file which provides the + definitions of the routines and variables exported by the DLL. The Ada + equivalent of this header file is a package spec that contains definitions + for the imported entities. If the DLL you intend to use does not come with + an Ada spec you have to generate one such spec yourself. For example if + the header file of @file{API.dll} is a file @file{api.h} containing the + following two definitions: + + @smallexample + @group + @cartouche + int some_var; + int get (char *); + @end cartouche + @end group + @end smallexample + + @noindent + then the equivalent Ada spec could be: + + @smallexample @c ada + @group + @cartouche + with Interfaces.C.Strings; + package API is + use Interfaces; + + Some_Var : C.int; + function Get (Str : C.Strings.Chars_Ptr) return C.int; + + private + pragma Import (C, Get); + pragma Import (DLL, Some_Var); + end API; + @end cartouche + @end group + @end smallexample + + @noindent + Note that a variable is @strong{always imported with a DLL convention}. A + function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For + subprograms, the @code{DLL} convention is a synonym of @code{Stdcall} + (@pxref{Windows Calling Conventions}). + + @node Creating an Import Library + @subsection Creating an Import Library + @cindex Import library + + @menu + * The Definition File:: + * GNAT-Style Import Library:: + * Microsoft-Style Import Library:: + @end menu + + @noindent + If a Microsoft-style import library @file{API.lib} or a GNAT-style + import library @file{libAPI.a} is available with @file{API.dll} you + can skip this section. Otherwise read on. + + @node The Definition File + @subsubsection The Definition File + @cindex Definition file + @findex .def + + @noindent + As previously mentioned, and unlike Unix systems, the list of symbols + that are exported from a DLL must be provided explicitly in Windows. + The main goal of a definition file is precisely that: list the symbols + exported by a DLL. A definition file (usually a file with a @code{.def} + suffix) has the following structure: + + @smallexample + @group + @cartouche + [LIBRARY @i{name}] + [DESCRIPTION @i{string}] + EXPORTS + @i{symbol1} + @i{symbol2} + ... + @end cartouche + @end group + @end smallexample + + @table @code + @item LIBRARY @i{name} + This section, which is optional, gives the name of the DLL. + + @item DESCRIPTION @i{string} + This section, which is optional, gives a description string that will be + embedded in the import library. + + @item EXPORTS + This section gives the list of exported symbols (procedures, functions or + variables). For instance in the case of @file{API.dll} the @code{EXPORTS} + section of @file{API.def} looks like: + + @smallexample + @group + @cartouche + EXPORTS + some_var + get + @end cartouche + @end group + @end smallexample + @end table + + @noindent + Note that you must specify the correct suffix (@code{@@}@code{@i{nn}}) + (@pxref{Windows Calling Conventions}) for a Stdcall + calling convention function in the exported symbols list. + + @noindent + There can actually be other sections in a definition file, but these + sections are not relevant to the discussion at hand. + + @node GNAT-Style Import Library + @subsubsection GNAT-Style Import Library + + @noindent + To create a static import library from @file{API.dll} with the GNAT tools + you should proceed as follows: + + @enumerate + @item + Create the definition file @file{API.def} (@pxref{The Definition File}). + For that use the @code{dll2def} tool as follows: + + @smallexample + $ dll2def API.dll > API.def + @end smallexample + + @noindent + @code{dll2def} is a very simple tool: it takes as input a DLL and prints + to standard output the list of entry points in the DLL. Note that if + some routines in the DLL have the @code{Stdcall} convention + (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn} + suffix then you'll have to edit @file{api.def} to add it. + + @noindent + Here are some hints to find the right @code{@@}@i{nn} suffix. + + @enumerate + @item + If you have the Microsoft import library (.lib), it is possible to get + the right symbols by using Microsoft @code{dumpbin} tool (see the + corresponding Microsoft documentation for further details). + + @smallexample + $ dumpbin /exports api.lib + @end smallexample + + @item + If you have a message about a missing symbol at link time the compiler + tells you what symbol is expected. You just have to go back to the + definition file and add the right suffix. + @end enumerate + + @item + Build the import library @code{libAPI.a}, using @code{gnatdll} + (@pxref{Using gnatdll}) as follows: + + @smallexample + $ gnatdll -e API.def -d API.dll + @end smallexample + + @noindent + @code{gnatdll} takes as input a definition file @file{API.def} and the + name of the DLL containing the services listed in the definition file + @file{API.dll}. The name of the static import library generated is + computed from the name of the definition file as follows: if the + definition file name is @i{xyz}@code{.def}, the import library name will + be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option + @option{-e} could have been removed because the name of the definition + file (before the ``@code{.def}'' suffix) is the same as the name of the + DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}). + @end enumerate + + @node Microsoft-Style Import Library + @subsubsection Microsoft-Style Import Library + + @noindent + With GNAT you can either use a GNAT-style or Microsoft-style import + library. A Microsoft import library is needed only if you plan to make an + Ada DLL available to applications developed with Microsoft + tools (@pxref{Mixed-Language Programming on Windows}). + + To create a Microsoft-style import library for @file{API.dll} you + should proceed as follows: + + @enumerate + @item + Create the definition file @file{API.def} from the DLL. For this use either + the @code{dll2def} tool as described above or the Microsoft @code{dumpbin} + tool (see the corresponding Microsoft documentation for further details). + + @item + Build the actual import library using Microsoft's @code{lib} utility: + + @smallexample + $ lib -machine:IX86 -def:API.def -out:API.lib + @end smallexample + + @noindent + If you use the above command the definition file @file{API.def} must + contain a line giving the name of the DLL: + + @smallexample + LIBRARY "API" + @end smallexample + + @noindent + See the Microsoft documentation for further details about the usage of + @code{lib}. + @end enumerate + + @node Building DLLs with GNAT + @section Building DLLs with GNAT + @cindex DLLs, building + + @menu + * Limitations When Using Ada DLLs from Ada:: + * Exporting Ada Entities:: + * Ada DLLs and Elaboration:: + * Ada DLLs and Finalization:: + * Creating a Spec for Ada DLLs:: + * Creating the Definition File:: + * Using gnatdll:: + @end menu + + @noindent + This section explains how to build DLLs containing Ada code. These DLLs + will be referred to as Ada DLLs in the remainder of this section. + + The steps required to build an Ada DLL that is to be used by Ada as well as + non-Ada applications are as follows: + + @enumerate + @item + You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or + @code{Stdcall} calling convention to avoid any Ada name mangling for the + entities exported by the DLL (@pxref{Exporting Ada Entities}). You can + skip this step if you plan to use the Ada DLL only from Ada applications. + + @item + Your Ada code must export an initialization routine which calls the routine + @code{adainit} generated by @code{gnatbind} to perform the elaboration of + the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization + routine exported by the Ada DLL must be invoked by the clients of the DLL + to initialize the DLL. + + @item + When useful, the DLL should also export a finalization routine which calls + routine @code{adafinal} generated by @code{gnatbind} to perform the + finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}). + The finalization routine exported by the Ada DLL must be invoked by the + clients of the DLL when the DLL services are no further needed. + + @item + You must provide a spec for the services exported by the Ada DLL in each + of the programming languages to which you plan to make the DLL available. + + @item + You must provide a definition file listing the exported entities + (@pxref{The Definition File}). + + @item + Finally you must use @code{gnatdll} to produce the DLL and the import + library (@pxref{Using gnatdll}). + @end enumerate + + @node Limitations When Using Ada DLLs from Ada + @subsection Limitations When Using Ada DLLs from Ada + + @noindent + When using Ada DLLs from Ada applications there is a limitation users + should be aware of. Because on Windows the GNAT run time is not in a DLL of + its own, each Ada DLL includes a part of the GNAT run time. Specifically, + each Ada DLL includes the services of the GNAT run time that are necessary + to the Ada code inside the DLL. As a result, when an Ada program uses an + Ada DLL there are two independent GNAT run times: one in the Ada DLL and + one in the main program. + + It is therefore not possible to exchange GNAT run-time objects between the + Ada DLL and the main Ada program. Example of GNAT run-time objects are file + handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects + types, etc. + + It is completely safe to exchange plain elementary, array or record types, + Windows object handles, etc. + + @node Exporting Ada Entities + @subsection Exporting Ada Entities + @cindex Export table + + @noindent + Building a DLL is a way to encapsulate a set of services usable from any + application. As a result, the Ada entities exported by a DLL should be + exported with the @code{C} or @code{Stdcall} calling conventions to avoid + any Ada name mangling. Please note that the @code{Stdcall} convention + should only be used for subprograms, not for variables. As an example here + is an Ada package @code{API}, spec and body, exporting two procedures, a + function, and a variable: + + @smallexample @c ada + @group + @cartouche + with Interfaces.C; use Interfaces; + package API is + Count : C.int := 0; + function Factorial (Val : C.int) return C.int; + + procedure Initialize_API; + procedure Finalize_API; + -- Initialization & Finalization routines. More in the next section. + private + pragma Export (C, Initialize_API); + pragma Export (C, Finalize_API); + pragma Export (C, Count); + pragma Export (C, Factorial); + end API; + @end cartouche + @end group + @end smallexample + + @smallexample @c ada + @group + @cartouche + package body API is + function Factorial (Val : C.int) return C.int is + Fact : C.int := 1; + begin + Count := Count + 1; + for K in 1 .. Val loop + Fact := Fact * K; + end loop; + return Fact; + end Factorial; + + procedure Initialize_API is + procedure Adainit; + pragma Import (C, Adainit); + begin + Adainit; + end Initialize_API; + + procedure Finalize_API is + procedure Adafinal; + pragma Import (C, Adafinal); + begin + Adafinal; + end Finalize_API; + end API; + @end cartouche + @end group + @end smallexample + + @noindent + If the Ada DLL you are building will only be used by Ada applications + you do not have to export Ada entities with a @code{C} or @code{Stdcall} + convention. As an example, the previous package could be written as + follows: + + @smallexample @c ada + @group + @cartouche + package API is + Count : Integer := 0; + function Factorial (Val : Integer) return Integer; + + procedure Initialize_API; + procedure Finalize_API; + -- Initialization and Finalization routines. + end API; + @end cartouche + @end group + @end smallexample + + @smallexample @c ada + @group + @cartouche + package body API is + function Factorial (Val : Integer) return Integer is + Fact : Integer := 1; + begin + Count := Count + 1; + for K in 1 .. Val loop + Fact := Fact * K; + end loop; + return Fact; + end Factorial; + + ... + -- The remainder of this package body is unchanged. + end API; + @end cartouche + @end group + @end smallexample + + @noindent + Note that if you do not export the Ada entities with a @code{C} or + @code{Stdcall} convention you will have to provide the mangled Ada names + in the definition file of the Ada DLL + (@pxref{Creating the Definition File}). + + @node Ada DLLs and Elaboration + @subsection Ada DLLs and Elaboration + @cindex DLLs and elaboration + + @noindent + The DLL that you are building contains your Ada code as well as all the + routines in the Ada library that are needed by it. The first thing a + user of your DLL must do is elaborate the Ada code + (@pxref{Elaboration Order Handling in GNAT}). + + To achieve this you must export an initialization routine + (@code{Initialize_API} in the previous example), which must be invoked + before using any of the DLL services. This elaboration routine must call + the Ada elaboration routine @code{adainit} generated by the GNAT binder + (@pxref{Binding with Non-Ada Main Programs}). See the body of + @code{Initialize_Api} for an example. Note that the GNAT binder is + automatically invoked during the DLL build process by the @code{gnatdll} + tool (@pxref{Using gnatdll}). + + When a DLL is loaded, Windows systematically invokes a routine called + @code{DllMain}. It would therefore be possible to call @code{adainit} + directly from @code{DllMain} without having to provide an explicit + initialization routine. Unfortunately, it is not possible to call + @code{adainit} from the @code{DllMain} if your program has library level + tasks because access to the @code{DllMain} entry point is serialized by + the system (that is, only a single thread can execute ``through'' it at a + time), which means that the GNAT run time will deadlock waiting for the + newly created task to complete its initialization. + + @node Ada DLLs and Finalization + @subsection Ada DLLs and Finalization + @cindex DLLs and finalization + + @noindent + When the services of an Ada DLL are no longer needed, the client code should + invoke the DLL finalization routine, if available. The DLL finalization + routine is in charge of releasing all resources acquired by the DLL. In the + case of the Ada code contained in the DLL, this is achieved by calling + routine @code{adafinal} generated by the GNAT binder + (@pxref{Binding with Non-Ada Main Programs}). + See the body of @code{Finalize_Api} for an + example. As already pointed out the GNAT binder is automatically invoked + during the DLL build process by the @code{gnatdll} tool + (@pxref{Using gnatdll}). + + @node Creating a Spec for Ada DLLs + @subsection Creating a Spec for Ada DLLs + + @noindent + To use the services exported by the Ada DLL from another programming + language (e.g. C), you have to translate the specs of the exported Ada + entities in that language. For instance in the case of @code{API.dll}, + the corresponding C header file could look like: + + @smallexample + @group + @cartouche + extern int *_imp__count; + #define count (*_imp__count) + int factorial (int); + @end cartouche + @end group + @end smallexample + + @noindent + It is important to understand that when building an Ada DLL to be used by + other Ada applications, you need two different specs for the packages + contained in the DLL: one for building the DLL and the other for using + the DLL. This is because the @code{DLL} calling convention is needed to + use a variable defined in a DLL, but when building the DLL, the variable + must have either the @code{Ada} or @code{C} calling convention. As an + example consider a DLL comprising the following package @code{API}: + + @smallexample @c ada + @group + @cartouche + package API is + Count : Integer := 0; + ... + -- Remainder of the package omitted. + end API; + @end cartouche + @end group + @end smallexample + + @noindent + After producing a DLL containing package @code{API}, the spec that + must be used to import @code{API.Count} from Ada code outside of the + DLL is: + + @smallexample @c ada + @group + @cartouche + package API is + Count : Integer; + pragma Import (DLL, Count); + end API; + @end cartouche + @end group + @end smallexample + + @node Creating the Definition File + @subsection Creating the Definition File + + @noindent + The definition file is the last file needed to build the DLL. It lists + the exported symbols. As an example, the definition file for a DLL + containing only package @code{API} (where all the entities are exported + with a @code{C} calling convention) is: + + @smallexample + @group + @cartouche + EXPORTS + count + factorial + finalize_api + initialize_api + @end cartouche + @end group + @end smallexample + + @noindent + If the @code{C} calling convention is missing from package @code{API}, + then the definition file contains the mangled Ada names of the above + entities, which in this case are: + + @smallexample + @group + @cartouche + EXPORTS + api__count + api__factorial + api__finalize_api + api__initialize_api + @end cartouche + @end group + @end smallexample + + @node Using gnatdll + @subsection Using @code{gnatdll} + @findex gnatdll + + @menu + * gnatdll Example:: + * gnatdll behind the Scenes:: + * Using dlltool:: + @end menu + + @noindent + @code{gnatdll} is a tool to automate the DLL build process once all the Ada + and non-Ada sources that make up your DLL have been compiled. + @code{gnatdll} is actually in charge of two distinct tasks: build the + static import library for the DLL and the actual DLL. The form of the + @code{gnatdll} command is + + @smallexample + @cartouche + $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}] + @end cartouche + @end smallexample + + @noindent + where @i{list-of-files} is a list of ALI and object files. The object + file list must be the exact list of objects corresponding to the non-Ada + sources whose services are to be included in the DLL. The ALI file list + must be the exact list of ALI files for the corresponding Ada sources + whose services are to be included in the DLL. If @i{list-of-files} is + missing, only the static import library is generated. + + @noindent + You may specify any of the following switches to @code{gnatdll}: + + @table @code + @item -a[@var{address}] + @cindex @option{-a} (@code{gnatdll}) + Build a non-relocatable DLL at @var{address}. If @var{address} is not + specified the default address @var{0x11000000} will be used. By default, + when this switch is missing, @code{gnatdll} builds relocatable DLL. We + advise the reader to build relocatable DLL. + + @item -b @var{address} + @cindex @option{-b} (@code{gnatdll}) + Set the relocatable DLL base address. By default the address is + @var{0x11000000}. + + @item -bargs @var{opts} + @cindex @option{-bargs} (@code{gnatdll}) + Binder options. Pass @var{opts} to the binder. + + @item -d @var{dllfile} + @cindex @option{-d} (@code{gnatdll}) + @var{dllfile} is the name of the DLL. This switch must be present for + @code{gnatdll} to do anything. The name of the generated import library is + obtained algorithmically from @var{dllfile} as shown in the following + example: if @var{dllfile} is @code{xyz.dll}, the import library name is + @code{libxyz.a}. The name of the definition file to use (if not specified + by option @option{-e}) is obtained algorithmically from @var{dllfile} + as shown in the following example: + if @var{dllfile} is @code{xyz.dll}, the definition + file used is @code{xyz.def}. + + @item -e @var{deffile} + @cindex @option{-e} (@code{gnatdll}) + @var{deffile} is the name of the definition file. + + @item -g + @cindex @option{-g} (@code{gnatdll}) + Generate debugging information. This information is stored in the object + file and copied from there to the final DLL file by the linker, + where it can be read by the debugger. You must use the + @option{-g} switch if you plan on using the debugger or the symbolic + stack traceback. + + @item -h + @cindex @option{-h} (@code{gnatdll}) + Help mode. Displays @code{gnatdll} switch usage information. + + @item -Idir + @cindex @option{-I} (@code{gnatdll}) + Direct @code{gnatdll} to search the @var{dir} directory for source and + object files needed to build the DLL. + (@pxref{Search Paths and the Run-Time Library (RTL)}). + + @item -k + @cindex @option{-k} (@code{gnatdll}) + Removes the @code{@@}@i{nn} suffix from the import library's exported + names. You must specified this option if you want to use a + @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix + has been removed. This is the case for most of the Windows NT DLL for + example. This option has no effect when @option{-n} option is specified. + + @item -l @var{file} + @cindex @option{-l} (@code{gnatdll}) + The list of ALI and object files used to build the DLL are listed in + @var{file}, instead of being given in the command line. Each line in + @var{file} contains the name of an ALI or object file. + + @item -n + @cindex @option{-n} (@code{gnatdll}) + No Import. Do not create the import library. + + @item -q + @cindex @option{-q} (@code{gnatdll}) + Quiet mode. Do not display unnecessary messages. + + @item -v + @cindex @option{-v} (@code{gnatdll}) + Verbose mode. Display extra information. + + @item -largs @var{opts} + @cindex @option{-largs} (@code{gnatdll}) + Linker options. Pass @var{opts} to the linker. + @end table + + @node gnatdll Example + @subsubsection @code{gnatdll} Example + + @noindent + As an example the command to build a relocatable DLL from @file{api.adb} + once @file{api.adb} has been compiled and @file{api.def} created is + + @smallexample + $ gnatdll -d api.dll api.ali + @end smallexample + + @noindent + The above command creates two files: @file{libapi.a} (the import + library) and @file{api.dll} (the actual DLL). If you want to create + only the DLL, just type: + + @smallexample + $ gnatdll -d api.dll -n api.ali + @end smallexample + + @noindent + Alternatively if you want to create just the import library, type: + + @smallexample + $ gnatdll -d api.dll + @end smallexample + + @node gnatdll behind the Scenes + @subsubsection @code{gnatdll} behind the Scenes + + @noindent + This section details the steps involved in creating a DLL. @code{gnatdll} + does these steps for you. Unless you are interested in understanding what + goes on behind the scenes, you should skip this section. + + We use the previous example of a DLL containing the Ada package @code{API}, + to illustrate the steps necessary to build a DLL. The starting point is a + set of objects that will make up the DLL and the corresponding ALI + files. In the case of this example this means that @file{api.o} and + @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does + the following: + + @enumerate + @item + @code{gnatdll} builds the base file (@file{api.base}). A base file gives + the information necessary to generate relocation information for the + DLL. + + @smallexample + @group + $ gnatbind -n api + $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base + @end group + @end smallexample + + @noindent + In addition to the base file, the @code{gnatlink} command generates an + output file @file{api.jnk} which can be discarded. The @option{-mdll} switch + asks @code{gnatlink} to generate the routines @code{DllMain} and + @code{DllMainCRTStartup} that are called by the Windows loader when the DLL + is loaded into memory. + + @item + @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the + export table (@file{api.exp}). The export table contains the relocation + information in a form which can be used during the final link to ensure + that the Windows loader is able to place the DLL anywhere in memory. + + @smallexample + @group + $ dlltool --dllname api.dll --def api.def --base-file api.base \ + --output-exp api.exp + @end group + @end smallexample + + @item + @code{gnatdll} builds the base file using the new export table. Note that + @code{gnatbind} must be called once again since the binder generated file + has been deleted during the previous call to @code{gnatlink}. + + @smallexample + @group + $ gnatbind -n api + $ gnatlink api -o api.jnk api.exp -mdll + -Wl,--base-file,api.base + @end group + @end smallexample + + @item + @code{gnatdll} builds the new export table using the new base file and + generates the DLL import library @file{libAPI.a}. + + @smallexample + @group + $ dlltool --dllname api.dll --def api.def --base-file api.base \ + --output-exp api.exp --output-lib libAPI.a + @end group + @end smallexample + + @item + Finally @code{gnatdll} builds the relocatable DLL using the final export + table. + + @smallexample + @group + $ gnatbind -n api + $ gnatlink api api.exp -o api.dll -mdll + @end group + @end smallexample + @end enumerate + + @node Using dlltool + @subsubsection Using @code{dlltool} + + @noindent + @code{dlltool} is the low-level tool used by @code{gnatdll} to build + DLLs and static import libraries. This section summarizes the most + common @code{dlltool} switches. The form of the @code{dlltool} command + is + + @smallexample + $ dlltool [@var{switches}] + @end smallexample + + @noindent + @code{dlltool} switches include: + + @table @option + @item --base-file @var{basefile} + @cindex @option{--base-file} (@command{dlltool}) + Read the base file @var{basefile} generated by the linker. This switch + is used to create a relocatable DLL. + + @item --def @var{deffile} + @cindex @option{--def} (@command{dlltool}) + Read the definition file. + + @item --dllname @var{name} + @cindex @option{--dllname} (@command{dlltool}) + Gives the name of the DLL. This switch is used to embed the name of the + DLL in the static import library generated by @code{dlltool} with switch + @option{--output-lib}. + + @item -k + @cindex @option{-k} (@command{dlltool}) + Kill @code{@@}@i{nn} from exported names + (@pxref{Windows Calling Conventions} + for a discussion about @code{Stdcall}-style symbols. + + @item --help + @cindex @option{--help} (@command{dlltool}) + Prints the @code{dlltool} switches with a concise description. + + @item --output-exp @var{exportfile} + @cindex @option{--output-exp} (@command{dlltool}) + Generate an export file @var{exportfile}. The export file contains the + export table (list of symbols in the DLL) and is used to create the DLL. + + @item --output-lib @i{libfile} + @cindex @option{--output-lib} (@command{dlltool}) + Generate a static import library @var{libfile}. + + @item -v + @cindex @option{-v} (@command{dlltool}) + Verbose mode. + + @item --as @i{assembler-name} + @cindex @option{--as} (@command{dlltool}) + Use @i{assembler-name} as the assembler. The default is @code{as}. + @end table + + @node GNAT and Windows Resources + @section GNAT and Windows Resources + @cindex Resources, windows + + @menu + * Building Resources:: + * Compiling Resources:: + * Using Resources:: + @end menu + + @noindent + Resources are an easy way to add Windows specific objects to your + application. The objects that can be added as resources include: + + @itemize @bullet + @item + menus + + @item + accelerators + + @item + dialog boxes + + @item + string tables + + @item + bitmaps + + @item + cursors + + @item + icons + + @item + fonts + @end itemize + + @noindent + This section explains how to build, compile and use resources. + + @node Building Resources + @subsection Building Resources + @cindex Resources, building + + @noindent + A resource file is an ASCII file. By convention resource files have an + @file{.rc} extension. + The easiest way to build a resource file is to use Microsoft tools + such as @code{imagedit.exe} to build bitmaps, icons and cursors and + @code{dlgedit.exe} to build dialogs. + It is always possible to build an @file{.rc} file yourself by writing a + resource script. + + It is not our objective to explain how to write a resource file. A + complete description of the resource script language can be found in the + Microsoft documentation. + + @node Compiling Resources + @subsection Compiling Resources + @findex rc + @findex windres + @cindex Resources, compiling + + @noindent + This section describes how to build a GNAT-compatible (COFF) object file + containing the resources. This is done using the Resource Compiler + @code{windres} as follows: + + @smallexample + $ windres -i myres.rc -o myres.o + @end smallexample + + @noindent + By default @code{windres} will run @code{gcc} to preprocess the @file{.rc} + file. You can specify an alternate preprocessor (usually named + @file{cpp.exe}) using the @code{windres} @option{--preprocessor} + parameter. A list of all possible options may be obtained by entering + the command @code{windres} @option{--help}. + + It is also possible to use the Microsoft resource compiler @code{rc.exe} + to produce a @file{.res} file (binary resource file). See the + corresponding Microsoft documentation for further details. In this case + you need to use @code{windres} to translate the @file{.res} file to a + GNAT-compatible object file as follows: + + @smallexample + $ windres -i myres.res -o myres.o + @end smallexample + + @node Using Resources + @subsection Using Resources + @cindex Resources, using + + @noindent + To include the resource file in your program just add the + GNAT-compatible object file for the resource(s) to the linker + arguments. With @code{gnatmake} this is done by using the @option{-largs} + option: + + @smallexample + $ gnatmake myprog -largs myres.o + @end smallexample + + @node Debugging a DLL + @section Debugging a DLL + @cindex DLL debugging + + @menu + * Program and DLL Both Built with GCC/GNAT:: + * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: + @end menu + + @noindent + Debugging a DLL is similar to debugging a standard program. But + we have to deal with two different executable parts: the DLL and the + program that uses it. We have the following four possibilities: + + @enumerate 1 + @item + The program and the DLL are built with @code{GCC/GNAT}. + @item + The program is built with foreign tools and the DLL is built with + @code{GCC/GNAT}. + @item + The program is built with @code{GCC/GNAT} and the DLL is built with + foreign tools. + @item + @end enumerate + + @noindent + In this section we address only cases one and two above. + There is no point in trying to debug + a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging + information in it. To do so you must use a debugger compatible with the + tools suite used to build the DLL. + + @node Program and DLL Both Built with GCC/GNAT + @subsection Program and DLL Both Built with GCC/GNAT + + @noindent + This is the simplest case. Both the DLL and the program have @code{GDB} + compatible debugging information. It is then possible to break anywhere in + the process. Let's suppose here that the main procedure is named + @code{ada_main} and that in the DLL there is an entry point named + @code{ada_dll}. + + @noindent + The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and + program must have been built with the debugging information (see GNAT -g + switch). Here are the step-by-step instructions for debugging it: + + @enumerate 1 + @item Launch @code{GDB} on the main program. + + @smallexample + $ gdb -nw ada_main + @end smallexample + + @item Break on the main procedure and run the program. + + @smallexample + (gdb) break ada_main + (gdb) run + @end smallexample + + @noindent + This step is required to be able to set a breakpoint inside the DLL. As long + as the program is not run, the DLL is not loaded. This has the + consequence that the DLL debugging information is also not loaded, so it is not + possible to set a breakpoint in the DLL. + + @item Set a breakpoint inside the DLL + + @smallexample + (gdb) break ada_dll + (gdb) run + @end smallexample + + @end enumerate + + @noindent + At this stage a breakpoint is set inside the DLL. From there on + you can use the standard approach to debug the whole program + (@pxref{Running and Debugging Ada Programs}). + + @node Program Built with Foreign Tools and DLL Built with GCC/GNAT + @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT + + @menu + * Debugging the DLL Directly:: + * Attaching to a Running Process:: + @end menu + + @noindent + In this case things are slightly more complex because it is not possible to + start the main program and then break at the beginning to load the DLL and the + associated DLL debugging information. It is not possible to break at the + beginning of the program because there is no @code{GDB} debugging information, + and therefore there is no direct way of getting initial control. This + section addresses this issue by describing some methods that can be used + to break somewhere in the DLL to debug it. + + @noindent + First suppose that the main procedure is named @code{main} (this is for + example some C code built with Microsoft Visual C) and that there is a + DLL named @code{test.dll} containing an Ada entry point named + @code{ada_dll}. + + @noindent + The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have + been built with debugging information (see GNAT -g option). + + @node Debugging the DLL Directly + @subsubsection Debugging the DLL Directly + + @enumerate 1 + @item + Launch the debugger on the DLL. + + @smallexample + $ gdb -nw test.dll + @end smallexample + + @item Set a breakpoint on a DLL subroutine. + + @smallexample + (gdb) break ada_dll + @end smallexample + + @item + Specify the executable file to @code{GDB}. + + @smallexample + (gdb) exec-file main.exe + @end smallexample + + @item + Run the program. + + @smallexample + (gdb) run + @end smallexample + + @noindent + This will run the program until it reaches the breakpoint that has been + set. From that point you can use the standard way to debug a program + as described in (@pxref{Running and Debugging Ada Programs}). + + @end enumerate + + @noindent + It is also possible to debug the DLL by attaching to a running process. + + @node Attaching to a Running Process + @subsubsection Attaching to a Running Process + @cindex DLL debugging, attach to process + + @noindent + With @code{GDB} it is always possible to debug a running process by + attaching to it. It is possible to debug a DLL this way. The limitation + of this approach is that the DLL must run long enough to perform the + attach operation. It may be useful for instance to insert a time wasting + loop in the code of the DLL to meet this criterion. + + @enumerate 1 + + @item Launch the main program @file{main.exe}. + + @smallexample + $ main + @end smallexample + + @item Use the Windows @i{Task Manager} to find the process ID. Let's say + that the process PID for @file{main.exe} is 208. + + @item Launch gdb. + + @smallexample + $ gdb -nw + @end smallexample + + @item Attach to the running process to be debugged. + + @smallexample + (gdb) attach 208 + @end smallexample + + @item Load the process debugging information. + + @smallexample + (gdb) symbol-file main.exe + @end smallexample + + @item Break somewhere in the DLL. + + @smallexample + (gdb) break ada_dll + @end smallexample + + @item Continue process execution. + + @smallexample + (gdb) continue + @end smallexample + + @end enumerate + + @noindent + This last step will resume the process execution, and stop at + the breakpoint we have set. From there you can use the standard + approach to debug a program as described in + (@pxref{Running and Debugging Ada Programs}). + + @node GNAT and COM/DCOM Objects + @section GNAT and COM/DCOM Objects + @findex COM + @findex DCOM + + @noindent + This section is temporarily left blank. + + @end ifset + + + @c ********************************** + @c * GNU Free Documentation License * + @c ********************************** + @include fdl.texi + @c GNU Free Documentation License + + @node Index,,GNU Free Documentation License, Top + @unnumbered Index + + @printindex cp + + @contents + @c Put table of contents at end, otherwise it precedes the "title page" in + @c the .txt version + @c Edit the pdf file to move the contents to the beginning, after the title + @c page + + @bye diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_ug.texi gcc-3.4.1/gcc/ada/gnat_ug.texi *** gcc-3.4.0/gcc/ada/gnat_ug.texi 2004-03-20 15:33:52.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_ug.texi 1970-01-01 00:00:00.000000000 +0000 *************** *** 1,24882 **** - \input texinfo @c -*-texinfo-*- - @c %**start of header - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c o - @c GNAT DOCUMENTATION o - @c o - @c G N A T _ U G o - @c o - @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. o - @c o - @c GNAT is free software; you can redistribute it and/or modify it under o - @c terms of the GNU General Public License as published by the Free Soft- o - @c ware Foundation; either version 2, or (at your option) any later ver- o - @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o - @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o - @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o - @c for more details. You should have received a copy of the GNU General o - @c Public License distributed with GNAT; see file COPYING. If not, write o - @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o - @c MA 02111-1307, USA. o - @c o - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c - @c GNAT_UG Style Guide - @c - @c 1. Always put a @noindent on the line before the first paragraph - @c after any of these commands: - @c - @c @chapter - @c @section - @c @subsection - @c @subsubsection - @c @subsubsubsection - @c - @c @end smallexample - @c @end itemize - @c @end enumerate - @c - @c 2. DO NOT use @example. Use @smallexample instead. - @c - @c 3. Each @chapter, @section, @subsection, @subsubsection, etc. - @c command must be preceded by two empty lines - @c - @c 4. The @item command must be on a line of its own if it is in an - @c @itemize or @enumerate command. - @c - @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" - @c or "ali". - @c - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @ifset vms - @setfilename gnat_ug_vms.info - @settitle GNAT User's Guide for OpenVMS Alpha - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_vms). GNAT User's Guide for OpenVMS Alpha. - @end direntry - @end ifset - - @ifset wnt - @setfilename gnat_ug_wnt.info - @settitle GNAT User's Guide for Windows NT - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_wnt). GNAT User's Guide for Windows NT. - @end direntry - @end ifset - - @ifset unx - @setfilename gnat_ug_unx.info - @settitle GNAT User's Guide for Unix Platforms - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_unx). GNAT User's Guide for Unix Platforms. - @end direntry - @end ifset - - @ifset vxworks - @setfilename gnat_ug_vxw.info - @settitle GNAT User's Guide for Cross Platforms - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_vxw). GNAT User's Guide for Cross Platforms. - @end direntry - @end ifset - - @include gcc-common.texi - - @setchapternewpage odd - @syncodeindex fn cp - @c %**end of header - - @copying - Copyright @copyright{} 1995-2003, Free Software Foundation - - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with the Invariant Sections being ``GNU Free Documentation License'', with the - Front-Cover Texts being - @ifset vms - ``GNAT User's Guide for OpenVMS Alpha'', - @end ifset - @ifset wnt - ``GNAT User's Guide for Windows NT'', - @end ifset - @ifset unx - ``GNAT User's Guide for Unix Platforms'', - @end ifset - @ifset vxworks - ``GNAT User's Guide for Cross Platforms'', - @end ifset - and with no Back-Cover Texts. - A copy of the license is included in the section entitled ``GNU - Free Documentation License''. - @end copying - - @titlepage - - @ifset vms - @title GNAT User's Guide - @center @titlefont{for OpenVMS Alpha} - @end ifset - - @ifset wnt - @title GNAT User's Guide - @center @titlefont{for Windows NT} - @end ifset - - @ifset unx - @title GNAT User's Guide - @center @titlefont{for Unix Platforms} - @end ifset - - @ifset vxworks - @title GNAT User's Guide - @center @titlefont{for Cross Platforms} - @end ifset - - @subtitle GNAT, The GNU Ada 95 Compiler - @subtitle GNAT Version for GCC @value{version-GCC} - - @author Ada Core Technologies, Inc. - - @page - @vskip 0pt plus 1filll - - @insertcopying - - @end titlepage - - @ifnottex - @node Top, About This Guide, (dir), (dir) - @top GNAT User's Guide - - @ifset vms - GNAT User's Guide for OpenVMS Alpha - @end ifset - - @ifset wnt - GNAT User's Guide for Windows NT - @end ifset - - @ifset unx - GNAT User's Guide for Unix Platforms - @end ifset - - @ifset vxworks - GNAT User's Guide for Cross Platforms - @end ifset - - GNAT, The GNU Ada 95 Compiler - - GNAT Version for GCC @value{version-GCC} - - Ada Core Technologies, Inc. - - @insertcopying - - @menu - * About This Guide:: - @ifset vxworks - * Preliminary Note for Cross Platform Users:: - @end ifset - * Getting Started with GNAT:: - * The GNAT Compilation Model:: - * Compiling Using gcc:: - * Binding Using gnatbind:: - * Linking Using gnatlink:: - * The GNAT Make Program gnatmake:: - * Renaming Files Using gnatchop:: - * Configuration Pragmas:: - * Handling Arbitrary File Naming Conventions Using gnatname:: - * GNAT Project Manager:: - * Elaboration Order Handling in GNAT:: - * The Cross-Referencing Tools gnatxref and gnatfind:: - * File Name Krunching Using gnatkr:: - * Preprocessing Using gnatprep:: - @ifset vms - * The GNAT Run-Time Library Builder gnatlbr:: - @end ifset - * The GNAT Library Browser gnatls:: - @ifclear vms - * GNAT and Libraries:: - * Using the GNU make Utility:: - @ifclear vxworks - * Finding Memory Problems with gnatmem:: - @end ifclear - @end ifclear - * Finding Memory Problems with GNAT Debug Pool:: - * Creating Sample Bodies Using gnatstub:: - * Reducing the Size of Ada Executables with gnatelim:: - * Other Utility Programs:: - @ifset vms - * Compatibility with DEC Ada:: - @end ifset - * Running and Debugging Ada Programs:: - * Inline Assembler:: - @ifset wnt - * Microsoft Windows Topics:: - @end ifset - @ifset vxworks - * VxWorks Topics:: - * LynxOS Topics:: - @end ifset - * Performance Considerations:: - * GNU Free Documentation License:: - * Index:: - - --- The Detailed Node Listing --- - - About This Guide - - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - - @ifset vxworks - Preliminary Note for Cross Platform Users:: - @end ifset - - Getting Started with GNAT - - * Running GNAT:: - @ifclear vxworks - * Running a Simple Ada Program:: - @end ifclear - @ifset vxworks - * Building a Simple Ada Program:: - * Executing a Program on VxWorks:: - @end ifset - * Running a Program with Multiple Units:: - * Using the gnatmake Utility:: - @ifset vms - * Editing with Emacs:: - @end ifset - - The GNAT Compilation Model - - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - - Foreign Language Representation - - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - - Compiling Ada Programs With gcc - - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - - Switches for gcc - - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - - Binding Ada Programs With gnatbind - - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - - Linking Using gnatlink - - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - - The GNAT Make Program gnatmake - - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - - Renaming Files Using gnatchop - - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - - Configuration Pragmas - - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - - Handling Arbitrary File Naming Conventions Using gnatname - - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - - GNAT Project Manager - - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - - Elaboration Order Handling in GNAT - - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - - The Cross-Referencing Tools gnatxref and gnatfind - - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - - File Name Krunching Using gnatkr - - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - - Preprocessing Using gnatprep - - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - - @ifset vms - The GNAT Run-Time Library Builder gnatlbr - - * Running gnatlbr:: - * Switches for gnatlbr:: - * Examples of gnatlbr Usage:: - @end ifset - - The GNAT Library Browser gnatls - - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - - @ifclear vms - - GNAT and Libraries - - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - - Using the GNU make Utility - - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - - @ifclear vxworks - Finding Memory Problems with gnatmem - - * Running gnatmem (GDB Mode):: - * Running gnatmem (GMEM Mode):: - * Switches for gnatmem:: - * Examples of gnatmem Usage:: - * GDB and GMEM Modes:: - * Implementation Note:: - - @end ifclear - @end ifclear - - Finding Memory Problems with GNAT Debug Pool - - Creating Sample Bodies Using gnatstub - - * Running gnatstub:: - * Switches for gnatstub:: - - Reducing the Size of Ada Executables with gnatelim - - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - - Other Utility Programs - - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - @ifset vms - * LSE:: - @end ifset - - @ifset vms - Compatibility with DEC Ada - - * Ada 95 Compatibility:: - * Differences in the Definition of Package System:: - * Language-Related Features:: - * The Package STANDARD:: - * The Package SYSTEM:: - * Tasking and Task-Related Features:: - * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems:: - * Pragmas and Pragma-Related Features:: - * Library of Predefined Units:: - * Bindings:: - * Main Program Definition:: - * Implementation-Defined Attributes:: - * Compiler and Run-Time Interfacing:: - * Program Compilation and Library Management:: - * Input-Output:: - * Implementation Limits:: - * Tools:: - - Language-Related Features - - * Integer Types and Representations:: - * Floating-Point Types and Representations:: - * Pragmas Float_Representation and Long_Float:: - * Fixed-Point Types and Representations:: - * Record and Array Component Alignment:: - * Address Clauses:: - * Other Representation Clauses:: - - Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems - - * Assigning Task IDs:: - * Task IDs and Delays:: - * Task-Related Pragmas:: - * Scheduling and Task Priority:: - * The Task Stack:: - * External Interrupts:: - - Pragmas and Pragma-Related Features - - * Restrictions on the Pragma INLINE:: - * Restrictions on the Pragma INTERFACE:: - * Restrictions on the Pragma SYSTEM_NAME:: - - Library of Predefined Units - - * Changes to DECLIB:: - - Bindings - - * Shared Libraries and Options Files:: - * Interfaces to C:: - @end ifset - - Running and Debugging Ada Programs - - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - - Inline Assembler - - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - - @ifset wnt - Microsoft Windows Topics - - * Using GNAT on Windows:: - * GNAT Setup Tool:: - * CONSOLE and WINDOWS subsystems:: - * Temporary Files:: - * Mixed-Language Programming on Windows:: - * Windows Calling Conventions:: - * Introduction to Dynamic Link Libraries (DLLs):: - * Using DLLs with GNAT:: - * Building DLLs with GNAT:: - * GNAT and Windows Resources:: - * GNAT and COM/DCOM Objects:: - @end ifset - - @ifset vxworks - VxWorks Topics - - * Kernel Configuration for VxWorks:: - * Kernel Compilation Issues for VxWorks:: - * Handling Relocation Issues for PowerPc Targets:: - * Support for Software Floating Point on PowerPC Processors:: - * Interrupt Handling for VxWorks:: - * Simulating Command Line Arguments for VxWorks:: - * Debugging Issues for VxWorks:: - * Using GNAT from the Tornado 2 Project Facility:: - * Frequently Asked Questions for VxWorks:: - - LynxOS Topics - - * Getting Started with GNAT on LynxOS:: - * Kernel Configuration for LynxOS:: - * Patch Level Issues for LynxOS:: - * Debugging Issues for LynxOS:: - * An Example Debugging Session for LynxOS:: - @end ifset - - Performance Considerations - - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - @ifset vms - * Coverage Analysis:: - @end ifset - - * Index:: - @end menu - @end ifnottex - - @node About This Guide - @unnumbered About This Guide - - @noindent - @ifset vms - This guide describes the use of of GNAT, a full language compiler for the Ada - 95 programming language, implemented on DIGITAL OpenVMS Alpha Systems. - @end ifset - @ifclear vms - This guide describes the use of GNAT, a compiler and software development - toolset for the full Ada 95 programming language. - @end ifclear - It describes the features of the compiler and tools, and details - how to use them to build Ada 95 applications. - - @menu - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - @end menu - - @node What This Guide Contains - @unnumberedsec What This Guide Contains - - @noindent - This guide contains the following chapters: - @itemize @bullet - @ifset vxworks - @item - @ref{Preliminary Note for Cross Platform Users}, describes the basic - differences between the cross and native versions of GNAT. - @end ifset - @item - @ref{Getting Started with GNAT}, describes how to get started compiling - and running Ada programs with the GNAT Ada programming environment. - @item - @ref{The GNAT Compilation Model}, describes the compilation model used - by GNAT. - @item - @ref{Compiling Using gcc}, describes how to compile - Ada programs with @code{gcc}, the Ada compiler. - @item - @ref{Binding Using gnatbind}, describes how to - perform binding of Ada programs with @code{gnatbind}, the GNAT binding - utility. - @item - @ref{Linking Using gnatlink}, - describes @code{gnatlink}, a - program that provides for linking using the GNAT run-time library to - construct a program. @code{gnatlink} can also incorporate foreign language - object units into the executable. - @item - @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a - utility that automatically determines the set of sources - needed by an Ada compilation unit, and executes the necessary compilations - binding and link. - @item - @ref{Renaming Files Using gnatchop}, describes - @code{gnatchop}, a utility that allows you to preprocess a file that - contains Ada source code, and split it into one or more new files, one - for each compilation unit. - @item - @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT. - @item - @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override - the default GNAT file naming conventions, either for an individual unit or globally. - @item - @ref{GNAT Project Manager}, describes how to use project files to organize large projects. - @item - @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with - elaboration order issues. - @item - @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses - @code{gnatxref} and @code{gnatfind}, two tools that provide an easy - way to navigate through sources. - @item - @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr} - file name krunching utility, used to handle shortened - file names on operating systems with a limit on the length of names. - @item - @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a - preprocessor utility that allows a single source file to be used to - generate multiple or parameterized source files, by means of macro - substitution. - @item - @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a - utility that displays information about compiled units, including dependences - on the corresponding sources files, and consistency of compilations. - @ifclear vms - @item - @ref{GNAT and Libraries}, describes the process of creating and using - Libraries with GNAT. It also describes how to recompile the GNAT run-time - library. - - @item - @ref{Using the GNU make Utility}, describes some techniques for using - the GNAT toolset in Makefiles. - - @ifclear vxworks - @item - @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a - utility that monitors dynamic allocation and deallocation activity in a - program, and displays information about incorrect deallocations and sources - of possible memory leaks. - @end ifclear - @end ifclear - @item - @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to - use the GNAT-specific Debug Pool in order to detect as early as possible - the use of incorrect memory references. - - @item - @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub}, - a utility that generates empty but compilable bodies for library units. - - @item - @ref{Reducing the Size of Ada Executables with gnatelim}, describes - @code{gnatelim}, a tool which detects unused subprograms and helps - the compiler to create a smaller executable for the program. - - @item - @ref{Other Utility Programs}, discusses several other GNAT utilities, - including @code{gnatpsta}. - - @item - @ref{Running and Debugging Ada Programs}, describes how to run and debug - Ada programs. - - @item - @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program. - - @ifset vxworks - @item - @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation - configurations. - - @item - @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation - configurations. - @end ifset - - @item - @ref{Performance Considerations}, reviews the trade offs between using - defaults or options in program development. - @ifset vms - @item - @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with - DEC Ada 83 for OpenVMS Alpha. - @end ifset - @end itemize - - @node What You Should Know before Reading This Guide - @unnumberedsec What You Should Know before Reading This Guide - - @cindex Ada 95 Language Reference Manual - @noindent - This user's guide assumes that you are familiar with Ada 95 language, as - described in the International Standard ANSI/ISO/IEC-8652:1995, Jan - 1995. - - @node Related Information - @unnumberedsec Related Information - - @noindent - For further information about related tools, refer to the following - documents: - - @itemize @bullet - @item - @cite{GNAT Reference Manual}, which contains all reference - material for the GNAT implementation of Ada 95. - - @item - @cite{Ada 95 Language Reference Manual}, which contains all reference - material for the Ada 95 programming language. - - @item - @cite{Debugging with GDB} - @ifset vms - , located in the GNU:[DOCS] directory, - @end ifset - contains all details on the use of the GNU source-level debugger. - - @item - @cite{GNU Emacs Manual} - @ifset vms - , located in the GNU:[DOCS] directory if the EMACS kit is installed, - @end ifset - contains full information on the extensible editor and programming - environment Emacs. - - @end itemize - - @node Conventions - @unnumberedsec Conventions - @cindex Conventions - @cindex Typographical conventions - - @noindent - Following are examples of the typographical and graphic conventions used - in this guide: - - @itemize @bullet - @item - @code{Functions}, @code{utility program names}, @code{standard names}, - and @code{classes}. - - @item - @samp{Option flags} - - @item - @file{File Names}, @file{button names}, and @file{field names}. - - @item - @var{Variables}. - - @item - @emph{Emphasis}. - - @item - [optional information or parameters] - - @item - Examples are described by text - @smallexample - and then shown this way. - @end smallexample - @end itemize - - @noindent - Commands that are entered by the user are preceded in this manual by the - characters @w{"@code{$ }"} (dollar sign followed by space). If your system - uses this sequence as a prompt, then the commands will appear exactly as - you see them in the manual. If your system uses some other prompt, then - the command will appear with the @code{$} replaced by whatever prompt - character you are using. - - @ifset vxworks - @node Preliminary Note for Cross Platform Users - @chapter Preliminary Note for Cross Platform Users - - @noindent - The use of GNAT in a cross environment is very similar to its use in a - native environment. Most of the tools described in this manual have - similar functions and options in both modes. The major - difference is that the name of the cross tools includes the target for - which the cross compiler is configured. For instance, the cross @command{gnatmake} - tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of - the cross target. Thus, in an environment configured for the - target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is - @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the - installation of a native and one or several cross development - environments at the same location. - - The tools that are most relevant in a cross environment are: - @code{@i{target}-gcc}, @code{@i{target}-gnatmake}, - @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross - applications and @code{@i{target}-gnatls} for cross library - browsing. @code{@i{target}-gdb} is also usually available for cross - debugging in text mode. The graphical debugger interface - @code{gvd} is always a native tool but it can be configured to drive - the above mentioned cross debugger, thus allowing graphical cross debugging - sessions. Some other tools such as @code{@i{target}-gnatchop}, - @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep}, - @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind} - and @code{@i{target}-gnatname} are also provided for completeness - even though they do not differ greatly from their native counterpart. - - In the rest of this manual, the tools are sometimes designated with - their full cross name, and sometimes with their simplified native - name. - - @end ifset - - @node Getting Started with GNAT - @chapter Getting Started with GNAT - - @ifclear vxworks - @noindent - This chapter describes some simple ways of using GNAT to build - executable Ada programs. - @end ifclear - @ifset vxworks - @noindent - This introduction is a starting point for using GNAT to develop - and execute Ada 95 programs in a cross environment. - It provides some specifics - about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform; - for other targets please refer to the corresponding chapter later in this manual. - - Basic familiarity with use of GNAT in a native environment is - presumed. For the VxWorks specific part, a knowledge of how to start - Tornado's @code{windsh} tool is also presumed. - @end ifset - - @menu - * Running GNAT:: - @ifclear vxworks - * Running a Simple Ada Program:: - @end ifclear - @ifset vxworks - * Building a Simple Ada Program:: - * Executing a Program on VxWorks:: - @end ifset - - * Running a Program with Multiple Units:: - - * Using the gnatmake Utility:: - @ifset vms - * Editing with Emacs:: - @end ifset - @ifclear vms - * Introduction to Glide and GVD:: - @end ifclear - @end menu - - @node Running GNAT - @section Running GNAT - - @noindent - Three steps are needed to create an executable file from an Ada source - file: - - @enumerate - @item - The source file(s) must be compiled. - @item - The file(s) must be bound using the GNAT binder. - @item - @ifclear vxworks - All appropriate object files must be linked to produce an executable. - @end ifclear - @ifset vxworks - All appropriate object files must be linked to produce a loadable module. - @end ifset - @end enumerate - - @noindent - All three steps are most commonly handled by using the @code{gnatmake} - utility program that, given the name of the main program, automatically - performs the necessary compilation, binding and linking steps. - - @ifclear vxworks - @node Running a Simple Ada Program - @section Running a Simple Ada Program - @end ifclear - @ifset vxworks - @node Building a Simple Ada Program - @section Building a Simple Ada Program - @end ifset - - @noindent - Any text editor may be used to prepare an Ada program. If @code{Glide} is - used, the optional Ada mode may be helpful in laying out the program. The - program text is a normal text file. We will suppose in our initial - example that you have used your editor to prepare the following - standard format text file: - - @smallexample - @group - @cartouche - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - @end cartouche - @end group - @end smallexample - - @noindent - This file should be named @file{hello.adb}. - With the normal default file naming conventions, GNAT requires - that each file - contain a single compilation unit whose file name is the - unit name, - with periods replaced by hyphens; the - extension is @file{ads} for a - spec and @file{adb} for a body. - You can override this default file naming convention by use of the - special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). - Alternatively, if you want to rename your files according to this default - convention, which is probably more convenient if you will be using GNAT - for all your compilations, then the @code{gnatchop} utility - can be used to generate correctly-named source files - (@pxref{Renaming Files Using gnatchop}). - - You can compile the program using the following command (@code{$} is used - as the command prompt in the examples in this document): - - @ifclear vxworks - @smallexample - $ gcc -c hello.adb - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gcc -c hello.adb - @end smallexample - @end ifset - - @noindent - @code{gcc} is the command used to run the compiler. This compiler is - capable of compiling programs in several languages, including Ada 95 and - C. It assumes that you have given it an Ada program if the file extension is - either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile - the specified file. - - @ifclear vms - The @option{-c} switch is required. It tells @command{gcc} to only do a - compilation. (For C programs, @command{gcc} can also do linking, but this - capability is not used directly for Ada programs, so the @option{-c} - switch must always be present.) - @end ifclear - - This compile command generates a file - @file{hello.o}, which is the object - file corresponding to your Ada program. It also generates an "Ada Library Information" file - @file{hello.ali}, - which contains additional information used to check - that an Ada program is consistent. - @ifclear vxworks - To build an executable file, - @end ifclear - @ifset vxworks - To build a downloadable module, - @end ifset - use @code{gnatbind} to bind the program - and @code{gnatlink} to link it. The - argument to both @code{gnatbind} and @code{gnatlink} is the name of the - @file{ali} file, but the default extension of @file{.ali} can - be omitted. This means that in the most common case, the argument - is simply the name of the main program: - - @ifclear vxworks - @smallexample - $ gnatbind hello - $ gnatlink hello - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gnatbind hello - $ @i{target}-gnatlink hello - @end smallexample - @end ifset - - @noindent - A simpler method of carrying out these steps is to use - @command{gnatmake}, - a master program that invokes all the required - compilation, binding and linking tools in the correct order. In particular, - @command{gnatmake} automatically recompiles any sources that have been modified - since they were last compiled, or sources that depend - on such modified sources, so that "version skew" is avoided. - @cindex Version skew (avoided by @command{gnatmake}) - - @ifclear vxworks - @smallexample - $ gnatmake hello.adb - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gnatmake hello.adb - @end smallexample - @end ifset - - @ifclear vxworks - @noindent - The result is an executable program called @file{hello}, which can be - run by entering: - - @c The following should be removed (BMB 2001-01-23) - @c @smallexample - @c $ ^./hello^$ RUN HELLO^ - @c @end smallexample - - @smallexample - $ hello - @end smallexample - - @noindent - assuming that the current directory is on the search path for executable programs. - - @noindent - and, if all has gone well, you will see - - @smallexample - Hello WORLD! - @end smallexample - - @noindent - appear in response to this command. - - @end ifclear - - @ifset vxworks - @noindent - The result is a relocatable object called @file{hello}. - - @emph{Technical note:} the result of the linking stage is a - relocatable partially-linked object containing all the relevant GNAT - run-time units, in contrast with the executable-format object file found in - native environments. - - - @node Executing a Program on VxWorks - @section Executing a Program on VxWorks - - @noindent - Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it. - - @menu - * Loading and Running the Program:: - * Unloading the Program:: - @end menu - - @node Loading and Running the Program - @subsection Loading and Running the Program - - @noindent - An Ada program is loaded and run in the same way as a C program. - Details may be found in the @cite{Tornado User's Guide}. - - In order to load and run our simple "Hello World" example, we assume that - the target has access to the disk of the host containing this object and - that its working directory has been set to the directory containing this - object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt - is the @code{->} sequence. - - @smallexample - -> vf0=open("/vio/0",2,0) - new symbol "vf0" added to symbol table. - vf0 = 0x2cab48: value = 12 = 0xc - -> ioGlobalStdSet(1,vf0) - value = 1 = 0x1 - -> ld < hello - value = 665408 = 0xa2740 - -> hello - Hello World - value = 0 = 0x0 - -> - @end smallexample - - @noindent - The first two commands redirect output to the shell window. - They are only needed if the target server was started without the - @code{-C} option. The third command loads the module, which is the file - @file{hello} created previously by the @code{@i{target}-gnatmake} command. - Note that for Tornado AE, the @command{ml} command replaces @command{ld}." - - The "Hello World" program comprises a procedure named @code{hello}, and this - is the name entered for the procedure in the target server's symbol table - when the module is loaded. To execute the procedure, type the symbol name @code{hello} - into @code{windsh} as shown in the last command above. - - Note that by default the entry point of an Ada program is the name of the main - Ada subprogram in a VxWorks environment. It is possible to use an alternative - name; see the description of @code{gnatbind} options for details. - - @node Unloading the Program - @subsection Unloading the Program - - @noindent - It is important to remember that - you must unload a program once you have run it. You - cannot load it once and run it several times. If you don't follow - this rule, your program's behavior can be unpredictable, and will most - probably crash. - - This effect is due to the implementation of Ada 95's @emph{elaboration} semantics. - The unit elaboration phase comprises a @emph{static} elaboration and a - @emph{dynamic} elaboration. On a native platform they both take place - when the program is run. Thus rerunning the program will repeat the complete - elaboration phase, and the program will run correctly. - - On VxWorks, the process is a bit different. - The static elaboration phase is handled by - the loader (typically when you type @code{ld < program_name} in - @code{windsh}). The dynamic phase takes place when the program is run. If the - program is run twice and has not been unloaded and then reloaded, the - second time it is run, the static elaboration phase is skipped. - Variables initialized during the static elaboration phase - may have been modified during the first execution of the program. Thus the - second execution isn't performed on a completely initialized environment. - - Note that in C programs, elaboration isn't systematic. Multiple runs without reload - might work, but, even with C programs, if there is an elaboration - phase, you will have to unload your program before re-running it. - @end ifset - - - @node Running a Program with Multiple Units - @section Running a Program with Multiple Units - - @noindent - Consider a slightly more complicated example that has three files: a - main program, and the spec and body of a package: - - @smallexample - @cartouche - @group - @b{package} Greetings @b{is} - @b{procedure} Hello; - @b{procedure} Goodbye; - @b{end} Greetings; - - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{package} @b{body} Greetings @b{is} - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - - @b{procedure} Goodbye @b{is} - @b{begin} - Put_Line ("Goodbye WORLD!"); - @b{end} Goodbye; - @b{end} Greetings; - @end group - - @group - @b{with} Greetings; - @b{procedure} Gmain @b{is} - @b{begin} - Greetings.Hello; - Greetings.Goodbye; - @b{end} Gmain; - @end group - @end cartouche - @end smallexample - - @noindent - Following the one-unit-per-file rule, place this program in the - following three separate files: - - @table @file - @item greetings.ads - spec of package @code{Greetings} - - @item greetings.adb - body of package @code{Greetings} - - @item gmain.adb - body of main program - @end table - - @noindent - To build an executable version of - this program, we could use four separate steps to compile, bind, and link - the program, as follows: - - @ifclear vxworks - @smallexample - $ gcc -c gmain.adb - $ gcc -c greetings.adb - $ gnatbind gmain - $ gnatlink gmain - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gcc -c gmain.adb - $ @i{target}-gcc -c greetings.adb - $ @i{target}-gnatbind gmain - $ @i{target}-gnatlink gmain - @end smallexample - @end ifset - - @noindent - Note that there is no required order of compilation when using GNAT. - In particular it is perfectly fine to compile the main program first. - Also, it is not necessary to compile package specs in the case where - there is an accompanying body; you only need to compile the body. If you want - to submit these files to the compiler for semantic checking and not code generation, - then use the - @option{-gnatc} switch: - - @ifclear vxworks - @smallexample - $ gcc -c greetings.ads -gnatc - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gcc -c greetings.ads -gnatc - @end smallexample - @end ifset - - @noindent - Although the compilation can be done in separate steps as in the - above example, in practice it is almost always more convenient - to use the @code{gnatmake} tool. All you need to know in this case - is the name of the main program's source file. The effect of the above four - commands can be achieved with a single one: - - @ifclear vxworks - @smallexample - $ gnatmake gmain.adb - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gnatmake gmain.adb - @end smallexample - @end ifset - - @noindent - In the next section we discuss the advantages of using @code{gnatmake} in - more detail. - - @node Using the gnatmake Utility - @section Using the @command{gnatmake} Utility - - @noindent - If you work on a program by compiling single components at a time using - @code{gcc}, you typically keep track of the units you modify. In order to - build a consistent system, you compile not only these units, but also any - units that depend on the units you have modified. - For example, in the preceding case, - if you edit @file{gmain.adb}, you only need to recompile that file. But if - you edit @file{greetings.ads}, you must recompile both - @file{greetings.adb} and @file{gmain.adb}, because both files contain - units that depend on @file{greetings.ads}. - - @code{gnatbind} will warn you if you forget one of these compilation - steps, so that it is impossible to generate an inconsistent program as a - result of forgetting to do a compilation. Nevertheless it is tedious and - error-prone to keep track of dependencies among units. - One approach to handle the dependency-bookkeeping is to use a - makefile. However, makefiles present maintenance problems of their own: - if the dependencies change as you change the program, you must make - sure that the makefile is kept up-to-date manually, which is also an - error-prone process. - - The @code{gnatmake} utility takes care of these details automatically. - Invoke it using either one of the following forms: - - @ifclear vxworks - @smallexample - $ gnatmake gmain.adb - $ gnatmake ^gmain^GMAIN^ - @end smallexample - @end ifclear - - @ifset vxworks - @smallexample - $ @i{target}-gnatmake gmain.adb - $ @i{target}-gnatmake gmain - @end smallexample - @end ifset - - @noindent - The argument is the name of the file containing the main program; - you may omit the extension. @code{gnatmake} - examines the environment, automatically recompiles any files that need - recompiling, and binds and links the resulting set of object files, - generating the executable file, @file{^gmain^GMAIN.EXE^}. - In a large program, it - can be extremely helpful to use @code{gnatmake}, because working out by hand - what needs to be recompiled can be difficult. - - Note that @code{gnatmake} - takes into account all the Ada 95 rules that - establish dependencies among units. These include dependencies that result - from inlining subprogram bodies, and from - generic instantiation. Unlike some other - Ada make tools, @code{gnatmake} does not rely on the dependencies that were - found by the compiler on a previous compilation, which may possibly - be wrong when sources change. @code{gnatmake} determines the exact set of - dependencies from scratch each time it is run. - - @ifset vms - @node Editing with Emacs - @section Editing with Emacs - @cindex Emacs - - @noindent - Emacs is an extensible self-documenting text editor that is available in a - separate VMSINSTAL kit. - - Invoke Emacs by typing "Emacs" at the command prompt. To get started, - click on the Emacs Help menu and run the Emacs Tutorial. - In a character cell terminal, Emacs help is invoked with "Ctrl-h" (also written - as "C-h"), and the tutorial by "C-h t". - - Documentation on Emacs and other tools is available in Emacs under the - pull-down menu button: Help - Info. After selecting Info, use the middle - mouse button to select a topic (e.g. Emacs). - - In a character cell terminal, do "C-h i" to invoke info, and then "m" - (stands for menu) followed by the menu item desired, as in "m Emacs", to get - to the Emacs manual. - Help on Emacs is also available by typing "HELP EMACS" at the DCL command - prompt. - - The tutorial is highly recommended in order to learn the intricacies of Emacs, - which is sufficiently extensible to provide for a complete programming - environment and shell for the sophisticated user. - @end ifset - - @ifclear vms - @node Introduction to Glide and GVD - @section Introduction to Glide and GVD - @cindex Glide - @cindex GVD - @noindent - Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs. This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger. Additional information may be found in the on-line help for these tools. - - @menu - * Building a New Program with Glide:: - * Simple Debugging with GVD:: - * Other Glide Features:: - @end menu - - @node Building a New Program with Glide - @subsection Building a New Program with Glide - @noindent - The simplest way to invoke Glide is to enter @command{glide} at the command prompt. It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running: - - @smallexample - $ glide& - @end smallexample - - @noindent - Glide will start up with an initial screen displaying the top-level menu items as well as some other information. The menu selections are as follows - @itemize @bullet - @item @code{Buffers} - @item @code{Files} - @item @code{Tools} - @item @code{Edit} - @item @code{Search} - @item @code{Mule} - @item @code{Glide} - @item @code{Help} - @end itemize - - @noindent - For this introductory example, you will need to create a new Ada source file. First, select the @code{Files} menu. This will pop open a menu with around a dozen or so items. To create a file, select the @code{Open file...} choice. Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name. Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name. For this example enter @file{hello.adb} as the name of the file. - - A new buffer will now appear, occupying the entire Glide window, with the file name at the top. The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item. Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file. - - You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines. First, type the following text: - @smallexample - with Ada.Text_IO; use Ada.Text_IO; - procedure Hello is - begin - @end smallexample - - @noindent - Observe that Glide uses different colors to distinguish reserved words from identifiers. Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations. When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left. But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed. - - The main part of the program will be a @code{for} loop. Instead of entering the text explicitly, however, use a statement template. Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives. Choose @code{for loop}. You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed. You should see the beginning of a @code{for} loop appear in the source program window. You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case). Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction). Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax. - - Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop: - @smallexample - Put_Line("Hello, World" & Integer'Image(I)) - @end smallexample - - @noindent - Finally, type @code{end Hello;} as the last line in the program. Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection. You will see a message at the bottom of the buffer confirming that the file has been saved. - - You are now ready to attempt to build the program. Select the @code{Ada} item from the top menu bar. Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable. Thus select @code{Ada build}. This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools. Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window. The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected. - - Correct the error: type in a semicolon to terminate the statement. Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file. This time the build will succeed; the tool output window shows you the options that are supplied by default. The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched. - - To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window: - - @smallexample - Hello, world 1 - Hello, world 2 - Hello, world 3 - Hello, world 4 - Hello, world 5 - @end smallexample - - @node Simple Debugging with GVD - @subsection Simple Debugging with GVD - - @noindent - This section describes how to set breakpoints, examine/modify variables, and step through execution. - - In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}. If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect. You can then launch GVD, e.g. on the @code{hello} program, by issuing the command: - - @smallexample - $ gvd hello - @end smallexample - - @noindent - If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build. Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}. - - GVD comes up in a multi-part window. One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected. - - To the left of the source file pane, you will notice green dots adjacent to some lines. These are lines for which object code exists and where breakpoints can thus be set. You set/reset a breakpoint by clicking the green dot. When a breakpoint is set, the dot is replaced by an @code{X} in a red circle. Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot. - - For this example, set a breakpoint at the statement where @code{Put_Line} is invoked. - - Start program execution by selecting the @code{Run} button on the top menu bar. (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.) Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message. - - You can examine the values of variables in several ways. Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas. - - Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger. Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item. Enter @code{2} as the new value, and press @command{OK}. The box for @code{Ind} shows the update. - - Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}. - - Remove the breakpoint, and resume execution by selecting the @code{Cont} button. You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination. - - - @node Other Glide Features - @subsection Other Glide Features - - @noindent - You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu. These are @emph{shortcut keys} that you can use instead of selecting menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}. - - To abort a Glide command, type @key{Ctrl-g}. - - If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line: - - @smallexample - $ glide hello.adb& - @end smallexample - - @noindent - While you are using Glide, a number of @emph{buffers} exist. You create some explicitly; e.g., when you open/create a file. Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build. If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry. - - If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}. - - If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps: - @itemize @bullet - @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents) - @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu - @end itemize - - @noindent - To exit from Glide, choose @code{Files} @result{} @code{Exit}. - @end ifclear - - @node The GNAT Compilation Model - @chapter The GNAT Compilation Model - @cindex GNAT compilation model - @cindex Compilation model - - @menu - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - @end menu - - @noindent - This chapter describes the compilation model used by GNAT. Although - similar to that used by other languages, such as C and C++, this model - is substantially different from the traditional Ada compilation models, - which are based on a library. The model is initially described without - reference to the library-based model. If you have not previously used an - Ada compiler, you need only read the first part of this chapter. The - last section describes and discusses the differences between the GNAT - model and the traditional Ada compiler models. If you have used other - Ada compilers, this section will help you to understand those - differences, and the advantages of the GNAT model. - - @node Source Representation - @section Source Representation - @cindex Latin-1 - - @noindent - Ada source programs are represented in standard text files, using - Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar - 7-bit ASCII set, plus additional characters used for - representing foreign languages (@pxref{Foreign Language Representation} - for support of non-USA character sets). The format effector characters - are represented using their standard ASCII encodings, as follows: - - @table @code - @item VT - @findex VT - Vertical tab, @code{16#0B#} - - @item HT - @findex HT - Horizontal tab, @code{16#09#} - - @item CR - @findex CR - Carriage return, @code{16#0D#} - - @item LF - @findex LF - Line feed, @code{16#0A#} - - @item FF - @findex FF - Form feed, @code{16#0C#} - @end table - - @noindent - Source files are in standard text file format. In addition, GNAT will - recognize a wide variety of stream formats, in which the end of physical - physical lines is marked by any of the following sequences: - @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful - in accommodating files that are imported from other operating systems. - - @cindex End of source file - @cindex Source file, end - @findex SUB - The end of a source file is normally represented by the physical end of - file. However, the control character @code{16#1A#} (@code{SUB}) is also - recognized as signalling the end of the source file. Again, this is - provided for compatibility with other operating systems where this - code is used to represent the end of file. - - Each file contains a single Ada compilation unit, including any pragmas - associated with the unit. For example, this means you must place a - package declaration (a package @dfn{spec}) and the corresponding body in - separate files. An Ada @dfn{compilation} (which is a sequence of - compilation units) is represented using a sequence of files. Similarly, - you will place each subunit or child unit in a separate file. - - @node Foreign Language Representation - @section Foreign Language Representation - - @noindent - GNAT supports the standard character sets defined in Ada 95 as well as - several other non-standard character sets for use in localized versions - of the compiler (@pxref{Character Set Control}). - @menu - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - @end menu - - @node Latin-1 - @subsection Latin-1 - @cindex Latin-1 - - @noindent - The basic character set is Latin-1. This character set is defined by ISO - standard 8859, part 1. The lower half (character codes @code{16#00#} - ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is - used to represent additional characters. These include extended letters - used by European languages, such as French accents, the vowels with umlauts - used in German, and the extra letter A-ring used in Swedish. - - @findex Ada.Characters.Latin_1 - For a complete list of Latin-1 codes and their encodings, see the source - file of library unit @code{Ada.Characters.Latin_1} in file - @file{a-chlat1.ads}. - You may use any of these extended characters freely in character or - string literals. In addition, the extended characters that represent - letters can be used in identifiers. - - @node Other 8-Bit Codes - @subsection Other 8-Bit Codes - - @noindent - GNAT also supports several other 8-bit coding schemes: - - @table @asis - @cindex Latin-2 - @item Latin-2 - Latin-2 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-3 - @cindex Latin-3 - Latin-3 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-4 - @cindex Latin-4 - Latin-4 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-5 - @cindex Latin-5 - @cindex Cyrillic - Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase - equivalence. - - @item IBM PC (code page 437) - @cindex code page 437 - This code page is the normal default for PCs in the U.S. It corresponds - to the original IBM PC character set. This set has some, but not all, of - the extended Latin-1 letters, but these letters do not have the same - encoding as Latin-1. In this mode, these letters are allowed in - identifiers with uppercase and lowercase equivalence. - - @item IBM PC (code page 850) - @cindex code page 850 - This code page is a modification of 437 extended to include all the - Latin-1 letters, but still not with the usual Latin-1 encoding. In this - mode, all these letters are allowed in identifiers with uppercase and - lowercase equivalence. - - @item Full Upper 8-bit - Any character in the range 80-FF allowed in identifiers, and all are - considered distinct. In other words, there are no uppercase and lowercase - equivalences in this range. This is useful in conjunction with - certain encoding schemes used for some foreign character sets (e.g. - the typical method of representing Chinese characters on the PC). - - @item No Upper-Half - No upper-half characters in the range 80-FF are allowed in identifiers. - This gives Ada 83 compatibility for identifier names. - @end table - - @noindent - For precise data on the encodings permitted, and the uppercase and lowercase - equivalences that are recognized, see the file @file{csets.adb} in - the GNAT compiler sources. You will need to obtain a full source release - of GNAT to obtain this file. - - @node Wide Character Encodings - @subsection Wide Character Encodings - - @noindent - GNAT allows wide character codes to appear in character and string - literals, and also optionally in identifiers, by means of the following - possible encoding schemes: - - @table @asis - - @item Hex Coding - In this encoding, a wide character is represented by the following five - character sequence: - - @smallexample - ESC a b c d - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ESC A345 is used to represent the wide character with code - @code{16#A345#}. - This scheme is compatible with use of the full Wide_Character set. - - @item Upper-Half Coding - @cindex Upper-Half Coding - The wide character with encoding @code{16#abcd#} where the upper bit is on (in - other words, "a" is in the range 8-F) is represented as two bytes, - @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control - character, but is not required to be in the upper half. This method can - be also used for shift-JIS or EUC, where the internal coding matches the - external coding. - - @item Shift JIS Coding - @cindex Shift JIS Coding - A wide character is represented by a two-character sequence, - @code{16#ab#} and - @code{16#cd#}, with the restrictions described for upper-half encoding as - described above. The internal character code is the corresponding JIS - character according to the standard algorithm for Shift-JIS - conversion. Only characters defined in the JIS code set table can be - used with this encoding method. - - @item EUC Coding - @cindex EUC Coding - A wide character is represented by a two-character sequence - @code{16#ab#} and - @code{16#cd#}, with both characters being in the upper half. The internal - character code is the corresponding JIS character according to the EUC - encoding algorithm. Only characters defined in the JIS code set table - can be used with this encoding method. - - @item UTF-8 Coding - A wide character is represented using - UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO - 10646-1/Am.2. Depending on the character value, the representation - is a one, two, or three byte sequence: - @smallexample - @iftex - @leftskip=.7cm - @end iftex - 16#0000#-16#007f#: 2#0xxxxxxx# - 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# - 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# - - @end smallexample - - @noindent - where the xxx bits correspond to the left-padded bits of the - 16-bit character value. Note that all lower half ASCII characters - are represented as ASCII bytes and all upper half characters and - other wide characters are represented as sequences of upper-half - (The full UTF-8 scheme allows for encoding 31-bit characters as - 6-byte sequences, but in this implementation, all UTF-8 sequences - of four or more bytes length will be treated as illegal). - @item Brackets Coding - In this encoding, a wide character is represented by the following eight - character sequence: - - @smallexample - [ " a b c d " ] - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ["A345"] is used to represent the wide character with code - @code{16#A345#}. It is also possible (though not required) to use the - Brackets coding for upper half characters. For example, the code - @code{16#A3#} can be represented as @code{["A3"]}. - - This scheme is compatible with use of the full Wide_Character set, - and is also the method used for wide character encoding in the standard - ACVC (Ada Compiler Validation Capability) test suite distributions. - - @end table - - @noindent - Note: Some of these coding schemes do not permit the full use of the - Ada 95 character set. For example, neither Shift JIS, nor EUC allow the - use of the upper half of the Latin-1 set. - - @node File Naming Rules - @section File Naming Rules - - @noindent - The default file name is determined by the name of the unit that the - file contains. The name is formed by taking the full expanded name of - the unit and replacing the separating dots with hyphens and using - ^lowercase^uppercase^ for all letters. - - An exception arises if the file name generated by the above rules starts - with one of the characters - @ifset vms - A,G,I, or S, - @end ifset - @ifclear vms - a,g,i, or s, - @end ifclear - and the second character is a - minus. In this case, the character ^tilde^dollar sign^ is used in place - of the minus. The reason for this special rule is to avoid clashes with - the standard names for child units of the packages System, Ada, - Interfaces, and GNAT, which use the prefixes - @ifset vms - S- A- I- and G- - @end ifset - @ifclear vms - s- a- i- and g- - @end ifclear - respectively. - - The file extension is @file{.ads} for a spec and - @file{.adb} for a body. The following list shows some - examples of these rules. - - @table @file - @item main.ads - Main (spec) - @item main.adb - Main (body) - @item arith_functions.ads - Arith_Functions (package spec) - @item arith_functions.adb - Arith_Functions (package body) - @item func-spec.ads - Func.Spec (child package spec) - @item func-spec.adb - Func.Spec (child package body) - @item main-sub.adb - Sub (subunit of Main) - @item ^a~bad.adb^A$BAD.ADB^ - A.Bad (child package body) - @end table - - @noindent - Following these rules can result in excessively long - file names if corresponding - unit names are long (for example, if child units or subunits are - heavily nested). An option is available to shorten such long file names - (called file name "krunching"). This may be particularly useful when - programs being developed with GNAT are to be used on operating systems - with limited file name lengths. @xref{Using gnatkr}. - - Of course, no file shortening algorithm can guarantee uniqueness over - all possible unit names; if file name krunching is used, it is your - responsibility to ensure no name clashes occur. Alternatively you - can specify the exact file names that you want used, as described - in the next section. Finally, if your Ada programs are migrating from a - compiler with a different naming convention, you can use the gnatchop - utility to produce source files that follow the GNAT naming conventions. - (For details @pxref{Renaming Files Using gnatchop}.) - - @node Using Other File Names - @section Using Other File Names - @cindex File names - - @noindent - In the previous section, we have described the default rules used by - GNAT to determine the file name in which a given unit resides. It is - often convenient to follow these default rules, and if you follow them, - the compiler knows without being explicitly told where to find all - the files it needs. - - However, in some cases, particularly when a program is imported from - another Ada compiler environment, it may be more convenient for the - programmer to specify which file names contain which units. GNAT allows - arbitrary file names to be used by means of the Source_File_Name pragma. - The form of this pragma is as shown in the following examples: - @cindex Source_File_Name pragma - - @smallexample - @group - @cartouche - @b{pragma} Source_File_Name (My_Utilities.Stacks, - Spec_File_Name => "myutilst_a.ada"); - @b{pragma} Source_File_name (My_Utilities.Stacks, - Body_File_Name => "myutilst.ada"); - @end cartouche - @end group - @end smallexample - - @noindent - As shown in this example, the first argument for the pragma is the unit - name (in this example a child unit). The second argument has the form - of a named association. The identifier - indicates whether the file name is for a spec or a body; - the file name itself is given by a string literal. - - The source file name pragma is a configuration pragma, which means that - normally it will be placed in the @file{gnat.adc} - file used to hold configuration - pragmas that apply to a complete compilation environment. - For more details on how the @file{gnat.adc} file is created and used - @pxref{Handling of Configuration Pragmas} - @cindex @file{gnat.adc} - - @ifclear vms - GNAT allows completely arbitrary file names to be specified using the - source file name pragma. However, if the file name specified has an - extension other than @file{.ads} or @file{.adb} it is necessary to use a special - syntax when compiling the file. The name in this case must be preceded - by the special sequence @code{-x} followed by a space and the name of the - language, here @code{ada}, as in: - - @smallexample - $ gcc -c -x ada peculiar_file_name.sim - @end smallexample - @end ifclear - - @noindent - @code{gnatmake} handles non-standard file names in the usual manner (the - non-standard file name for the main program is simply used as the - argument to gnatmake). Note that if the extension is also non-standard, - then it must be included in the gnatmake command, it may not be omitted. - - @node Alternative File Naming Schemes - @section Alternative File Naming Schemes - @cindex File naming schemes, alternative - @cindex File names - - In the previous section, we described the use of the @code{Source_File_Name} - pragma to allow arbitrary names to be assigned to individual source files. - However, this approach requires one pragma for each file, and especially in - large systems can result in very long @file{gnat.adc} files, and also create - a maintenance problem. - - GNAT also provides a facility for specifying systematic file naming schemes - other than the standard default naming scheme previously described. An - alternative scheme for naming is specified by the use of - @code{Source_File_Name} pragmas having the following format: - @cindex Source_File_Name pragma - - @smallexample - pragma Source_File_Name ( - Spec_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Body_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Subunit_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - FILE_NAME_PATTERN ::= STRING_LITERAL - CASING_SPEC ::= Lowercase | Uppercase | Mixedcase - - @end smallexample - - @noindent - The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. - It contains a single asterisk character, and the unit name is substituted - systematically for this asterisk. The optional parameter - @code{Casing} indicates - whether the unit name is to be all upper-case letters, all lower-case letters, - or mixed-case. If no - @code{Casing} parameter is used, then the default is all - ^lower-case^upper-case^. - - The optional @code{Dot_Replacement} string is used to replace any periods - that occur in subunit or child unit names. If no @code{Dot_Replacement} - argument is used then separating dots appear unchanged in the resulting - file name. - Although the above syntax indicates that the - @code{Casing} argument must appear - before the @code{Dot_Replacement} argument, but it - is also permissible to write these arguments in the opposite order. - - As indicated, it is possible to specify different naming schemes for - bodies, specs, and subunits. Quite often the rule for subunits is the - same as the rule for bodies, in which case, there is no need to give - a separate @code{Subunit_File_Name} rule, and in this case the - @code{Body_File_name} rule is used for subunits as well. - - The separate rule for subunits can also be used to implement the rather - unusual case of a compilation environment (e.g. a single directory) which - contains a subunit and a child unit with the same unit name. Although - both units cannot appear in the same partition, the Ada Reference Manual - allows (but does not require) the possibility of the two units coexisting - in the same environment. - - The file name translation works in the following steps: - - @itemize @bullet - - @item - If there is a specific @code{Source_File_Name} pragma for the given unit, - then this is always used, and any general pattern rules are ignored. - - @item - If there is a pattern type @code{Source_File_Name} pragma that applies to - the unit, then the resulting file name will be used if the file exists. If - more than one pattern matches, the latest one will be tried first, and the - first attempt resulting in a reference to a file that exists will be used. - - @item - If no pattern type @code{Source_File_Name} pragma that applies to the unit - for which the corresponding file exists, then the standard GNAT default - naming rules are used. - - @end itemize - - @noindent - As an example of the use of this mechanism, consider a commonly used scheme - in which file names are all lower case, with separating periods copied - unchanged to the resulting file name, and specs end with ".1.ada", and - bodies end with ".2.ada". GNAT will follow this scheme if the following - two pragmas appear: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.1.ada"); - pragma Source_File_Name - (Body_File_Name => "*.2.ada"); - @end smallexample - - @noindent - The default GNAT scheme is actually implemented by providing the following - default pragmas internally: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.ads", Dot_Replacement => "-"); - pragma Source_File_Name - (Body_File_Name => "*.adb", Dot_Replacement => "-"); - @end smallexample - - @noindent - Our final example implements a scheme typically used with one of the - Ada 83 compilers, where the separator character for subunits was "__" - (two underscores), specs were identified by adding @file{_.ADA}, bodies - by adding @file{.ADA}, and subunits by - adding @file{.SEP}. All file names were - upper case. Child units were not present of course since this was an - Ada 83 compiler, but it seems reasonable to extend this scheme to use - the same double underscore separator for child units. - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*_.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Body_File_Name => "*.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Subunit_File_Name => "*.SEP", - Dot_Replacement => "__", - Casing = Uppercase); - @end smallexample - - @node Generating Object Files - @section Generating Object Files - - @noindent - An Ada program consists of a set of source files, and the first step in - compiling the program is to generate the corresponding object files. - These are generated by compiling a subset of these source files. - The files you need to compile are the following: - - @itemize @bullet - @item - If a package spec has no body, compile the package spec to produce the - object file for the package. - - @item - If a package has both a spec and a body, compile the body to produce the - object file for the package. The source file for the package spec need - not be compiled in this case because there is only one object file, which - contains the code for both the spec and body of the package. - - @item - For a subprogram, compile the subprogram body to produce the object file - for the subprogram. The spec, if one is present, is as usual in a - separate file, and need not be compiled. - - @item - @cindex Subunits - In the case of subunits, only compile the parent unit. A single object - file is generated for the entire subunit tree, which includes all the - subunits. - - @item - Compile child units independently of their parent units - (though, of course, the spec of all the ancestor unit must be present in order - to compile a child unit). - - @item - @cindex Generics - Compile generic units in the same manner as any other units. The object - files in this case are small dummy files that contain at most the - flag used for elaboration checking. This is because GNAT always handles generic - instantiation by means of macro expansion. However, it is still necessary to - compile generic units, for dependency checking and elaboration purposes. - @end itemize - - @noindent - The preceding rules describe the set of files that must be compiled to - generate the object files for a program. Each object file has the same - name as the corresponding source file, except that the extension is - @file{.o} as usual. - - You may wish to compile other files for the purpose of checking their - syntactic and semantic correctness. For example, in the case where a - package has a separate spec and body, you would not normally compile the - spec. However, it is convenient in practice to compile the spec to make - sure it is error-free before compiling clients of this spec, because such - compilations will fail if there is an error in the spec. - - GNAT provides an option for compiling such files purely for the - purposes of checking correctness; such compilations are not required as - part of the process of building a program. To compile a file in this - checking mode, use the @option{-gnatc} switch. - - @node Source Dependencies - @section Source Dependencies - - @noindent - A given object file clearly depends on the source file which is compiled - to produce it. Here we are using @dfn{depends} in the sense of a typical - @code{make} utility; in other words, an object file depends on a source - file if changes to the source file require the object file to be - recompiled. - In addition to this basic dependency, a given object may depend on - additional source files as follows: - - @itemize @bullet - @item - If a file being compiled @code{with}'s a unit @var{X}, the object file - depends on the file containing the spec of unit @var{X}. This includes - files that are @code{with}'ed implicitly either because they are parents - of @code{with}'ed child units or they are run-time units required by the - language constructs used in a particular unit. - - @item - If a file being compiled instantiates a library level generic unit, the - object file depends on both the spec and body files for this generic - unit. - - @item - If a file being compiled instantiates a generic unit defined within a - package, the object file depends on the body file for the package as - well as the spec file. - - @item - @findex Inline - @cindex @option{-gnatn} switch - If a file being compiled contains a call to a subprogram for which - pragma @code{Inline} applies and inlining is activated with the - @option{-gnatn} switch, the object file depends on the file containing the - body of this subprogram as well as on the file containing the spec. Note - that for inlining to actually occur as a result of the use of this switch, - it is necessary to compile in optimizing mode. - - @cindex @option{-gnatN} switch - The use of @option{-gnatN} activates a more extensive inlining optimization - that is performed by the front end of the compiler. This inlining does - not require that the code generation be optimized. Like @option{-gnatn}, - the use of this switch generates additional dependencies. - - @item - If an object file O depends on the proper body of a subunit through inlining - or instantiation, it depends on the parent unit of the subunit. This means that - any modification of the parent unit or one of its subunits affects the - compilation of O. - - @item - The object file for a parent unit depends on all its subunit body files. - - @item - The previous two rules meant that for purposes of computing dependencies and - recompilation, a body and all its subunits are treated as an indivisible whole. - - @noindent - These rules are applied transitively: if unit @code{A} @code{with}'s - unit @code{B}, whose elaboration calls an inlined procedure in package - @code{C}, the object file for unit @code{A} will depend on the body of - @code{C}, in file @file{c.adb}. - - The set of dependent files described by these rules includes all the - files on which the unit is semantically dependent, as described in the - Ada 95 Language Reference Manual. However, it is a superset of what the - ARM describes, because it includes generic, inline, and subunit dependencies. - - An object file must be recreated by recompiling the corresponding source - file if any of the source files on which it depends are modified. For - example, if the @code{make} utility is used to control compilation, - the rule for an Ada object file must mention all the source files on - which the object file depends, according to the above definition. - The determination of the necessary - recompilations is done automatically when one uses @code{gnatmake}. - @end itemize - - @node The Ada Library Information Files - @section The Ada Library Information Files - @cindex Ada Library Information files - @cindex @file{ali} files - - @noindent - Each compilation actually generates two output files. The first of these - is the normal object file that has a @file{.o} extension. The second is a - text file containing full dependency information. It has the same - name as the source file, but an @file{.ali} extension. - This file is known as the Ada Library Information (@file{ali}) file. - The following information is contained in the @file{ali} file. - - @itemize @bullet - @item - Version information (indicates which version of GNAT was used to compile - the unit(s) in question) - - @item - Main program information (including priority and time slice settings, - as well as the wide character encoding used during compilation). - - @item - List of arguments used in the @code{gcc} command for the compilation - - @item - Attributes of the unit, including configuration pragmas used, an indication - of whether the compilation was successful, exception model used etc. - - @item - A list of relevant restrictions applying to the unit (used for consistency) - checking. - - @item - Categorization information (e.g. use of pragma @code{Pure}). - - @item - Information on all @code{with}'ed units, including presence of - @code{Elaborate} or @code{Elaborate_All} pragmas. - - @item - Information from any @code{Linker_Options} pragmas used in the unit - - @item - Information on the use of @code{Body_Version} or @code{Version} - attributes in the unit. - - @item - Dependency information. This is a list of files, together with - time stamp and checksum information. These are files on which - the unit depends in the sense that recompilation is required - if any of these units are modified. - - @item - Cross-reference data. Contains information on all entities referenced - in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to - provide cross-reference information. - - @end itemize - - @noindent - For a full detailed description of the format of the @file{ali} file, - see the source of the body of unit @code{Lib.Writ}, contained in file - @file{lib-writ.adb} in the GNAT compiler sources. - - @node Binding an Ada Program - @section Binding an Ada Program - - @noindent - When using languages such as C and C++, once the source files have been - compiled the only remaining step in building an executable program - is linking the object modules together. This means that it is possible to - link an inconsistent version of a program, in which two units have - included different versions of the same header. - - The rules of Ada do not permit such an inconsistent program to be built. - For example, if two clients have different versions of the same package, - it is illegal to build a program containing these two clients. - These rules are enforced by the GNAT binder, which also determines an - elaboration order consistent with the Ada rules. - - The GNAT binder is run after all the object files for a program have - been created. It is given the name of the main program unit, and from - this it determines the set of units required by the program, by reading the - corresponding ALI files. It generates error messages if the program is - inconsistent or if no valid order of elaboration exists. - - If no errors are detected, the binder produces a main program, in Ada by - default, that contains calls to the elaboration procedures of those - compilation unit that require them, followed by - a call to the main program. This Ada program is compiled to generate the - object file for the main program. The name of - the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec - @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the - main program unit. - - Finally, the linker is used to build the resulting executable program, - using the object from the main program from the bind step as well as the - object files for the Ada units of the program. - - @node Mixed Language Programming - @section Mixed Language Programming - @cindex Mixed Language Programming - - @menu - * Interfacing to C:: - * Calling Conventions:: - @end menu - - @node Interfacing to C - @subsection Interfacing to C - @noindent - There are two ways to - build a program that contains some Ada files and some other language - files depending on whether the main program is in Ada or not. - If the main program is in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind my_main.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. For instance: - @smallexample - gnatlink my_main.ali file1.o file2.o - @end smallexample - @end enumerate - - The three last steps can be grouped in a single command: - @smallexample - gnatmake my_main.adb -largs file1.o file2.o - @end smallexample - - @cindex Binder output file - @noindent - If the main program is in some language other than Ada, you may - have more than one entry point in the Ada subsystem. You must use a - special option of the binder to generate callable routines to initialize - and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). - Calls to the initialization and finalization routines must be inserted in - the main program, or some other appropriate point in the code. The call to - initialize the Ada units must occur before the first Ada subprogram is - called, and the call to finalize the Ada units must occur after the last - Ada subprogram returns. You use the same procedure for building the - program as described previously. In this case, however, the binder - only places the initialization and finalization subprograms into file - @file{b~@var{xxx}.adb} instead of the main program. - So, if the main program is not in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake ^-c^/ACTIONS=COMPILE^ entry_point1.adb - gnatmake ^-c^/ACTIONS=COMPILE^ entry_point2.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind ^-n^/NOMAIN^ entry_point1.ali entry_point2.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. You only need to give the last entry point here. For instance: - @smallexample - gnatlink entry_point2.ali file1.o file2.o - @end smallexample - @end enumerate - - @node Calling Conventions - @subsection Calling Conventions - @cindex Foreign Languages - @cindex Calling Conventions - GNAT follows standard calling sequence conventions and will thus interface - to any other language that also follows these conventions. The following - Convention identifiers are recognized by GNAT: - - @itemize @bullet - @cindex Interfacing to Ada - @cindex Other Ada compilers - @cindex Convention Ada - @item - Ada. This indicates that the standard Ada calling sequence will be - used and all Ada data items may be passed without any limitations in the - case where GNAT is used to generate both the caller and callee. It is also - possible to mix GNAT generated code and code generated by another Ada - compiler. In this case, the data types should be restricted to simple - cases, including primitive types. Whether complex data types can be passed - depends on the situation. Probably it is safe to pass simple arrays, such - as arrays of integers or floats. Records may or may not work, depending - on whether both compilers lay them out identically. Complex structures - involving variant records, access parameters, tasks, or protected types, - are unlikely to be able to be passed. - - Note that in the case of GNAT running - on a platform that supports DEC Ada 83, a higher degree of compatibility - can be guaranteed, and in particular records are layed out in an identical - manner in the two compilers. Note also that if output from two different - compilers is mixed, the program is responsible for dealing with elaboration - issues. Probably the safest approach is to write the main program in the - version of Ada other than GNAT, so that it takes care of its own elaboration - requirements, and then call the GNAT-generated adainit procedure to ensure - elaboration of the GNAT components. Consult the documentation of the other - Ada compiler for further details on elaboration. - - However, it is not possible to mix the tasking run time of GNAT and - DEC Ada 83, All the tasking operations must either be entirely within - GNAT compiled sections of the program, or entirely within DEC Ada 83 - compiled sections of the program. - - @cindex Interfacing to Assembly - @cindex Convention Assembler - @item - Assembler. Specifies assembler as the convention. In practice this has the - same effect as convention Ada (but is not equivalent in the sense of being - considered the same convention). - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembler. - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembly. - - @cindex Interfacing to COBOL - @cindex Convention COBOL - @findex COBOL - @item - COBOL. Data will be passed according to the conventions described - in section B.4 of the Ada 95 Reference Manual. - - @findex C - @cindex Interfacing to C - @cindex Convention C - @item - C. Data will be passed according to the conventions described - in section B.3 of the Ada 95 Reference Manual. - - @cindex Convention Default - @findex Default - @item - Default. Equivalent to C. - - @cindex Convention External - @findex External - @item - External. Equivalent to C. - - @findex C++ - @cindex Interfacing to C++ - @cindex Convention C++ - @item - CPP. This stands for C++. For most purposes this is identical to C. - See the separate description of the specialized GNAT pragmas relating to - C++ interfacing for further details. - - @findex Fortran - @cindex Interfacing to Fortran - @cindex Convention Fortran - @item - Fortran. Data will be passed according to the conventions described - in section B.5 of the Ada 95 Reference Manual. - - @item - Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95 - Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, - this means that the body of the subprogram is provided by the compiler itself, - usually by means of an efficient code sequence, and that the user does not - supply an explicit body for it. In an application program, the pragma can only - be applied to the following two sets of names, which the GNAT compiler - recognizes. - @itemize @bullet - @item - Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_- - Arithmetic. The corresponding subprogram declaration must have - two formal parameters. The - first one must be a signed integer type or a modular type with a binary - modulus, and the second parameter must be of type Natural. - The return type must be the same as the type of the first argument. The size - of this type can only be 8, 16, 32, or 64. - @item binary arithmetic operators: "+", "-", "*", "/" - The corresponding operator declaration must have parameters and result type - that have the same root numeric type (for example, all three are long_float - types). This simplifies the definition of operations that use type checking - to perform dimensional checks: - @smallexample - type Distance is new Long_Float; - type Time is new Long_Float; - type Velocity is new Long_Float; - function "/" (D : Distance; T : Time) - return Velocity; - pragma Import (Intrinsic, "/"); - @end smallexample - @noindent - This common idiom is often programmed with a generic definition and an explicit - body. The pragma makes it simpler to introduce such declarations. It incurs - no overhead in compilation time or code size, because it is implemented as a - single machine instruction. - @end itemize - @noindent - - @findex Stdcall - @cindex Convention Stdcall - @item - Stdcall. This is relevant only to NT/Win95 implementations of GNAT, - and specifies that the Stdcall calling sequence will be used, as defined - by the NT API. - - @findex DLL - @cindex Convention DLL - @item - DLL. This is equivalent to Stdcall. - - @findex Win32 - @cindex Convention Win32 - @item - Win32. This is equivalent to Stdcall. - - @findex Stubbed - @cindex Convention Stubbed - @item - Stubbed. This is a special convention that indicates that the compiler - should provide a stub body that raises @code{Program_Error}. - @end itemize - - @noindent - GNAT additionally provides a useful pragma @code{Convention_Identifier} - that can be used to parametrize conventions and allow additional synonyms - to be specified. For example if you have legacy code in which the convention - identifier Fortran77 was used for Fortran, you can use the configuration - pragma: - - @smallexample - pragma Convention_Identifier (Fortran77, Fortran); - @end smallexample - - @noindent - And from now on the identifier Fortran77 may be used as a convention - identifier (for example in an @code{Import} pragma) with the same - meaning as Fortran. - - @node Building Mixed Ada & C++ Programs - @section Building Mixed Ada & C++ Programs - - @noindent - Building a mixed application containing both Ada and C++ code may be a - challenge for the unaware programmer. As a matter of fact, this - interfacing has not been standardized in the Ada 95 reference manual due - to the immaturity and lack of standard of C++ at the time. This - section gives a few hints that should make this task easier. In - particular the first section addresses the differences with - interfacing with C. The second section looks into the delicate problem - of linking the complete application from its Ada and C++ parts. The last - section give some hints on how the GNAT run time can be adapted in order - to allow inter-language dispatching with a new C++ compiler. - - @menu - * Interfacing to C++:: - * Linking a Mixed C++ & Ada Program:: - * A Simple Example:: - * Adapting the Run Time to a New C++ Compiler:: - @end menu - - @node Interfacing to C++ - @subsection Interfacing to C++ - - @noindent - GNAT supports interfacing with C++ compilers generating code that is - compatible with the standard Application Binary Interface of the given - platform. - - @noindent - Interfacing can be done at 3 levels: simple data, subprograms and - classes. In the first 2 cases, GNAT offer a specific @var{Convention - CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle - names of subprograms and currently GNAT does not provide any help to - solve the demangling problem. This problem can be addressed in 2 ways: - @itemize @bullet - @item - by modifying the C++ code in order to force a C convention using - the @var{extern "C"} syntax. - - @item - by figuring out the mangled name and use it as the Link_Name argument of - the pragma import. - @end itemize - - @noindent - Interfacing at the class level can be achieved by using the GNAT specific - pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT - Reference Manual for additional information. - - @node Linking a Mixed C++ & Ada Program - @subsection Linking a Mixed C++ & Ada Program - - @noindent - Usually the linker of the C++ development system must be used to link - mixed applications because most C++ systems will resolve elaboration - issues (such as calling constructors on global class instances) - transparently during the link phase. GNAT has been adapted to ease the - use of a foreign linker for the last phase. Three cases can be - considered: - @enumerate - - @item - Using GNAT and G++ (GNU C++ compiler) from the same GCC - installation. The c++ linker can simply be called by using the c++ - specific driver called @code{c++}. Note that this setup is not - very common because it may request recompiling the whole GCC - tree from sources and it does not allow to upgrade easily to a new - version of one compiler for one of the two languages without taking the - risk of destabilizing the other. - - @smallexample - $ c++ -c file1.C - $ c++ -c file2.C - $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++ - @end smallexample - - @item - Using GNAT and G++ from 2 different GCC installations. If both compilers - are on the PATH, the same method can be used. It is important to be - aware that environment variables such as C_INCLUDE_PATH, - GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at - the same time and thus may make one of the 2 compilers operate - improperly if they are set for the other. In particular it is important - that the link command has access to the proper gcc library @file{libgcc.a}, - that is to say the one that is part of the C++ compiler - installation. The implicit link command as suggested in the gnatmake - command from the former example can be replaced by an explicit link - command with full verbosity in order to verify which library is used: - @smallexample - $ gnatbind ada_unit - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ - @end smallexample - If there is a problem due to interfering environment variables, it can - be workaround by using an intermediate script. The following example - shows the proper script to use when GNAT has not been installed at its - default location and g++ has been installed at its default location: - - @smallexample - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - unset BINUTILS_ROOT - unset GCC_ROOT - c++ $* - @end smallexample - - @item - Using a non GNU C++ compiler. The same set of command as previously - described can be used to insure that the c++ linker is - used. Nonetheless, you need to add the path to libgcc explicitely, since some - libraries needed by GNAT are located in this directory: - - @smallexample - - $ gnatlink ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - CC $* `gcc -print-libgcc-file-name` - - @end smallexample - - Where CC is the name of the non GNU C++ compiler. - - @end enumerate - - @node A Simple Example - @subsection A Simple Example - @noindent - The following example, provided as part of the GNAT examples, show how - to achieve procedural interfacing between Ada and C++ in both - directions. The C++ class A has 2 methods. The first method is exported - to Ada by the means of an extern C wrapper function. The second method - calls an Ada subprogram. On the Ada side, The C++ calls is modelized by - a limited record with a layout comparable to the C++ class. The Ada - subprogram, in turn, calls the c++ method. So from the C++ main program - the code goes back and forth between the 2 languages. - - @noindent - Here are the compilation commands - @ifclear vxworks - for native configurations: - @smallexample - $ gnatmake -c simple_cpp_interface - $ c++ -c cpp_main.C - $ c++ -c ex7.C - $ gnatbind -n simple_cpp_interface - $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS) - -lstdc++ ex7.o cpp_main.o - @end smallexample - @end ifclear - @ifset vxworks - for a GNAT VxWorks/PowerPC configuration: - @smallexample - $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface - $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface - $ gnatlink simple_cpp_interface -o ada_part - $ c++ppc -c -DCPU=PPC604 -I/usr/windppc/target/h cpp_main.C - $ c++ppc -c -DCPU=PPC604 -I/usr/windppc/target/h ex7.C - $ ldppc -r -o my_main my_main.o ex7.o ada_part - @end smallexample - @end ifset - @noindent - Here are the corresponding sources: - @smallexample - - //cpp_main.C - - #include "ex7.h" - - extern "C" @{ - void adainit (void); - void adafinal (void); - void method1 (A *t); - @} - - void method1 (A *t) - @{ - t->method1 (); - @} - - int main () - @{ - A obj; - adainit (); - obj.method2 (3030); - adafinal (); - @} - - //ex7.h - - class Origin @{ - public: - int o_value; - @}; - class A : public Origin @{ - public: - void method1 (void); - virtual void method2 (int v); - A(); - int a_value; - @}; - - //ex7.C - - #include "ex7.h" - #include - - extern "C" @{ void ada_method2 (A *t, int v);@} - - void A::method1 (void) - @{ - a_value = 2020; - printf ("in A::method1, a_value = %d \n",a_value); - - @} - - void A::method2 (int v) - @{ - ada_method2 (this, v); - printf ("in A::method2, a_value = %d \n",a_value); - - @} - - A::A(void) - @{ - a_value = 1010; - printf ("in A::A, a_value = %d \n",a_value); - @} - - -- Ada sources - @b{package} @b{body} Simple_Cpp_Interface @b{is} - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is} - @b{begin} - Method1 (This); - This.A_Value := V; - @b{end} Ada_Method2; - - @b{end} Simple_Cpp_Interface; - - @b{package} Simple_Cpp_Interface @b{is} - @b{type} A @b{is} @b{limited} - @b{record} - O_Value : Integer; - A_Value : Integer; - @b{end} @b{record}; - @b{pragma} Convention (C, A); - - @b{procedure} Method1 (This : @b{in} @b{out} A); - @b{pragma} Import (C, Method1); - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer); - @b{pragma} Export (C, Ada_Method2); - - @b{end} Simple_Cpp_Interface; - @end smallexample - - @node Adapting the Run Time to a New C++ Compiler - @subsection Adapting the Run Time to a New C++ Compiler - @noindent - GNAT offers the capability to derive Ada 95 tagged types directly from - preexisting C++ classes and . See "Interfacing with C++" in the GNAT - reference manual. The mechanism used by GNAT for achieving such a goal - has been made user configurable through a GNAT library unit - @code{Interfaces.CPP}. The default version of this file is adapted to - the GNU c++ compiler. Internal knowledge of the virtual - table layout used by the new C++ compiler is needed to configure - properly this unit. The Interface of this unit is known by the compiler - and cannot be changed except for the value of the constants defining the - characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, - CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source - of this unit for more details. - - @node Comparison between GNAT and C/C++ Compilation Models - @section Comparison between GNAT and C/C++ Compilation Models - - @noindent - The GNAT model of compilation is close to the C and C++ models. You can - think of Ada specs as corresponding to header files in C. As in C, you - don't need to compile specs; they are compiled when they are used. The - Ada @code{with} is similar in effect to the @code{#include} of a C - header. - - One notable difference is that, in Ada, you may compile specs separately - to check them for semantic and syntactic accuracy. This is not always - possible with C headers because they are fragments of programs that have - less specific syntactic or semantic rules. - - The other major difference is the requirement for running the binder, - which performs two important functions. First, it checks for - consistency. In C or C++, the only defense against assembling - inconsistent programs lies outside the compiler, in a makefile, for - example. The binder satisfies the Ada requirement that it be impossible - to construct an inconsistent program when the compiler is used in normal - mode. - - @cindex Elaboration order control - The other important function of the binder is to deal with elaboration - issues. There are also elaboration issues in C++ that are handled - automatically. This automatic handling has the advantage of being - simpler to use, but the C++ programmer has no control over elaboration. - Where @code{gnatbind} might complain there was no valid order of - elaboration, a C++ compiler would simply construct a program that - malfunctioned at run time. - - @node Comparison between GNAT and Conventional Ada Library Models - @section Comparison between GNAT and Conventional Ada Library Models - - @noindent - This section is intended to be useful to Ada programmers who have - previously used an Ada compiler implementing the traditional Ada library - model, as described in the Ada 95 Language Reference Manual. If you - have not used such a system, please go on to the next section. - - @cindex GNAT library - In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of - source files themselves acts as the library. Compiling Ada programs does - not generate any centralized information, but rather an object file and - a ALI file, which are of interest only to the binder and linker. - In a traditional system, the compiler reads information not only from - the source file being compiled, but also from the centralized library. - This means that the effect of a compilation depends on what has been - previously compiled. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the version of the unit most recently compiled into the library. - - @item - Inlining is effective only if the necessary body has already been - compiled into the library. - - @item - Compiling a unit may obsolete other units in the library. - @end itemize - - @noindent - In GNAT, compiling one unit never affects the compilation of any other - units because the compiler reads only source files. Only changes to source - files can affect the results of a compilation. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the source version of the unit that is currently accessible to the - compiler. - - @item - @cindex Inlining - Inlining requires the appropriate source files for the package or - subprogram bodies to be available to the compiler. Inlining is always - effective, independent of the order in which units are complied. - - @item - Compiling a unit never affects any other compilations. The editing of - sources may cause previous compilations to be out of date if they - depended on the source file being modified. - @end itemize - - @noindent - The most important result of these differences is that order of compilation - is never significant in GNAT. There is no situation in which one is - required to do one compilation before another. What shows up as order of - compilation requirements in the traditional Ada library becomes, in - GNAT, simple source dependencies; in other words, there is only a set - of rules saying what source files must be present when a file is - compiled. - - @node Compiling Using gcc - @chapter Compiling Using @code{gcc} - - @noindent - This chapter discusses how to compile Ada programs using the @code{gcc} - command. It also describes the set of switches - that can be used to control the behavior of the compiler. - @menu - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - @end menu - - @node Compiling Programs - @section Compiling Programs - - @noindent - The first step in creating an executable program is to compile the units - of the program using the @code{gcc} command. You must compile the - following files: - - @itemize @bullet - @item - the body file (@file{.adb}) for a library level subprogram or generic - subprogram - - @item - the spec file (@file{.ads}) for a library level package or generic - package that has no body - - @item - the body file (@file{.adb}) for a library level package - or generic package that has a body - - @end itemize - - @noindent - You need @emph{not} compile the following files - - @itemize @bullet - - @item - the spec of a library unit which has a body - - @item - subunits - @end itemize - - @noindent - because they are compiled as part of compiling related units. GNAT - package specs - when the corresponding body is compiled, and subunits when the parent is - compiled. - @cindex No code generated - If you attempt to compile any of these files, you will get one of the - following error messages (where fff is the name of the file you compiled): - - @smallexample - No code generated for file @var{fff} (@var{package spec}) - No code generated for file @var{fff} (@var{subunit}) - @end smallexample - - @noindent - The basic command for compiling a file containing an Ada unit is - - @smallexample - $ gcc -c [@var{switches}] @file{file name} - @end smallexample - - @noindent - where @var{file name} is the name of the Ada file (usually - having an extension - @file{.ads} for a spec or @file{.adb} for a body). - @ifclear vms - You specify the - @code{-c} switch to tell @code{gcc} to compile, but not link, the file. - @end ifclear - The result of a successful compilation is an object file, which has the - same name as the source file but an extension of @file{.o} and an Ada - Library Information (ALI) file, which also has the same name as the - source file, but with @file{.ali} as the extension. GNAT creates these - two output files in the current directory, but you may specify a source - file in any directory using an absolute or relative path specification - containing the directory information. - - @findex gnat1 - @code{gcc} is actually a driver program that looks at the extensions of - the file arguments and loads the appropriate compiler. For example, the - GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}. - These programs are in directories known to the driver program (in some - configurations via environment variables you set), but need not be in - your path. The @code{gcc} driver also calls the assembler and any other - utilities needed to complete the generation of the required object - files. - - It is possible to supply several file names on the same @code{gcc} - command. This causes @code{gcc} to call the appropriate compiler for - each file. For example, the following command lists three separate - files to be compiled: - - @smallexample - $ gcc -c x.adb y.adb z.c - @end smallexample - - @noindent - calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and - @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}. - The compiler generates three object files @file{x.o}, @file{y.o} and - @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the - Ada compilations. Any switches apply to all the files ^listed,^listed.^ - @ifclear vms - except for - @option{-gnat@var{x}} switches, which apply only to Ada compilations. - @end ifclear - - @node Switches for gcc - @section Switches for @code{gcc} - - @noindent - The @code{gcc} command accepts switches that control the - compilation process. These switches are fully described in this section. - First we briefly list all the switches, in alphabetical order, then we - describe the switches in more detail in functionally grouped sections. - - @menu - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - @end menu - - @table @code - @ifclear vms - @cindex @code{-b} (@code{gcc}) - @item -b @var{target} - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gcc}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item -c - @cindex @code{-c} (@code{gcc}) - Compile. Always use this switch when compiling Ada programs. - - Note: for some other languages when using @code{gcc}, notably in - the case of C and C++, it is possible to use - use @code{gcc} without a @code{-c} switch to - compile and link in one step. In the case of GNAT, you - cannot use this approach, because the binder must be run - and @code{gcc} cannot be used to run the GNAT binder. - @end ifclear - - @item ^-g^/DEBUG^ - @cindex @code{^-g^/DEBUG^} (@code{gcc}) - Generate debugging information. This information is stored in the object - file and copied from there to the final executable file by the linker, - where it can be read by the debugger. You must use the - @code{^-g^/DEBUG^} switch if you plan on using the debugger. - - @item ^-I^/SEARCH=^@var{dir} - @cindex @code{^-I^/SEARCH^} (@code{gcc}) - @cindex RTL - Direct GNAT to search the @var{dir} directory for source files needed by - the current compilation - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item ^-I-^/NOCURRENT_DIRECTORY^ - @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc}) - @cindex RTL - Except for the source file named in the command line, do not look for source files - in the directory containing the source file named in the command line - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @ifclear vms - @item -o @var{file} - @cindex @code{-o} (@code{gcc}) - This switch is used in @code{gcc} to redirect the generated object file - and its associated ALI file. Beware of this switch with GNAT, because it may - cause the object file and ALI file to have different names which in turn - may confuse the binder and the linker. - @end ifclear - - @ifclear vms - @item -O[@var{n}] - @cindex @code{-O} (@code{gcc}) - @var{n} controls the optimization level. - - @table @asis - @item n = 0 - No optimization, the default setting if no @code{-O} appears - - @item n = 1 - Normal optimization, the default if you specify @code{-O} without - an operand. - - @item n = 2 - Extensive optimization - - @item n = 3 - Extensive optimization with automatic inlining. This applies only to - inlining within a unit. For details on control of inter-unit inlining - see @xref{Subprogram Inlining Control}. - @end table - @end ifclear - - @ifset vms - @item /NOOPTIMIZE (default) - @itemx /OPTIMIZE[=(keyword[,...])] - Selects the level of optimization for your program. The supported - keywords are as follows: - @table @code - @item ALL (default) - Perform most optimizations, including those that - be expensive. - - @item NONE - Do not do any optimizations. Same as @code{/NOOPTIMIZE}. - - @item SOME - Perform some optimizations, but omit ones that are costly. - - @item DEVELOPMENT - Same as @code{SOME}. - - @item INLINING - Full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - - @item UNROLL_LOOPS - Try to unroll loops. This keyword may be specified together with - any keyword above other than @code{NONE}. Loop unrolling - usually, but not always, improves the performance of programs. - @end table - @end ifset - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gcc}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item ^-S^/ASM^ - @cindex @code{^-S^/ASM^} (@code{gcc}) - ^Used in place of @code{-c} to^Used to^ - cause the assembler source file to be - generated, using @file{^.s^.S^} as the extension, - instead of the object file. - This may be useful if you need to examine the generated assembly code. - - @item ^-v^/VERBOSE^ - @cindex @code{^-v^/VERBOSE^} (@code{gcc}) - Show commands generated by the @code{gcc} driver. Normally used only for - debugging purposes or if you need to be sure what version of the - compiler you are executing. - - @ifclear vms - @item -V @var{ver} - @cindex @code{-V} (@code{gcc}) - Execute @var{ver} version of the compiler. This is the @code{gcc} - version, not the GNAT version. - @end ifclear - - @item -gnata - Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be - activated. - - @item -gnatA - Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored. - - @item -gnatb - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -gnatc - Check syntax and semantics only (no code generation attempted). - - @item -gnatC - Compress debug information and external symbol name table entries. - - @item -gnatD - Output expanded source files for source level debugging. This switch - also suppress generation of cross-reference information (see -gnatx). - - @item -gnatec@var{path} - Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files}) - - @item -gnatem@var{path} - Specify a mapping file. (see @ref{Units to Sources Mapping Files}) - - @item -gnatE - Full dynamic elaboration checks. - - @item -gnatf - Full errors. Multiple errors per line, all undefined references. - - @item -gnatF - Externals names are folded to all uppercase. - - @item -gnatg - Internal GNAT implementation mode. This should not be used for - applications programs, it is intended only for use by the compiler - and its run-time library. For documentation, see the GNAT sources. - - @item -gnatG - List generated expanded code in source form. - - @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c} - Identifier character set - @ifclear vms - (@var{c}=1/2/3/4/8/9/p/f/n/w). - @end ifclear - @ifset vms - For details of the possible selections for @var{c}, - see @xref{Character Set Control}. - @end ifset - - @item ^-gnath^/HELP^ - Output usage information. The output is written to @file{stdout}. - - @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n} - Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^. - - @item -gnatl - Output full source listing with embedded error messages. - - @item -gnatm^^=^@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item -gnatn - Activate inlining across unit boundaries for subprograms for which - pragma @code{inline} is specified. - - @item -gnatN - Activate front end inlining. - - @item ^-fno-inline^/INLINE=SUPPRESS^ - Suppresses all inlining, even if other optimization or inlining switches - are set. - - @ifclear vms - @item -fstack-check - Activates stack checking. See separate section on stack checking for - details of the use of this option. - @end ifclear - - @item -gnato - Enable numeric overflow checking (which is not normally enabled by - default). Not that division by zero is a separate check that is not - controlled by this switch (division by zero checking is on by default). - - @item -gnatp - Suppress all checks. - - @item -gnatq - Don't quit; try semantics, even if parse errors. - - @item -gnatQ - Don't quit; generate @file{ali} and tree files even if illegalities. - - @item -gnatP - Enable polling. This is required on some systems (notably Windows NT) to - obtain asynchronous abort and asynchronous transfer of control capability. - See the description of pragma Polling in the GNAT Reference Manual for - full details. - - @item -gnatR[0/1/2/3][s] - Output representation information for declared types and objects. - - @item -gnats - Syntax check only. - - @item -gnatt - Tree output file to be generated. - - @item -gnatT nnn - Set time slice to specified number of microseconds - - @item -gnatu - List units for this compilation. - - @item -gnatU - Tag all error messages with the unique string "error:" - - @item -gnatv - Verbose mode. Full error output with source lines to @file{stdout}. - - @item -gnatV - Control level of validity checking. See separate section describing - this feature. - - @item ^-gnatwxxx^/WARNINGS=^@var{xxx} - Warning mode where - @var{xxx} is a string of options describing the exact warnings that - are enabled or disabled. See separate section on warning control. - - @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e} - Wide character encoding method - @ifclear vms - (@var{e}=n/h/u/s/e/8). - @end ifclear - @ifset vms - (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8}) - @end ifset - - @item -gnatx - Suppress generation of cross-reference information. - - @item ^-gnaty^/STYLE_CHECKS=(option,option..)^ - Enable built-in style checks. See separate section describing this feature. - - @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m} - Distribution stub generation and compilation - @ifclear vms - (@var{m}=r/c for receiver/caller stubs). - @end ifclear - @ifset vms - (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs - to be generated and compiled). - @end ifset - - @item -gnat83 - Enforce Ada 83 restrictions. - - @ifclear vms - @item -pass-exit-codes - Catch exit codes from the compiler and use the most meaningful as - exit status. - @end ifclear - @end table - - @ifclear vms - You may combine a sequence of GNAT switches into a single switch. For - example, the combined switch - - @cindex Combining GNAT switches - @smallexample - -gnatofi3 - @end smallexample - - @noindent - is equivalent to specifying the following sequence of switches: - - @smallexample - -gnato -gnatf -gnati3 - @end smallexample - @end ifclear - - @noindent - The following restrictions apply to the combination of switches - in this manner: - - @itemize @bullet - @item - The switch @option{-gnatc} if combined with other switches must come - first in the string. - - @item - The switch @option{-gnats} if combined with other switches must come - first in the string. - - @item - Once a "y" appears in the string (that is a use of the @option{-gnaty} - switch), then all further characters in the switch are interpreted - as style modifiers (see description of @option{-gnaty}). - - @item - Once a "d" appears in the string (that is a use of the @option{-gnatd} - switch), then all further characters in the switch are interpreted - as debug flags (see description of @option{-gnatd}). - - @item - Once a "w" appears in the string (that is a use of the @option{-gnatw} - switch), then all further characters in the switch are interpreted - as warning mode modifiers (see description of @option{-gnatw}). - - @item - Once a "V" appears in the string (that is a use of the @option{-gnatV} - switch), then all further characters in the switch are interpreted - as validity checking options (see description of @option{-gnatV}). - - @end itemize - - @node Output and Error Message Control - @subsection Output and Error Message Control - @findex stderr - - @noindent - The standard default format for error messages is called "brief format." - Brief format messages are written to @file{stderr} (the standard error - file) and have the following form: - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:4:20: ";" should be "is" - @end smallexample - - @noindent - The first integer after the file name is the line number in the file, - and the second integer is the column number within the line. - @code{glide} can parse the error messages - and point to the referenced character. - The following switches provide control over the error message - format: - - @table @code - @item -gnatv - @cindex @option{-gnatv} (@code{gcc}) - @findex stdout - @ifclear vms - The v stands for verbose. - @end ifclear - The effect of this setting is to write long-format error - messages to @file{stdout} (the standard output file. - The same program compiled with the - @option{-gnatv} switch would generate: - - @smallexample - @group - @cartouche - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - @end cartouche - @end group - @end smallexample - - @noindent - The vertical bar indicates the location of the error, and the @samp{>>>} - prefix can be used to search for error messages. When this switch is - used the only source lines output are those with errors. - - @item -gnatl - @cindex @option{-gnatl} (@code{gcc}) - @ifclear vms - The @code{l} stands for list. - @end ifclear - This switch causes a full listing of - the file to be generated. The output might look as follows: - - @smallexample - @group - @cartouche - 1. procedure E is - 2. V : Integer; - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - 5. begin - 6. return Q + Q; - 7. end; - 8. begin - 9. V := X + X; - 10.end E; - @end cartouche - @end group - @end smallexample - - @noindent - @findex stderr - When you specify the @option{-gnatv} or @option{-gnatl} switches and - standard output is redirected, a brief summary is written to - @file{stderr} (standard error) giving the number of error messages and - warning messages generated. - - @item -gnatU - @cindex @option{-gnatU} (@code{gcc}) - This switch forces all error messages to be preceded by the unique - string "error:". This means that error messages take a few more - characters in space, but allows easy searching for and identification - of error messages. - - @item -gnatb - @cindex @option{-gnatb} (@code{gcc}) - @ifclear vms - The @code{b} stands for brief. - @end ifclear - This switch causes GNAT to generate the - brief format error messages to @file{stderr} (the standard error - file) as well as the verbose - format message or full listing (which as usual is written to - @file{stdout} (the standard output file). - - @item -gnatm^^=^@var{n} - @cindex @option{-gnatm} (@code{gcc}) - @ifclear vms - The @code{m} stands for maximum. - @end ifclear - @var{n} is a decimal integer in the - range of 1 to 999 and limits the number of error messages to be - generated. For example, using @option{-gnatm2} might yield - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:5:35: missing ".." - fatal error: maximum errors reached - compilation abandoned - @end smallexample - - @item -gnatf - @cindex @option{-gnatf} (@code{gcc}) - @cindex Error messages, suppressing - @ifclear vms - The @code{f} stands for full. - @end ifclear - Normally, the compiler suppresses error messages that are likely to be - redundant. This switch causes all error - messages to be generated. In particular, in the case of - references to undefined variables. If a given variable is referenced - several times, the normal format of messages is - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:7:07: "V" is undefined (more references follow) - @end smallexample - - @noindent - where the parenthetical comment warns that there are additional - references to the variable @code{V}. Compiling the same program with the - @option{-gnatf} switch yields - - @smallexample - e.adb:7:07: "V" is undefined - e.adb:8:07: "V" is undefined - e.adb:8:12: "V" is undefined - e.adb:8:16: "V" is undefined - e.adb:9:07: "V" is undefined - e.adb:9:12: "V" is undefined - @end smallexample - - @item -gnatq - @cindex @option{-gnatq} (@code{gcc}) - @ifclear vms - The @code{q} stands for quit (really "don't quit"). - @end ifclear - In normal operation mode, the compiler first parses the program and - determines if there are any syntax errors. If there are, appropriate - error messages are generated and compilation is immediately terminated. - This switch tells - GNAT to continue with semantic analysis even if syntax errors have been - found. This may enable the detection of more errors in a single run. On - the other hand, the semantic analyzer is more likely to encounter some - internal fatal error when given a syntactically invalid tree. - - @item -gnatQ - In normal operation mode, the @file{ali} file is not generated if any - illegalities are detected in the program. The use of @option{-gnatQ} forces - generation of the @file{ali} file. This file is marked as being in - error, so it cannot be used for binding purposes, but it does contain - reasonably complete cross-reference information, and thus may be useful - for use by tools (e.g. semantic browsing tools or integrated development - environments) that are driven from the @file{ali} file. - - In addition, if @option{-gnatt} is also specified, then the tree file is - generated even if there are illegalities. It may be useful in this case - to also specify @option{-gnatq} to ensure that full semantic processing - occurs. The resulting tree file can be processed by ASIS, for the purpose - of providing partial information about illegal units, but if the error - causes the tree to be badly malformed, then ASIS may crash during the - analysis. - - @end table - - @noindent - In addition to error messages, which correspond to illegalities as defined - in the Ada 95 Reference Manual, the compiler detects two kinds of warning - situations. - - @cindex Warning messages - First, the compiler considers some constructs suspicious and generates a - warning message to alert you to a possible error. Second, if the - compiler detects a situation that is sure to raise an exception at - run time, it generates a warning message. The following shows an example - of warning messages: - @smallexample - @iftex - @leftskip=.2cm - @end iftex - e.adb:4:24: warning: creation of object may raise Storage_Error - e.adb:10:17: warning: static value out of range - e.adb:10:17: warning: "Constraint_Error" will be raised at run time - - @end smallexample - - @noindent - GNAT considers a large number of situations as appropriate - for the generation of warning messages. As always, warnings are not - definite indications of errors. For example, if you do an out-of-range - assignment with the deliberate intention of raising a - @code{Constraint_Error} exception, then the warning that may be - issued does not indicate an error. Some of the situations for which GNAT - issues warnings (at least some of the time) are given in the following - list, which is not necessarily complete. - - @itemize @bullet - @item - Possible infinitely recursive calls - - @item - Out-of-range values being assigned - - @item - Possible order of elaboration problems - - @item - Unreachable code - - @item - Fixed-point type declarations with a null range - - @item - Variables that are never assigned a value - - @item - Variables that are referenced before being initialized - - @item - Task entries with no corresponding accept statement - - @item - Duplicate accepts for the same task entry in a select - - @item - Objects that take too much storage - - @item - Unchecked conversion between types of differing sizes - - @item - Missing return statements along some execution paths in a function - - @item - Incorrect (unrecognized) pragmas - - @item - Incorrect external names - - @item - Allocation from empty storage pool - - @item - Potentially blocking operations in protected types - - @item - Suspicious parenthesization of expressions - - @item - Mismatching bounds in an aggregate - - @item - Attempt to return local value by reference - - @item - Unrecognized pragmas - - @item - Premature instantiation of a generic body - - @item - Attempt to pack aliased components - - @item - Out of bounds array subscripts - - @item - Wrong length on string assignment - - @item - Violations of style rules if style checking is enabled - - @item - Unused with clauses - - @item - Bit_Order usage that does not have any effect - - @item - Compile time biased rounding of floating-point constant - - @item - Standard.Duration used to resolve universal fixed expression - - @item - Dereference of possibly null value - - @item - Declaration that is likely to cause storage error - - @item - Internal GNAT unit with'ed by application unit - - @item - Values known to be out of range at compile time - - @item - Unreferenced labels and variables - - @item - Address overlays that could clobber memory - - @item - Unexpected initialization when address clause present - - @item - Bad alignment for address clause - - @item - Useless type conversions - - @item - Redundant assignment statements - - @item - Accidental hiding of name by child unit - - @item - Unreachable code - - @item - Access before elaboration detected at compile time - - @item - A range in a @code{for} loop that is known to be null or might be null - - @end itemize - - @noindent - The following switches are available to control the handling of - warning messages: - - @table @code - @item -gnatwa (activate all optional errors) - @cindex @option{-gnatwa} (@code{gcc}) - This switch activates most optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. The warnings that are not turned on by this - switch are @option{-gnatwb} (biased rounding), - @option{-gnatwd} (implicit dereferencing), - and @option{-gnatwh} (hiding). All other optional warnings are - turned on. - - @item -gnatwA (suppress all optional errors) - @cindex @option{-gnatwA} (@code{gcc}) - This switch suppresses all optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. - - @item -gnatwb (activate warnings on biased rounding) - @cindex @option{-gnatwb} (@code{gcc}) - @cindex Rounding, biased - @cindex Biased rounding - If a static floating-point expression has a value that is exactly half - way between two adjacent machine numbers, then the rules of Ada - (Ada Reference Manual, section 4.9(38)) require that this rounding - be done away from zero, even if the normal unbiased rounding rules - at run time would require rounding towards zero. This warning message - alerts you to such instances where compile-time rounding and run-time - rounding are not equivalent. If it is important to get proper run-time - rounding, then you can force this by making one of the operands into - a variable. The default is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwB (suppress warnings on biased rounding) - @cindex @option{-gnatwB} (@code{gcc}) - This switch disables warnings on biased rounding. - - @item -gnatwc (activate warnings on conditionals) - @cindex @option{-gnatwc} (@code{gcc}) - @cindex Conditionals, constant - This switch activates warnings for conditional expressions used in - tests that are known to be True or False at compile time. The default - is that such warnings are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwC (suppress warnings on conditionals) - @cindex @option{-gnatwC} (@code{gcc}) - This switch suppresses warnings for conditional expressions used in - tests that are known to be True or False at compile time. - - @item -gnatwd (activate warnings on implicit dereferencing) - @cindex @option{-gnatwd} (@code{gcc}) - If this switch is set, then the use of a prefix of an access type - in an indexed component, slice, or selected component without an - explicit @code{.all} will generate a warning. With this warning - enabled, access checks occur only at points where an explicit - @code{.all} appears in the source code (assuming no warnings are - generated as a result of this switch). The default is that such - warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwD (suppress warnings on implicit dereferencing) - @cindex @option{-gnatwD} (@code{gcc}) - @cindex Implicit dereferencing - @cindex Dereferencing, implicit - This switch suppresses warnings for implicit deferences in - indexed components, slices, and selected components. - - @item -gnatwe (treat warnings as errors) - @cindex @option{-gnatwe} (@code{gcc}) - @cindex Warnings, treat as error - This switch causes warning messages to be treated as errors. - The warning string still appears, but the warning messages are counted - as errors, and prevent the generation of an object file. - - @item -gnatwf (activate warnings on unreferenced formals) - @cindex @option{-gnatwf} (@code{gcc}) - @cindex Formals, unreferenced - This switch causes a warning to be generated if a formal parameter - is not referenced in the body of the subprogram. This warning can - also be turned on using @option{-gnatwa} or @option{-gnatwu}. - - @item -gnatwF (suppress warnings on unreferenced formals) - @cindex @option{-gnatwF} (@code{gcc}) - This switch suppresses warnings for unreferenced formal - parameters. Note that the - combination @option{-gnatwu} followed by @option{-gnatwF} has the - effect of warning on unreferenced entities other than subprogram - formals. - - @item -gnatwh (activate warnings on hiding) - @cindex @option{-gnatwh} (@code{gcc}) - @cindex Hiding of Declarations - This switch activates warnings on hiding declarations. - A declaration is considered hiding - if it is for a non-overloadable entity, and it declares an entity with the - same name as some other entity that is directly or use-visible. The default - is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of this warning option. - - @item -gnatwH (suppress warnings on hiding) - @cindex @option{-gnatwH} (@code{gcc}) - This switch suppresses warnings on hiding declarations. - - @item -gnatwi (activate warnings on implementation units). - @cindex @option{-gnatwi} (@code{gcc}) - This switch activates warnings for a @code{with} of an internal GNAT - implementation unit, defined as any unit from the @code{Ada}, - @code{Interfaces}, @code{GNAT}, - ^^@code{DEC},^ or @code{System} - hierarchies that is not - documented in either the Ada Reference Manual or the GNAT - Programmer's Reference Manual. Such units are intended only - for internal implementation purposes and should not be @code{with}'ed - by user programs. The default is that such warnings are generated - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwI (disable warnings on implementation units). - @cindex @option{-gnatwI} (@code{gcc}) - This switch disables warnings for a @code{with} of an internal GNAT - implementation unit. - - @item -gnatwl (activate warnings on elaboration pragmas) - @cindex @option{-gnatwl} (@code{gcc}) - @cindex Elaboration, warnings - This switch activates warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. The default is that such warnings - are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwL (suppress warnings on elaboration pragmas) - @cindex @option{-gnatwL} (@code{gcc}) - This switch suppresses warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. - - @item -gnatwo (activate warnings on address clause overlays) - @cindex @option{-gnatwo} (@code{gcc}) - @cindex Address Clauses, warnings - This switch activates warnings for possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. The default is that such warnings are generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwO (suppress warnings on address clause overlays) - @cindex @option{-gnatwO} (@code{gcc}) - This switch suppresses warnings on possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. - - @item -gnatwp (activate warnings on ineffective pragma Inlines) - @cindex @option{-gnatwp} (@code{gcc}) - @cindex Inlining, warnings - This switch activates warnings for failure of front end inlining - (activated by @option{-gnatN}) to inline a particular call. There are - many reasons for not being able to inline a call, including most - commonly that the call is too complex to inline. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwP (suppress warnings on ineffective pragma Inlines) - @cindex @option{-gnatwP} (@code{gcc}) - This switch suppresses warnings on ineffective pragma Inlines. If the - inlining mechanism cannot inline a call, it will simply ignore the - request silently. - - @item -gnatwr (activate warnings on redundant constructs) - @cindex @option{-gnatwr} (@code{gcc}) - This switch activates warnings for redundant constructs. The following - is the current list of constructs regarded as redundant: - This warning can also be turned on using @option{-gnatwa}. - - @itemize @bullet - @item - Assignment of an item to itself. - @item - Type conversion that converts an expression to its own type. - @item - Use of the attribute @code{Base} where @code{typ'Base} is the same - as @code{typ}. - @item - Use of pragma @code{Pack} when all components are placed by a record - representation clause. - @end itemize - - @item -gnatwR (suppress warnings on redundant constructs) - @cindex @option{-gnatwR} (@code{gcc}) - This switch suppresses warnings for redundant constructs. - - @item -gnatws (suppress all warnings) - @cindex @option{-gnatws} (@code{gcc}) - This switch completely suppresses the - output of all warning messages from the GNAT front end. - Note that it does not suppress warnings from the @code{gcc} back end. - To suppress these back end warnings as well, use the switch @code{-w} - in addition to @option{-gnatws}. - - @item -gnatwu (activate warnings on unused entities) - @cindex @option{-gnatwu} (@code{gcc}) - This switch activates warnings to be generated for entities that - are defined but not referenced, and for units that are @code{with}'ed - and not - referenced. In the case of packages, a warning is also generated if - no entities in the package are referenced. This means that if the package - is referenced but the only references are in @code{use} - clauses or @code{renames} - declarations, a warning is still generated. A warning is also generated - for a generic package that is @code{with}'ed but never instantiated. - In the case where a package or subprogram body is compiled, and there - is a @code{with} on the corresponding spec - that is only referenced in the body, - a warning is also generated, noting that the - @code{with} can be moved to the body. The default is that - such warnings are not generated. - This switch also activates warnings on unreferenced formals - (it is includes the effect of @option{-gnatwf}). - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwU (suppress warnings on unused entities) - @cindex @option{-gnatwU} (@code{gcc}) - This switch suppresses warnings for unused entities and packages. - It also turns off warnings on unreferenced formals (and thus includes - the effect of @option{-gnatwF}). - - @noindent - A string of warning parameters can be used in the same parameter. For example: - - @smallexample - -gnatwaLe - @end smallexample - - @noindent - Would turn on all optional warnings except for elaboration pragma warnings, - and also specify that warnings should be treated as errors. - - @item -w - @cindex @code{-w} - This switch suppresses warnings from the @code{gcc} backend. It may be - used in conjunction with @option{-gnatws} to ensure that all warnings - are suppressed during the entire compilation process. - - @end table - - @node Debugging and Assertion Control - @subsection Debugging and Assertion Control - - @table @code - @item -gnata - @cindex @option{-gnata} (@code{gcc}) - @findex Assert - @findex Debug - @cindex Assertions - - @noindent - The pragmas @code{Assert} and @code{Debug} normally have no effect and - are ignored. This switch, where @samp{a} stands for assert, causes - @code{Assert} and @code{Debug} pragmas to be activated. - - The pragmas have the form: - - @smallexample - @group - @cartouche - @b{pragma} Assert (@var{Boolean-expression} [, - @var{static-string-expression}]) - @b{pragma} Debug (@var{procedure call}) - @end cartouche - @end group - @end smallexample - - @noindent - The @code{Assert} pragma causes @var{Boolean-expression} to be tested. - If the result is @code{True}, the pragma has no effect (other than - possible side effects from evaluating the expression). If the result is - @code{False}, the exception @code{Assert_Failure} declared in the package - @code{System.Assertions} is - raised (passing @var{static-string-expression}, if present, as the - message associated with the exception). If no string expression is - given the default is a string giving the file name and line number - of the pragma. - - The @code{Debug} pragma causes @var{procedure} to be called. Note that - @code{pragma Debug} may appear within a declaration sequence, allowing - debugging procedures to be called between declarations. - - @ifset vms - @item /DEBUG[=debug-level] - @itemx /NODEBUG - Specifies how much debugging information is to be included in - the resulting object file where 'debug-level' is one of the following: - @table @code - @item TRACEBACK (default) - Include both debugger symbol records and traceback - the object file. - @item ALL - Include both debugger symbol records and traceback in - object file. - @item NONE - Excludes both debugger symbol records and traceback - the object file. Same as /NODEBUG. - @item SYMBOLS - Includes only debugger symbol records in the object - file. Note that this doesn't include traceback information. - @end table - @end ifset - @end table - - @node Validity Checking - @subsection Validity Checking - @findex Validity Checking - - @noindent - The Ada 95 Reference Manual has specific requirements for checking - for invalid values. In particular, RM 13.9.1 requires that the - evaluation of invalid values (for example from unchecked conversions), - not result in erroneous execution. In GNAT, the result of such an - evaluation in normal default mode is to either use the value - unmodified, or to raise Constraint_Error in those cases where use - of the unmodified value would cause erroneous execution. The cases - where unmodified values might lead to erroneous execution are case - statements (where a wild jump might result from an invalid value), - and subscripts on the left hand side (where memory corruption could - occur as a result of an invalid value). - - The @option{-gnatVx} switch allows more control over the validity checking - mode. The @code{x} argument here is a string of letters which control which - validity checks are performed in addition to the default checks described - above. - - @itemize @bullet - @item - @option{-gnatVc} Validity checks for copies - - The right hand side of assignments, and the initializing values of - object declarations are validity checked. - - @item - @option{-gnatVd} Default (RM) validity checks - - Some validity checks are done by default following normal Ada semantics - (RM 13.9.1 (9-11)). - A check is done in case statements that the expression is within the range - of the subtype. If it is not, Constraint_Error is raised. - For assignments to array components, a check is done that the expression used - as index is within the range. If it is not, Constraint_Error is raised. - Both these validity checks may be turned off using switch @option{-gnatVD}. - They are turned on by default. If @option{-gnatVD} is specified, a subsequent - switch @option{-gnatVd} will leave the checks turned on. - Switch @option{-gnatVD} should be used only if you are sure that all such - expressions have valid values. If you use this switch and invalid values - are present, then the program is erroneous, and wild jumps or memory - overwriting may occur. - - @item - @option{-gnatVi} Validity checks for @code{in} mode parameters - - Arguments for parameters of mode @code{in} are validity checked in function - and procedure calls at the point of call. - - @item - @option{-gnatVm} Validity checks for @code{in out} mode parameters - - Arguments for parameters of mode @code{in out} are validity checked in - procedure calls at the point of call. The @code{'m'} here stands for - modify, since this concerns parameters that can be modified by the call. - Note that there is no specific option to test @code{out} parameters, - but any reference within the subprogram will be tested in the usual - manner, and if an invalid value is copied back, any reference to it - will be subject to validity checking. - - @item - @option{-gnatVo} Validity checks for operator and attribute operands - - Arguments for predefined operators and attributes are validity checked. - This includes all operators in package @code{Standard}, - the shift operators defined as intrinsic in package @code{Interfaces} - and operands for attributes such as @code{Pos}. - - @item - @option{-gnatVr} Validity checks for function returns - - The expression in @code{return} statements in functions is validity - checked. - - @item - @option{-gnatVs} Validity checks for subscripts - - All subscripts expressions are checked for validity, whether they appear - on the right side or left side (in default mode only left side subscripts - are validity checked). - - @item - @option{-gnatVt} Validity checks for tests - - Expressions used as conditions in @code{if}, @code{while} or @code{exit} - statements are checked, as well as guard expressions in entry calls. - - @item - @option{-gnatVf} Validity checks for floating-point values - - In the absence of this switch, validity checking occurs only for discrete - values. If @option{-gnatVf} is specified, then validity checking also applies - for floating-point values, and NaN's and infinities are considered invalid, - as well as out of range values for constrained types. Note that this means - that standard @code{IEEE} infinity mode is not allowed. The exact contexts - in which floating-point values are checked depends on the setting of other - options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does - not matter) specifies that floating-point parameters of mode @code{in} should - be validity checked. - - @item - @option{-gnatVa} All validity checks - - All the above validity checks are turned on. That is @option{-gnatVa} is - equivalent to @code{gnatVcdfimorst}. - - @item - @option{-gnatVn} No validity checks - - This switch turns off all validity checking, including the default checking - for case statements and left hand side subscripts. Note that the use of - the switch @option{-gnatp} supresses all run-time checks, including - validity checks, and thus implies @option{-gnatVn}. - - @end itemize - - The @option{-gnatV} switch may be followed by a string of letters to turn on - a series of validity checking options. For example, @option{-gnatVcr} specifies - that in addition to the default validity checking, copies and function - return expressions be validity checked. In order to make it easier to specify - a set of options, the upper case letters @code{CDFIMORST} may be used to turn - off the corresponding lower case option, so for example @option{-gnatVaM} turns - on all validity checking options except for checking of @code{in out} - procedure arguments. - - The specification of additional validity checking generates extra code (and - in the case of @option{-gnatva} the code expansion can be substantial. However, - these additional checks can be very useful in smoking out cases of - uninitialized variables, incorrect use of unchecked conversion, and other - errors leading to invalid values. The use of pragma @code{Initialize_Scalars} - is useful in conjunction with the extra validity checking, since this - ensures that wherever possible uninitialized variables have invalid values. - - See also the pragma @code{Validity_Checks} which allows modification of - the validity checking mode at the program source level, and also allows for - temporary disabling of validity checks. - - @node Style Checking - @subsection Style Checking - @findex Style checking - - @noindent - The -gnaty^@var{x}^(@var{option},@var{option},..)^ switch causes the compiler to - enforce specified style rules. A limited set of style rules has been used - in writing the GNAT sources themselves. This switch allows user programs - to activate all or some of these checks. If the source program fails a - specified style check, an appropriate warning message is given, preceded by - the character sequence "(style)". - @ifset vms - (OPTION,OPTION,..) is a sequence of keywords - @end ifset - @ifclear vms - The string @var{x} is a sequence of letters or digits - @end ifclear - indicating the particular style - checks to be performed. The following checks are defined: - - @table @code - @item 1-9 (specify indentation level) - If a digit from 1-9 appears in the string after @option{-gnaty} then proper - indentation is checked, with the digit indicating the indentation level - required. The general style of required indentation is as specified by - the examples in the Ada Reference Manual. Full line comments must be - aligned with the @code{--} starting on a column that is a multiple of - the alignment level. - - @item ^a^ATTRIBUTE^ (check attribute casing) - If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty} then - attribute names, including the case of keywords such as @code{digits} - used as attributes names, must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item ^b^BLANKS^ (blanks not allowed at statement end) - If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then - trailing blanks are not allowed at the end of statements. The purpose of this - rule, together with h (no horizontal tabs), is to enforce a canonical format - for the use of blanks to separate source tokens. - - @item ^c^COMMENTS^ (check comments) - If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty} then - comments must meet the following set of rules: - - @itemize @bullet - - @item - The "--" that starts the column must either start in column one, or else - at least one blank must precede this sequence. - - @item - Comments that follow other tokens on a line must have at least one blank - following the "--" at the start of the comment. - - @item - Full line comments must have two blanks following the "--" that starts - the comment, with the following exceptions. - - @item - A line consisting only of the "--" characters, possibly preceded by blanks - is permitted. - - @item - A comment starting with "--x" where x is a special character is permitted. - This alows proper processing of the output generated by specialized tools - including @code{gnatprep} (where --! is used) and the SPARK annnotation - language (where --# is used). For the purposes of this rule, a special - character is defined as being in one of the ASCII ranges - 16#21#..16#2F# or 16#3A#..16#3F#. - - @item - A line consisting entirely of minus signs, possibly preceded by blanks, is - permitted. This allows the construction of box comments where lines of minus - signs are used to form the top and bottom of the box. - - @item - If a comment starts and ends with "--" is permitted as long as at least - one blank follows the initial "--". Together with the preceding rule, - this allows the construction of box comments, as shown in the following - example: - @smallexample - --------------------------- - -- This is a box comment -- - -- with two text lines. -- - --------------------------- - @end smallexample - @end itemize - - @item ^e^END^ (check end/exit labels) - If the ^letter e^word END^ appears in the string after @option{-gnaty} then - optional labels on @code{end} statements ending subprograms and on - @code{exit} statements exiting named loops, are required to be present. - - @item ^f^VTABS^ (no form feeds or vertical tabs) - If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then - neither form feeds nor vertical tab characters are not permitted - in the source text. - - @item ^h^HTABS^ (no horizontal tabs) - If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then - horizontal tab characters are not permitted in the source text. - Together with the b (no blanks at end of line) check, this - enforces a canonical form for the use of blanks to separate - source tokens. - - @item ^i^IF_THEN^ (check if-then layout) - If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty}, - then the keyword @code{then} must appear either on the same - line as corresponding @code{if}, or on a line on its own, lined - up under the @code{if} with at least one non-blank line in between - containing all or part of the condition to be tested. - - @item ^k^KEYWORD^ (check keyword casing) - If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then - all keywords must be in lower case (with the exception of keywords - such as @code{digits} used as attribute names to which this check - does not apply). - - @item ^l^LAYOUT^ (check layout) - If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then - layout of statement and declaration constructs must follow the - recommendations in the Ada Reference Manual, as indicated by the - form of the syntax rules. For example an @code{else} keyword must - be lined up with the corresponding @code{if} keyword. - - There are two respects in which the style rule enforced by this check - option are more liberal than those in the Ada Reference Manual. First - in the case of record declarations, it is permissible to put the - @code{record} keyword on the same line as the @code{type} keyword, and - then the @code{end} in @code{end record} must line up under @code{type}. - For example, either of the following two layouts is acceptable: - - @smallexample - @group - @cartouche - @b{type} q @b{is record} - a : integer; - b : integer; - @b{end record}; - - @b{type} q @b{is} - @b{record} - a : integer; - b : integer; - @b{end record}; - @end cartouche - @end group - @end smallexample - - @noindent - Second, in the case of a block statement, a permitted alternative - is to put the block label on the same line as the @code{declare} or - @code{begin} keyword, and then line the @code{end} keyword up under - the block label. For example both the following are permitted: - - @smallexample - @group - @cartouche - Block : @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - - Block : - @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - @end cartouche - @end group - @end smallexample - - @noindent - The same alternative format is allowed for loops. For example, both of - the following are permitted: - - @smallexample - @group - @cartouche - Clear : @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - - Clear : - @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - @end cartouche - @end group - @end smallexample - - @item ^m^LINE_LENGTH^ (check maximum line length) - If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty} - then the length of source lines must not exceed 79 characters, including - any trailing blanks. The value of 79 allows convenient display on an - 80 character wide device or window, allowing for possible special - treatment of 80 character lines. - - @item ^Mnnn^MAX_LENGTH=nnn^ (set maximum line length) - If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in - the string after @option{-gnaty} then the length of lines must not exceed the - given value. - - @item ^n^STANDARD_CASING^ (check casing of entities in Standard) - If the ^letter n^word STANDARD_CASING^ appears in the string - after @option{-gnaty} then any identifier from Standard must be cased - to match the presentation in the Ada Reference Manual (for example, - @code{Integer} and @code{ASCII.NUL}). - - @item ^o^ORDERED_SUBPROGRAMS^ (check order of subprogram bodies) - If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string - after @option{-gnaty} then all subprogram bodies in a given scope - (e.g. a package body) must be in alphabetical order. The ordering - rule uses normal Ada rules for comparing strings, ignoring casing - of letters, except that if there is a trailing numeric suffix, then - the value of this suffix is used in the ordering (e.g. Junk2 comes - before Junk10). - - @item ^p^PRAGMA^ (check pragma casing) - If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then - pragma names must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item ^r^REFERENCES^ (check references) - If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty} - then all identifier references must be cased in the same way as the - corresponding declaration. No specific casing style is imposed on - identifiers. The only requirement is for consistency of references - with declarations. - - @item ^s^SPECS^ (check separate specs) - If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then - separate declarations ("specs") are required for subprograms (a - body is not allowed to serve as its own declaration). The only - exception is that parameterless library level procedures are - not required to have a separate declaration. This exception covers - the most frequent form of main program procedures. - - @item ^t^TOKEN^ (check token spacing) - If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then - the following token spacing rules are enforced: - - @itemize @bullet - - @item - The keywords @code{abs} and @code{not} must be followed by a space. - - @item - The token @code{=>} must be surrounded by spaces. - - @item - The token @code{<>} must be preceded by a space or a left parenthesis. - - @item - Binary operators other than @code{**} must be surrounded by spaces. - There is no restriction on the layout of the @code{**} binary operator. - - @item - Colon must be surrounded by spaces. - - @item - Colon-equal (assignment) must be surrounded by spaces. - - @item - Comma must be the first non-blank character on the line, or be - immediately preceded by a non-blank character, and must be followed - by a space. - - @item - If the token preceding a left paren ends with a letter or digit, then - a space must separate the two tokens. - - @item - A right parenthesis must either be the first non-blank character on - a line, or it must be preceded by a non-blank character. - - @item - A semicolon must not be preceded by a space, and must not be followed by - a non-blank character. - - @item - A unary plus or minus may not be followed by a space. - - @item - A vertical bar must be surrounded by spaces. - @end itemize - - @noindent - In the above rules, appearing in column one is always permitted, that is, - counts as meeting either a requirement for a required preceding space, - or as meeting a requirement for no preceding space. - - Appearing at the end of a line is also always permitted, that is, counts - as meeting either a requirement for a following space, or as meeting - a requirement for no following space. - - @end table - - @noindent - If any of these style rules is violated, a message is generated giving - details on the violation. The initial characters of such messages are - always "(style)". Note that these messages are treated as warning - messages, so they normally do not prevent the generation of an object - file. The @option{-gnatwe} switch can be used to treat warning messages, - including style messages, as fatal errors. - - @noindent - The switch - ^@option{-gnaty} on its own (that is not followed by any letters or digits),^/STYLE_CHECKS=ALL_BUILTIN^ - is equivalent to ^@code{gnaty3abcefhiklmprst}, that is^^ all checking - options ^are^^ enabled with - the exception of ^-gnatyo^ORDERED_SUBPROGRAMS^, - with an indentation level of 3. This is the standard - checking option that is used for the GNAT sources. - - @node Run-Time Checks - @subsection Run-Time Checks - @cindex Division by zero - @cindex Access before elaboration - @cindex Checks, division by zero - @cindex Checks, access before elaboration - - @noindent - If you compile with the default options, GNAT will insert many run-time - checks into the compiled code, including code that performs range - checking against constraints, but not arithmetic overflow checking for - integer operations (including division by zero) or checks for access - before elaboration on subprogram calls. All other run-time checks, as - required by the Ada 95 Reference Manual, are generated by default. - The following @code{gcc} switches refine this default behavior: - - @table @code - @item -gnatp - @cindex @option{-gnatp} (@code{gcc}) - @cindex Suppressing checks - @cindex Checks, suppressing - @findex Suppress - Suppress all run-time checks as though @code{pragma Suppress (all_checks}) - had been present in the source. Validity checks are also suppressed (in - other words @option{-gnatp} also implies @option{-gnatVn}. - Use this switch to improve the performance - of the code at the expense of safety in the presence of invalid data or - program bugs. - - @item -gnato - @cindex @option{-gnato} (@code{gcc}) - @cindex Overflow checks - @cindex Check, overflow - Enables overflow checking for integer operations. - This causes GNAT to generate slower and larger executable - programs by adding code to check for overflow (resulting in raising - @code{Constraint_Error} as required by standard Ada - semantics). These overflow checks correspond to situations in which - the true value of the result of an operation may be outside the base - range of the result type. The following example shows the distinction: - - @smallexample - X1 : Integer := Integer'Last; - X2 : Integer range 1 .. 5 := 5; - ... - X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error - X2 := X2 + 1; -- range check, @option{-gnato} has no effect here - @end smallexample - - @noindent - Here the first addition results in a value that is outside the base range - of Integer, and hence requires an overflow check for detection of the - constraint error. The second increment operation results in a violation - of the explicit range constraint, and such range checks are always - performed. Basically the compiler can assume that in the absence of - the @option{-gnato} switch that any value of type @code{xxx} is - in range of the base type of @code{xxx}. - - @findex Machine_Overflows - Note that the @option{-gnato} switch does not affect the code generated - for any floating-point operations; it applies only to integer - semantics). - For floating-point, GNAT has the @code{Machine_Overflows} - attribute set to @code{False} and the normal mode of operation is to - generate IEEE NaN and infinite values on overflow or invalid operations - (such as dividing 0.0 by 0.0). - - The reason that we distinguish overflow checking from other kinds of - range constraint checking is that a failure of an overflow check can - generate an incorrect value, but cannot cause erroneous behavior. This - is unlike the situation with a constraint check on an array subscript, - where failure to perform the check can result in random memory description, - or the range check on a case statement, where failure to perform the check - can cause a wild jump. - - Note again that @option{-gnato} is off by default, so overflow checking is - not performed in default mode. This means that out of the box, with the - default settings, GNAT does not do all the checks expected from the - language description in the Ada Reference Manual. If you want all constraint - checks to be performed, as described in this Manual, then you must - explicitly use the -gnato switch either on the @code{gnatmake} or - @code{gcc} command. - - @item -gnatE - @cindex @option{-gnatE} (@code{gcc}) - @cindex Elaboration checks - @cindex Check, elaboration - Enables dynamic checks for access-before-elaboration - on subprogram calls and generic instantiations. - For full details of the effect and use of this switch, - @xref{Compiling Using gcc}. - @end table - - @findex Unsuppress - @noindent - The setting of these switches only controls the default setting of the - checks. You may modify them using either @code{Suppress} (to remove - checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in - the program source. - - @node Stack Overflow Checking - @subsection Stack Overflow Checking - @cindex Stack Overflow Checking - @cindex -fstack-check - - @noindent - For most operating systems, @code{gcc} does not perform stack overflow - checking by default. This means that if the main environment task or - some other task exceeds the available stack space, then unpredictable - behavior will occur. - - To activate stack checking, compile all units with the gcc option - @code{-fstack-check}. For example: - - @smallexample - gcc -c -fstack-check package1.adb - @end smallexample - - @noindent - Units compiled with this option will generate extra instructions to check - that any use of the stack (for procedure calls or for declaring local - variables in declare blocks) do not exceed the available stack space. - If the space is exceeded, then a @code{Storage_Error} exception is raised. - - For declared tasks, the stack size is always controlled by the size - given in an applicable @code{Storage_Size} pragma (or is set to - the default size if no pragma is used. - - For the environment task, the stack size depends on - system defaults and is unknown to the compiler. The stack - may even dynamically grow on some systems, precluding the - normal Ada semantics for stack overflow. In the worst case, - unbounded stack usage, causes unbounded stack expansion - resulting in the system running out of virtual memory. - - The stack checking may still work correctly if a fixed - size stack is allocated, but this cannot be guaranteed. - To ensure that a clean exception is signalled for stack - overflow, set the environment variable - @code{GNAT_STACK_LIMIT} to indicate the maximum - stack area that can be used, as in: - @cindex GNAT_STACK_LIMIT - - @smallexample - SET GNAT_STACK_LIMIT 1600 - @end smallexample - - @noindent - The limit is given in kilobytes, so the above declaration would - set the stack limit of the environment task to 1.6 megabytes. - Note that the only purpose of this usage is to limit the amount - of stack used by the environment task. If it is necessary to - increase the amount of stack for the environment task, then this - is an operating systems issue, and must be addressed with the - appropriate operating systems commands. - - @node Run-Time Control - @subsection Run-Time Control - - @table @code - @item -gnatT nnn - @cindex @option{-gnatT} (@code{gcc}) - @cindex Time Slicing - - @noindent - The @code{gnatT} switch can be used to specify the time-slicing value - to be used for task switching between equal priority tasks. The value - @code{nnn} is given in microseconds as a decimal integer. - - Setting the time-slicing value is only effective if the underlying thread - control system can accommodate time slicing. Check the documentation of - your operating system for details. Note that the time-slicing value can - also be set by use of pragma @code{Time_Slice} or by use of the - @code{t} switch in the gnatbind step. The pragma overrides a command - line argument if both are present, and the @code{t} switch for gnatbind - overrides both the pragma and the @code{gcc} command line switch. - @end table - - @node Using gcc for Syntax Checking - @subsection Using @code{gcc} for Syntax Checking - @table @code - @item -gnats - @cindex @option{-gnats} (@code{gcc}) - @ifclear vms - - @noindent - The @code{s} stands for syntax. - @end ifclear - - Run GNAT in syntax checking only mode. For - example, the command - - @smallexample - $ gcc -c -gnats x.adb - @end smallexample - - @noindent - compiles file @file{x.adb} in syntax-check-only mode. You can check a - series of files in a single command - @ifclear vms - , and can use wild cards to specify such a group of files. - Note that you must specify the @code{-c} (compile - only) flag in addition to the @option{-gnats} flag. - @end ifclear - . - - You may use other switches in conjunction with @option{-gnats}. In - particular, @option{-gnatl} and @option{-gnatv} are useful to control the - format of any generated error messages. - - The output is simply the error messages, if any. No object file or ALI - file is generated by a syntax-only compilation. Also, no units other - than the one specified are accessed. For example, if a unit @code{X} - @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax - check only mode does not access the source file containing unit - @code{Y}. - - @cindex Multiple units, syntax checking - Normally, GNAT allows only a single unit in a source file. However, this - restriction does not apply in syntax-check-only mode, and it is possible - to check a file containing multiple compilation units concatenated - together. This is primarily used by the @code{gnatchop} utility - (@pxref{Renaming Files Using gnatchop}). - @end table - - @node Using gcc for Semantic Checking - @subsection Using @code{gcc} for Semantic Checking - @table @code - @item -gnatc - @cindex @option{-gnatc} (@code{gcc}) - - @ifclear vms - @noindent - The @code{c} stands for check. - @end ifclear - Causes the compiler to operate in semantic check mode, - with full checking for all illegalities specified in the - Ada 95 Reference Manual, but without generation of any object code - (no object file is generated). - - Because dependent files must be accessed, you must follow the GNAT - semantic restrictions on file structuring to operate in this mode: - - @itemize @bullet - @item - The needed source files must be accessible - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item - Each file must contain only one compilation unit. - - @item - The file name and unit name must match (@pxref{File Naming Rules}). - @end itemize - - The output consists of error messages as appropriate. No object file is - generated. An @file{ALI} file is generated for use in the context of - cross-reference tools, but this file is marked as not being suitable - for binding (since no object file is generated). - The checking corresponds exactly to the notion of - legality in the Ada 95 Reference Manual. - - Any unit can be compiled in semantics-checking-only mode, including - units that would not normally be compiled (subunits, - and specifications where a separate body is present). - @end table - - @node Compiling Ada 83 Programs - @subsection Compiling Ada 83 Programs - @table @code - @cindex Ada 83 compatibility - @item -gnat83 - @cindex @option{-gnat83} (@code{gcc}) - @cindex ACVC, Ada 83 tests - - @noindent - Although GNAT is primarily an Ada 95 compiler, it accepts this switch to - specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify - this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics - where this can be done easily. - It is not possible to guarantee this switch does a perfect - job; for example, some subtle tests, such as are - found in earlier ACVC tests (that have been removed from the ACVC suite for Ada - 95), may not compile correctly. However, for most purposes, using - this switch should help to ensure that programs that compile correctly - under the @option{-gnat83} switch can be ported easily to an Ada 83 - compiler. This is the main use of the switch. - - With few exceptions (most notably the need to use @code{<>} on - @cindex Generic formal parameters - unconstrained generic formal parameters, the use of the new Ada 95 - keywords, and the use of packages - with optional bodies), it is not necessary to use the - @option{-gnat83} switch when compiling Ada 83 programs, because, with rare - exceptions, Ada 95 is upwardly compatible with Ada 83. This - means that a correct Ada 83 program is usually also a correct Ada 95 - program. - - @end table - - @node Character Set Control - @subsection Character Set Control - @table @code - @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c} - @cindex @code{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc}) - - @noindent - Normally GNAT recognizes the Latin-1 character set in source program - identifiers, as described in the Ada 95 Reference Manual. - This switch causes - GNAT to recognize alternate character sets in identifiers. @var{c} is a - single character ^^or word^ indicating the character set, as follows: - - @table @code - @item 1 - Latin-1 identifiers - - @item 2 - Latin-2 letters allowed in identifiers - - @item 3 - Latin-3 letters allowed in identifiers - - @item 4 - Latin-4 letters allowed in identifiers - - @item 5 - Latin-5 (Cyrillic) letters allowed in identifiers - - @item 9 - Latin-9 letters allowed in identifiers - - @item ^p^PC^ - IBM PC letters (code page 437) allowed in identifiers - - @item ^8^PC850^ - IBM PC letters (code page 850) allowed in identifiers - - @item ^f^FULL_UPPER^ - Full upper-half codes allowed in identifiers - - @item ^n^NO_UPPER^ - No upper-half codes allowed in identifiers - - @item ^w^WIDE^ - Wide-character codes (that is, codes greater than 255) - allowed in identifiers - @end table - - @xref{Foreign Language Representation}, for full details on the - implementation of these character sets. - - @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e} - @cindex @code{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc}) - Specify the method of encoding for wide characters. - @var{e} is one of the following: - - @table @code - - @item ^h^HEX^ - Hex encoding (brackets coding also recognized) - - @item ^u^UPPER^ - Upper half encoding (brackets encoding also recognized) - - @item ^s^SHIFT_JIS^ - Shift/JIS encoding (brackets encoding also recognized) - - @item ^e^EUC^ - EUC encoding (brackets encoding also recognized) - - @item ^8^UTF8^ - UTF-8 encoding (brackets encoding also recognized) - - @item ^b^BRACKETS^ - Brackets encoding only (default value) - @end table - For full details on the these encoding - methods see @xref{Wide Character Encodings}. - Note that brackets coding is always accepted, even if one of the other - options is specified, so for example @option{-gnatW8} specifies that both - brackets and @code{UTF-8} encodings will be recognized. The units that are - with'ed directly or indirectly will be scanned using the specified - representation scheme, and so if one of the non-brackets scheme is - used, it must be used consistently throughout the program. However, - since brackets encoding is always recognized, it may be conveniently - used in standard libraries, allowing these libraries to be used with - any of the available coding schemes. - scheme. If no @option{-gnatW?} parameter is present, then the default - representation is Brackets encoding only. - - Note that the wide character representation that is specified (explicitly - or by default) for the main program also acts as the default encoding used - for Wide_Text_IO files if not specifically overridden by a WCEM form - parameter. - - @end table - @node File Naming Control - @subsection File Naming Control - - @table @code - @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n} - @cindex @option{-gnatk} (@code{gcc}) - Activates file name "krunching". @var{n}, a decimal integer in the range - 1-999, indicates the maximum allowable length of a file name (not - including the @file{.ads} or @file{.adb} extension). The default is not - to enable file name krunching. - - For the source file naming rules, @xref{File Naming Rules}. - @end table - - @node Subprogram Inlining Control - @subsection Subprogram Inlining Control - - @table @code - @item -gnatn - @cindex @option{-gnatn} (@code{gcc}) - @ifclear vms - The @code{n} here is intended to suggest the first syllable of the - word "inline". - @end ifclear - GNAT recognizes and processes @code{Inline} pragmas. However, for the - inlining to actually occur, optimization must be enabled. To enable - inlining across unit boundaries, this is, inlining a call in one unit of - a subprogram declared in a @code{with}'ed unit, you must also specify - this switch. - In the absence of this switch, GNAT does not attempt - inlining across units and does not need to access the bodies of - subprograms for which @code{pragma Inline} is specified if they are not - in the current unit. - - If you specify this switch the compiler will access these bodies, - creating an extra source dependency for the resulting object file, and - where possible, the call will be inlined. - For further details on when inlining is possible - see @xref{Inlining of Subprograms}. - - @item -gnatN - @cindex @option{-gnatN} (@code{gcc}) - The front end inlining activated by this switch is generally more extensive, - and quite often more effective than the standard @option{-gnatn} inlining mode. - It will also generate additional dependencies. - - @end table - - @node Auxiliary Output Control - @subsection Auxiliary Output Control - - @table @code - @item -gnatt - @cindex @option{-gnatt} (@code{gcc}) - @cindex Writing internal trees - @cindex Internal trees, writing to file - Causes GNAT to write the internal tree for a unit to a file (with the - extension @file{.adt}. - This not normally required, but is used by separate analysis tools. - Typically - these tools do the necessary compilations automatically, so you should - not have to specify this switch in normal operation. - - @item -gnatu - @cindex @option{-gnatu} (@code{gcc}) - Print a list of units required by this compilation on @file{stdout}. - The listing includes all units on which the unit being compiled depends - either directly or indirectly. - - @ifclear vms - @item -pass-exit-codes - @cindex @code{-pass-exit-codes} (@code{gcc}) - If this switch is not used, the exit code returned by @code{gcc} when - compiling multiple files indicates whether all source files have - been successfully used to generate object files or not. - - When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended - exit status and allows an integrated development environment to better - react to a compilation failure. Those exit status are: - - @table @asis - @item 5 - There was an error in at least one source file. - @item 3 - At least one source file did not generate an object file. - @item 2 - The compiler died unexpectedly (internal error for example). - @item 0 - An object file has been generated for every source file. - @end table - @end ifclear - @end table - - @node Debugging Control - @subsection Debugging Control - - @table @code - @cindex Debugging options - @ifclear vms - @item -gnatd@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - outputs desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Debug} unit in the compiler source - file @file{debug.adb}. - @end ifclear - - @item -gnatG - @cindex @option{-gnatG} (@code{gcc}) - This switch causes the compiler to generate auxiliary output containing - a pseudo-source listing of the generated expanded code. Like most Ada - compilers, GNAT works by first transforming the high level Ada code into - lower level constructs. For example, tasking operations are transformed - into calls to the tasking run-time routines. A unique capability of GNAT - is to list this expanded code in a form very close to normal Ada source. - This is very useful in understanding the implications of various Ada - usage on the efficiency of the generated code. There are many cases in - Ada (e.g. the use of controlled types), where simple Ada statements can - generate a lot of run-time code. By using @option{-gnatG} you can identify - these cases, and consider whether it may be desirable to modify the coding - approach to improve efficiency. - - The format of the output is very similar to standard Ada source, and is - easily understood by an Ada programmer. The following special syntactic - additions correspond to low level features used in the generated code that - do not have any exact analogies in pure Ada source form. The following - is a partial list of these special constructions. See the specification - of package @code{Sprint} in file @file{sprint.ads} for a full list. - - @table @code - @item new @var{xxx} [storage_pool = @var{yyy}] - Shows the storage pool being used for an allocator. - - @item at end @var{procedure-name}; - Shows the finalization (cleanup) procedure for a scope. - - @item (if @var{expr} then @var{expr} else @var{expr}) - Conditional expression equivalent to the @code{x?y:z} construction in C. - - @item @var{target}^^^(@var{source}) - A conversion with floating-point truncation instead of rounding. - - @item @var{target}?(@var{source}) - A conversion that bypasses normal Ada semantic checking. In particular - enumeration types and fixed-point types are treated simply as integers. - - @item @var{target}?^^^(@var{source}) - Combines the above two cases. - - @item @var{x} #/ @var{y} - @itemx @var{x} #mod @var{y} - @itemx @var{x} #* @var{y} - @itemx @var{x} #rem @var{y} - A division or multiplication of fixed-point values which are treated as - integers without any kind of scaling. - - @item free @var{expr} [storage_pool = @var{xxx}] - Shows the storage pool associated with a @code{free} statement. - - @item freeze @var{typename} [@var{actions}] - Shows the point at which @var{typename} is frozen, with possible - associated actions to be performed at the freeze point. - - @item reference @var{itype} - Reference (and hence definition) to internal type @var{itype}. - - @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) - Intrinsic function call. - - @item @var{labelname} : label - Declaration of label @var{labelname}. - - @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr} - A multiple concatenation (same effect as @var{expr} & @var{expr} & - @var{expr}, but handled more efficiently). - - @item [constraint_error] - Raise the @code{Constraint_Error} exception. - - @item @var{expression}'reference - A pointer to the result of evaluating @var{expression}. - - @item @var{target-type}!(@var{source-expression}) - An unchecked conversion of @var{source-expression} to @var{target-type}. - - @item [@var{numerator}/@var{denominator}] - Used to represent internal real literals (that) have no exact - representation in base 2-16 (for example, the result of compile time - evaluation of the expression 1.0/27.0). - - @item -gnatD - @cindex @option{-gnatD} (@code{gcc}) - This switch is used in conjunction with @option{-gnatG} to cause the expanded - source, as described above to be written to files with names - @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name, - for example, if the source file name is @file{hello.adb}, - then a file @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. - The debugging information generated - by the @code{gcc} @code{^-g^/DEBUG^} switch will refer to the generated - @file{^xxx.dg^XXX_DG^} file. This allows you to do source level debugging using - the generated code which is sometimes useful for complex code, for example - to find out exactly which part of a complex construction raised an - exception. This switch also suppress generation of cross-reference - information (see -gnatx). - - @item -gnatC - @cindex @option{-gnatE} (@code{gcc}) - In the generated debugging information, and also in the case of long external - names, the compiler uses a compression mechanism if the name is very long. - This compression method uses a checksum, and avoids trouble on some operating - systems which have difficulty with very long names. The @option{-gnatC} switch - forces this compression approach to be used on all external names and names - in the debugging information tables. This reduces the size of the generated - executable, at the expense of making the naming scheme more complex. The - compression only affects the qualification of the name. Thus a name in - the source: - - @smallexample - Very_Long_Package.Very_Long_Inner_Package.Var - @end smallexample - - @noindent - would normally appear in these tables as: - - @smallexample - very_long_package__very_long_inner_package__var - @end smallexample - - @noindent - but if the @option{-gnatC} switch is used, then the name appears as - - @smallexample - XCb7e0c705__var - @end smallexample - - @noindent - Here b7e0c705 is a compressed encoding of the qualification prefix. - The GNAT Ada aware version of GDB understands these encoded prefixes, so if this - debugger is used, the encoding is largely hidden from the user of the compiler. - - @end table - - @item -gnatR[0|1|2|3][s] - @cindex @option{-gnatR} (@code{gcc}) - This switch controls output from the compiler of a listing showing - representation information for declared types and objects. For - @option{-gnatR0}, no information is output (equivalent to omitting - the @option{-gnatR} switch). For @option{-gnatR1} (which is the default, - so @option{-gnatR} with no parameter has the same effect), size and alignment - information is listed for declared array and record types. For - @option{-gnatR2}, size and alignment information is listed for all - expression information for values that are computed at run time for - variant records. These symbolic expressions have a mostly obvious - format with #n being used to represent the value of the n'th - discriminant. See source files @file{repinfo.ads/adb} in the - @code{GNAT} sources for full detalis on the format of @option{-gnatR3} - output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then - the output is to a file with the name @file{^file.rep^file_REP^} where - file is the name of the corresponding source file. - - @item -gnatx - @cindex @option{-gnatx} (@code{gcc}) - Normally the compiler generates full cross-referencing information in - the @file{ALI} file. This information is used by a number of tools, - including @code{gnatfind} and @code{gnatxref}. The -gnatx switch - suppresses this information. This saves some space and may slightly - speed up compilation, but means that these tools cannot be used. - @end table - - @node Units to Sources Mapping Files - @subsection Units to Sources Mapping Files - - @table @code - - @item -gnatem@var{path} - @cindex @option{-gnatem} (@code{gcc}) - A mapping file is a way to communicate to the compiler two mappings: - from unit names to file names (without any directory information) and from - file names to path names (with full directory information). These mappings - are used by the compiler to short-circuit the path search. - - A mapping file is a sequence of sets of three lines. In each set, - the first line is the unit name, in lower case, with "%s" appended for - specifications and "%b" appended for bodies; the second line is the file - name; and the third line is the path name. - - Example: - @smallexample - main%b - main.2.ada - /gnat/project1/sources/main.2.ada - @end smallexample - - When the switch @option{-gnatem} is specified, the compiler will create - in memory the two mappings from the specified file. If there is any problem - (non existent file, truncated file or duplicate entries), no mapping - will be created. - - Several @option{-gnatem} switches may be specified; however, only the last - one on the command line will be taken into account. - - When using a project file, @code{gnatmake} create a temporary mapping file - and communicates it to the compiler using this switch. - - @end table - - @node Search Paths and the Run-Time Library (RTL) - @section Search Paths and the Run-Time Library (RTL) - - @noindent - With the GNAT source-based library system, the compiler must be able to - find source files for units that are needed by the unit being compiled. - Search paths are used to guide this process. - - The compiler compiles one source file whose name must be given - explicitly on the command line. In other words, no searching is done - for this file. To find all other source files that are needed (the most - common being the specs of units), the compiler examines the following - directories, in the following order: - - @enumerate - @item - The directory containing the source file of the main unit being compiled - (the file name on the command line). - - @item - Each directory named by an @code{^-I^/SOURCE_SEARCH^} switch given on the @code{gcc} - command line, in the order given. - - @item - @findex ADA_INCLUDE_PATH - Each of the directories listed in the value of the - @code{ADA_INCLUDE_PATH} ^environment variable^logical name^. - @ifclear vms - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version). - @end ifclear - @ifset vms - Normally, define this value as a logical name containing a comma separated - list of directory names. - - This variable can also be defined by means of an environment string - (an argument to the DEC C exec* set of functions). - - Logical Name: - @smallexample - DEFINE ANOTHER_PATH FOO:[BAG] - DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] - @end smallexample - - By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] - first, followed by the standard Ada 95 - libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE]. - If this is not redefined, the user will obtain the DEC Ada83 IO packages - (Text_IO, Sequential_IO, etc) - instead of the Ada95 packages. Thus, in order to get the Ada 95 - packages by default, ADA_INCLUDE_PATH must be redefined. - @end ifset - @item - The content of the "ada_source_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) source files. - @ifclear vms - @ref{Installing an Ada Library} - @end ifclear - @end enumerate - - @noindent - Specifying the switch @code{^-I-^/NOCURRENT_DIRECTORY^} - inhibits the use of the directory - containing the source file named in the command line. You can still - have this directory on your search path, but in this case it must be - explicitly requested with a @code{^-I^/SOURCE_SEARCH^} switch. - - Specifying the switch @code{-nostdinc} - inhibits the search of the default location for the GNAT Run Time - Library (RTL) source files. - - The compiler outputs its object files and ALI files in the current - working directory. - @ifclear vms - Caution: The object file can be redirected with the @code{-o} switch; - however, @code{gcc} and @code{gnat1} have not been coordinated on this - so the ALI file will not go to the right place. Therefore, you should - avoid using the @code{-o} switch. - @end ifclear - - @findex System.IO - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT RTL, together with the simple @code{System.IO} - package used in the "Hello World" example. The sources for these units - are needed by the compiler and are kept together in one directory. Not - all of the bodies are needed, but all of the sources are kept together - anyway. In a normal installation, you need not specify these directory - names when compiling or binding. Either the environment variables or - the built-in defaults cause these files to be found. - - In addition to the language-defined hierarchies (System, Ada and - Interfaces), the GNAT distribution provides a fourth hierarchy, - consisting of child units of GNAT. This is a collection of generally - useful routines. See the GNAT Reference Manual for further details. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Order of Compilation Issues - @section Order of Compilation Issues - - @noindent - If, in our earlier example, there was a spec for the @code{hello} - procedure, it would be contained in the file @file{hello.ads}; yet this - file would not have to be explicitly compiled. This is the result of the - model we chose to implement library management. Some of the consequences - of this model are as follows: - - @itemize @bullet - @item - There is no point in compiling specs (except for package - specs with no bodies) because these are compiled as needed by clients. If - you attempt a useless compilation, you will receive an error message. - It is also useless to compile subunits because they are compiled as needed - by the parent. - - @item - There are no order of compilation requirements: performing a - compilation never obsoletes anything. The only way you can obsolete - something and require recompilations is to modify one of the - source files on which it depends. - - @item - There is no library as such, apart from the ALI files - (@pxref{The Ada Library Information Files}, for information on the format of these - files). For now we find it convenient to create separate ALI files, but - eventually the information therein may be incorporated into the object - file directly. - - @item - When you compile a unit, the source files for the specs of all units - that it @code{with}'s, all its subunits, and the bodies of any generics it - instantiates must be available (reachable by the search-paths mechanism - described above), or you will receive a fatal error message. - @end itemize - - @node Examples - @section Examples - - @noindent - The following are some typical Ada compilation command line examples: - - @table @code - @item $ gcc -c xyz.adb - Compile body in file @file{xyz.adb} with all default options. - - @ifclear vms - @item $ gcc -c -O2 -gnata xyz-def.adb - @end ifclear - @ifset vms - @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb - @end ifset - - Compile the child unit package in file @file{xyz-def.adb} with extensive - optimizations, and pragma @code{Assert}/@code{Debug} statements - enabled. - - @item $ gcc -c -gnatc abc-def.adb - Compile the subunit in file @file{abc-def.adb} in semantic-checking-only - mode. - @end table - - @node Binding Using gnatbind - @chapter Binding Using @code{gnatbind} - @findex gnatbind - - @menu - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - @end menu - - @noindent - This chapter describes the GNAT binder, @code{gnatbind}, which is used - to bind compiled GNAT objects. The @code{gnatbind} program performs - four separate functions: - - @enumerate - @item - Checks that a program is consistent, in accordance with the rules in - Chapter 10 of the Ada 95 Reference Manual. In particular, error - messages are generated if a program uses inconsistent versions of a - given unit. - - @item - Checks that an acceptable order of elaboration exists for the program - and issues an error message if it cannot find an order of elaboration - that satisfies the rules in Chapter 10 of the Ada 95 Language Manual. - - @item - Generates a main program incorporating the given elaboration order. - This program is a small Ada package (body and spec) that - must be subsequently compiled - using the GNAT compiler. The necessary compilation step is usually - performed automatically by @code{gnatlink}. The two most important - functions of this program - are to call the elaboration routines of units in an appropriate order - and to call the main program. - - @item - Determines the set of object files required by the given main program. - This information is output in the forms of comments in the generated program, - to be read by the @code{gnatlink} utility used to link the Ada application. - @end enumerate - - @node Running gnatbind - @section Running @code{gnatbind} - - @noindent - The form of the @code{gnatbind} command is - - @smallexample - $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}] - @end smallexample - - @noindent - where @var{mainprog}.adb is the Ada file containing the main program - unit body. If no switches are specified, @code{gnatbind} constructs an Ada - package in two files which names are - @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}. - For example, if given the - parameter @samp{hello.ali}, for a main program contained in file - @file{hello.adb}, the binder output files would be @file{b~hello.ads} - and @file{b~hello.adb}. - - When doing consistency checking, the binder takes into consideration - any source files it can locate. For example, if the binder determines - that the given main program requires the package @code{Pack}, whose - @file{.ali} - file is @file{pack.ali} and whose corresponding source spec file is - @file{pack.ads}, it attempts to locate the source file @file{pack.ads} - (using the same search path conventions as previously described for the - @code{gcc} command). If it can locate this source file, it checks that - the time stamps - or source checksums of the source and its references to in @file{ali} files - match. In other words, any @file{ali} files that mentions this spec must have - resulted from compiling this version of the source file (or in the case - where the source checksums match, a version close enough that the - difference does not matter). - - @cindex Source files, use by binder - The effect of this consistency checking, which includes source files, is - that the binder ensures that the program is consistent with the latest - version of the source files that can be located at bind time. Editing a - source file without compiling files that depend on the source file cause - error messages to be generated by the binder. - - For example, suppose you have a main program @file{hello.adb} and a - package @code{P}, from file @file{p.ads} and you perform the following - steps: - - @enumerate - @item - Enter @code{gcc -c hello.adb} to compile the main program. - - @item - Enter @code{gcc -c p.ads} to compile package @code{P}. - - @item - Edit file @file{p.ads}. - - @item - Enter @code{gnatbind hello}. - @end enumerate - - At this point, the file @file{p.ali} contains an out-of-date time stamp - because the file @file{p.ads} has been edited. The attempt at binding - fails, and the binder generates the following error messages: - - @smallexample - error: "hello.adb" must be recompiled ("p.ads" has been modified) - error: "p.ads" has been modified and must be recompiled - @end smallexample - - @noindent - Now both files must be recompiled as indicated, and then the bind can - succeed, generating a main program. You need not normally be concerned - with the contents of this file, but it is similar to the following which - is the binder file generated for a simple "hello world" program. - - @smallexample - @iftex - @leftskip=0cm - @end iftex - -- The package is called Ada_Main unless this name is actually used - -- as a unit name in the partition, in which case some other unique - -- name is used. - - with System; - package ada_main is - - Elab_Final_Code : Integer; - pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); - - -- The main program saves the parameters (argument count, - -- argument values, environment pointer) in global variables - -- for later access by other units including - -- Ada.Command_Line. - - gnat_argc : Integer; - gnat_argv : System.Address; - gnat_envp : System.Address; - - -- The actual variables are stored in a library routine. This - -- is useful for some shared library situations, where there - -- are problems if variables are not in the library. - - pragma Import (C, gnat_argc); - pragma Import (C, gnat_argv); - pragma Import (C, gnat_envp); - - -- The exit status is similarly an external location - - gnat_exit_status : Integer; - pragma Import (C, gnat_exit_status); - - GNAT_Version : constant String := - "GNAT Version: 3.15w (20010315)"; - pragma Export (C, GNAT_Version, "__gnat_version"); - - -- This is the generated adafinal routine that performs - -- finalization at the end of execution. In the case where - -- Ada is the main program, this main program makes a call - -- to adafinal at program termination. - - procedure adafinal; - pragma Export (C, adafinal, "adafinal"); - - -- This is the generated adainit routine that performs - -- initialization at the start of execution. In the case - -- where Ada is the main program, this main program makes - -- a call to adainit at program startup. - - procedure adainit; - pragma Export (C, adainit, "adainit"); - - -- This routine is called at the start of execution. It is - -- a dummy routine that is used by the debugger to breakpoint - -- at the start of execution. - - procedure Break_Start; - pragma Import (C, Break_Start, "__gnat_break_start"); - - -- This is the actual generated main program (it would be - -- suppressed if the no main program switch were used). As - -- required by standard system conventions, this program has - -- the external name main. - - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer; - pragma Export (C, main, "main"); - - -- The following set of constants give the version - -- identification values for every unit in the bound - -- partition. This identification is computed from all - -- dependent semantic units, and corresponds to the - -- string that would be returned by use of the - -- Body_Version or Version attributes. - - type Version_32 is mod 2 ** 32; - u00001 : constant Version_32 := 16#7880BEB3#; - u00002 : constant Version_32 := 16#0D24CBD0#; - u00003 : constant Version_32 := 16#3283DBEB#; - u00004 : constant Version_32 := 16#2359F9ED#; - u00005 : constant Version_32 := 16#664FB847#; - u00006 : constant Version_32 := 16#68E803DF#; - u00007 : constant Version_32 := 16#5572E604#; - u00008 : constant Version_32 := 16#46B173D8#; - u00009 : constant Version_32 := 16#156A40CF#; - u00010 : constant Version_32 := 16#033DABE0#; - u00011 : constant Version_32 := 16#6AB38FEA#; - u00012 : constant Version_32 := 16#22B6217D#; - u00013 : constant Version_32 := 16#68A22947#; - u00014 : constant Version_32 := 16#18CC4A56#; - u00015 : constant Version_32 := 16#08258E1B#; - u00016 : constant Version_32 := 16#367D5222#; - u00017 : constant Version_32 := 16#20C9ECA4#; - u00018 : constant Version_32 := 16#50D32CB6#; - u00019 : constant Version_32 := 16#39A8BB77#; - u00020 : constant Version_32 := 16#5CF8FA2B#; - u00021 : constant Version_32 := 16#2F1EB794#; - u00022 : constant Version_32 := 16#31AB6444#; - u00023 : constant Version_32 := 16#1574B6E9#; - u00024 : constant Version_32 := 16#5109C189#; - u00025 : constant Version_32 := 16#56D770CD#; - u00026 : constant Version_32 := 16#02F9DE3D#; - u00027 : constant Version_32 := 16#08AB6B2C#; - u00028 : constant Version_32 := 16#3FA37670#; - u00029 : constant Version_32 := 16#476457A0#; - u00030 : constant Version_32 := 16#731E1B6E#; - u00031 : constant Version_32 := 16#23C2E789#; - u00032 : constant Version_32 := 16#0F1BD6A1#; - u00033 : constant Version_32 := 16#7C25DE96#; - u00034 : constant Version_32 := 16#39ADFFA2#; - u00035 : constant Version_32 := 16#571DE3E7#; - u00036 : constant Version_32 := 16#5EB646AB#; - u00037 : constant Version_32 := 16#4249379B#; - u00038 : constant Version_32 := 16#0357E00A#; - u00039 : constant Version_32 := 16#3784FB72#; - u00040 : constant Version_32 := 16#2E723019#; - u00041 : constant Version_32 := 16#623358EA#; - u00042 : constant Version_32 := 16#107F9465#; - u00043 : constant Version_32 := 16#6843F68A#; - u00044 : constant Version_32 := 16#63305874#; - u00045 : constant Version_32 := 16#31E56CE1#; - u00046 : constant Version_32 := 16#02917970#; - u00047 : constant Version_32 := 16#6CCBA70E#; - u00048 : constant Version_32 := 16#41CD4204#; - u00049 : constant Version_32 := 16#572E3F58#; - u00050 : constant Version_32 := 16#20729FF5#; - u00051 : constant Version_32 := 16#1D4F93E8#; - u00052 : constant Version_32 := 16#30B2EC3D#; - u00053 : constant Version_32 := 16#34054F96#; - u00054 : constant Version_32 := 16#5A199860#; - u00055 : constant Version_32 := 16#0E7F912B#; - u00056 : constant Version_32 := 16#5760634A#; - u00057 : constant Version_32 := 16#5D851835#; - - -- The following Export pragmas export the version numbers - -- with symbolic names ending in B (for body) or S - -- (for spec) so that they can be located in a link. The - -- information provided here is sufficient to track down - -- the exact versions of units used in a given build. - - pragma Export (C, u00001, "helloB"); - pragma Export (C, u00002, "system__standard_libraryB"); - pragma Export (C, u00003, "system__standard_libraryS"); - pragma Export (C, u00004, "adaS"); - pragma Export (C, u00005, "ada__text_ioB"); - pragma Export (C, u00006, "ada__text_ioS"); - pragma Export (C, u00007, "ada__exceptionsB"); - pragma Export (C, u00008, "ada__exceptionsS"); - pragma Export (C, u00009, "gnatS"); - pragma Export (C, u00010, "gnat__heap_sort_aB"); - pragma Export (C, u00011, "gnat__heap_sort_aS"); - pragma Export (C, u00012, "systemS"); - pragma Export (C, u00013, "system__exception_tableB"); - pragma Export (C, u00014, "system__exception_tableS"); - pragma Export (C, u00015, "gnat__htableB"); - pragma Export (C, u00016, "gnat__htableS"); - pragma Export (C, u00017, "system__exceptionsS"); - pragma Export (C, u00018, "system__machine_state_operationsB"); - pragma Export (C, u00019, "system__machine_state_operationsS"); - pragma Export (C, u00020, "system__machine_codeS"); - pragma Export (C, u00021, "system__storage_elementsB"); - pragma Export (C, u00022, "system__storage_elementsS"); - pragma Export (C, u00023, "system__secondary_stackB"); - pragma Export (C, u00024, "system__secondary_stackS"); - pragma Export (C, u00025, "system__parametersB"); - pragma Export (C, u00026, "system__parametersS"); - pragma Export (C, u00027, "system__soft_linksB"); - pragma Export (C, u00028, "system__soft_linksS"); - pragma Export (C, u00029, "system__stack_checkingB"); - pragma Export (C, u00030, "system__stack_checkingS"); - pragma Export (C, u00031, "system__tracebackB"); - pragma Export (C, u00032, "system__tracebackS"); - pragma Export (C, u00033, "ada__streamsS"); - pragma Export (C, u00034, "ada__tagsB"); - pragma Export (C, u00035, "ada__tagsS"); - pragma Export (C, u00036, "system__string_opsB"); - pragma Export (C, u00037, "system__string_opsS"); - pragma Export (C, u00038, "interfacesS"); - pragma Export (C, u00039, "interfaces__c_streamsB"); - pragma Export (C, u00040, "interfaces__c_streamsS"); - pragma Export (C, u00041, "system__file_ioB"); - pragma Export (C, u00042, "system__file_ioS"); - pragma Export (C, u00043, "ada__finalizationB"); - pragma Export (C, u00044, "ada__finalizationS"); - pragma Export (C, u00045, "system__finalization_rootB"); - pragma Export (C, u00046, "system__finalization_rootS"); - pragma Export (C, u00047, "system__finalization_implementationB"); - pragma Export (C, u00048, "system__finalization_implementationS"); - pragma Export (C, u00049, "system__string_ops_concat_3B"); - pragma Export (C, u00050, "system__string_ops_concat_3S"); - pragma Export (C, u00051, "system__stream_attributesB"); - pragma Export (C, u00052, "system__stream_attributesS"); - pragma Export (C, u00053, "ada__io_exceptionsS"); - pragma Export (C, u00054, "system__unsigned_typesS"); - pragma Export (C, u00055, "system__file_control_blockS"); - pragma Export (C, u00056, "ada__finalization__list_controllerB"); - pragma Export (C, u00057, "ada__finalization__list_controllerS"); - - -- BEGIN ELABORATION ORDER - -- ada (spec) - -- gnat (spec) - -- gnat.heap_sort_a (spec) - -- gnat.heap_sort_a (body) - -- gnat.htable (spec) - -- gnat.htable (body) - -- interfaces (spec) - -- system (spec) - -- system.machine_code (spec) - -- system.parameters (spec) - -- system.parameters (body) - -- interfaces.c_streams (spec) - -- interfaces.c_streams (body) - -- system.standard_library (spec) - -- ada.exceptions (spec) - -- system.exception_table (spec) - -- system.exception_table (body) - -- ada.io_exceptions (spec) - -- system.exceptions (spec) - -- system.storage_elements (spec) - -- system.storage_elements (body) - -- system.machine_state_operations (spec) - -- system.machine_state_operations (body) - -- system.secondary_stack (spec) - -- system.stack_checking (spec) - -- system.soft_links (spec) - -- system.soft_links (body) - -- system.stack_checking (body) - -- system.secondary_stack (body) - -- system.standard_library (body) - -- system.string_ops (spec) - -- system.string_ops (body) - -- ada.tags (spec) - -- ada.tags (body) - -- ada.streams (spec) - -- system.finalization_root (spec) - -- system.finalization_root (body) - -- system.string_ops_concat_3 (spec) - -- system.string_ops_concat_3 (body) - -- system.traceback (spec) - -- system.traceback (body) - -- ada.exceptions (body) - -- system.unsigned_types (spec) - -- system.stream_attributes (spec) - -- system.stream_attributes (body) - -- system.finalization_implementation (spec) - -- system.finalization_implementation (body) - -- ada.finalization (spec) - -- ada.finalization (body) - -- ada.finalization.list_controller (spec) - -- ada.finalization.list_controller (body) - -- system.file_control_block (spec) - -- system.file_io (spec) - -- system.file_io (body) - -- ada.text_io (spec) - -- ada.text_io (body) - -- hello (body) - -- END ELABORATION ORDER - - end ada_main; - - -- The following source file name pragmas allow the generated file - -- names to be unique for different main programs. They are needed - -- since the package name will always be Ada_Main. - - pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads"); - pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb"); - - -- Generated package body for Ada_Main starts here - - package body ada_main is - - -- The actual finalization is performed by calling the - -- library routine in System.Standard_Library.Adafinal - - procedure Do_Finalize; - pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); - - ------------- - -- adainit -- - ------------- - - @findex adainit - procedure adainit is - - -- These booleans are set to True once the associated unit has - -- been elaborated. It is also used to avoid elaborating the - -- same unit twice. - - E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E"); - E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E"); - E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E"); - E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E"); - E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E"); - E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E"); - E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E"); - E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E"); - E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E"); - E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E"); - E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E"); - E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E"); - E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E"); - E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E"); - E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E"); - E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E"); - E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E"); - - -- Set_Globals is a library routine that stores away the - -- value of the indicated set of global values in global - -- variables within the library. - - procedure Set_Globals - (Main_Priority : Integer; - Time_Slice_Value : Integer; - WC_Encoding : Character; - Locking_Policy : Character; - Queuing_Policy : Character; - Task_Dispatching_Policy : Character; - Adafinal : System.Address; - Unreserve_All_Interrupts : Integer; - Exception_Tracebacks : Integer); - @findex __gnat_set_globals - pragma Import (C, Set_Globals, "__gnat_set_globals"); - - -- SDP_Table_Build is a library routine used to build the - -- exception tables. See unit Ada.Exceptions in files - -- a-except.ads/adb for full details of how zero cost - -- exception handling works. This procedure, the call to - -- it, and the two following tables are all omitted if the - -- build is in longjmp/setjump exception mode. - - @findex SDP_Table_Build - @findex Zero Cost Exceptions - procedure SDP_Table_Build - (SDP_Addresses : System.Address; - SDP_Count : Natural; - Elab_Addresses : System.Address; - Elab_Addr_Count : Natural); - pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); - - -- Table of Unit_Exception_Table addresses. Used for zero - -- cost exception handling to build the top level table. - - ST : aliased constant array (1 .. 23) of System.Address := ( - Hello'UET_Address, - Ada.Text_Io'UET_Address, - Ada.Exceptions'UET_Address, - Gnat.Heap_Sort_A'UET_Address, - System.Exception_Table'UET_Address, - System.Machine_State_Operations'UET_Address, - System.Secondary_Stack'UET_Address, - System.Parameters'UET_Address, - System.Soft_Links'UET_Address, - System.Stack_Checking'UET_Address, - System.Traceback'UET_Address, - Ada.Streams'UET_Address, - Ada.Tags'UET_Address, - System.String_Ops'UET_Address, - Interfaces.C_Streams'UET_Address, - System.File_Io'UET_Address, - Ada.Finalization'UET_Address, - System.Finalization_Root'UET_Address, - System.Finalization_Implementation'UET_Address, - System.String_Ops_Concat_3'UET_Address, - System.Stream_Attributes'UET_Address, - System.File_Control_Block'UET_Address, - Ada.Finalization.List_Controller'UET_Address); - - -- Table of addresses of elaboration routines. Used for - -- zero cost exception handling to make sure these - -- addresses are included in the top level procedure - -- address table. - - EA : aliased constant array (1 .. 23) of System.Address := ( - adainit'Code_Address, - Do_Finalize'Code_Address, - Ada.Exceptions'Elab_Spec'Address, - System.Exceptions'Elab_Spec'Address, - Interfaces.C_Streams'Elab_Spec'Address, - System.Exception_Table'Elab_Body'Address, - Ada.Io_Exceptions'Elab_Spec'Address, - System.Stack_Checking'Elab_Spec'Address, - System.Soft_Links'Elab_Body'Address, - System.Secondary_Stack'Elab_Body'Address, - Ada.Tags'Elab_Spec'Address, - Ada.Tags'Elab_Body'Address, - Ada.Streams'Elab_Spec'Address, - System.Finalization_Root'Elab_Spec'Address, - Ada.Exceptions'Elab_Body'Address, - System.Finalization_Implementation'Elab_Spec'Address, - System.Finalization_Implementation'Elab_Body'Address, - Ada.Finalization'Elab_Spec'Address, - Ada.Finalization.List_Controller'Elab_Spec'Address, - System.File_Control_Block'Elab_Spec'Address, - System.File_Io'Elab_Body'Address, - Ada.Text_Io'Elab_Spec'Address, - Ada.Text_Io'Elab_Body'Address); - - -- Start of processing for adainit - - begin - - -- Call SDP_Table_Build to build the top level procedure - -- table for zero cost exception handling (omitted in - -- longjmp/setjump mode). - - SDP_Table_Build (ST'Address, 23, EA'Address, 23); - - -- Call Set_Globals to record various information for - -- this partition. The values are derived by the binder - -- from information stored in the ali files by the compiler. - - @findex __gnat_set_globals - Set_Globals - (Main_Priority => -1, - -- Priority of main program, -1 if no pragma Priority used - - Time_Slice_Value => -1, - -- Time slice from Time_Slice pragma, -1 if none used - - WC_Encoding => 'b', - -- Wide_Character encoding used, default is brackets - - Locking_Policy => ' ', - -- Locking_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Queuing_Policy => ' ', - -- Queuing_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Task_Dispatching_Policy => ' ', - -- Task_Dispatching_Policy used, default of space means - -- not specified, otherwise first character of the - -- policy name. - - Adafinal => System.Null_Address, - -- Address of Adafinal routine, not used anymore - - Unreserve_All_Interrupts => 0, - -- Set true if pragma Unreserve_All_Interrupts was used - - Exception_Tracebacks => 0); - -- Indicates if exception tracebacks are enabled - - Elab_Final_Code := 1; - - -- Now we have the elaboration calls for all units in the partition. - -- The Elab_Spec and Elab_Body attributes generate references to the - -- implicit elaboration procedures generated by the compiler for - -- each unit that requires elaboration. - - if not E040 then - Interfaces.C_Streams'Elab_Spec; - end if; - E040 := True; - if not E008 then - Ada.Exceptions'Elab_Spec; - end if; - if not E014 then - System.Exception_Table'Elab_Body; - E014 := True; - end if; - if not E053 then - Ada.Io_Exceptions'Elab_Spec; - E053 := True; - end if; - if not E017 then - System.Exceptions'Elab_Spec; - E017 := True; - end if; - if not E030 then - System.Stack_Checking'Elab_Spec; - end if; - if not E028 then - System.Soft_Links'Elab_Body; - E028 := True; - end if; - E030 := True; - if not E024 then - System.Secondary_Stack'Elab_Body; - E024 := True; - end if; - if not E035 then - Ada.Tags'Elab_Spec; - end if; - if not E035 then - Ada.Tags'Elab_Body; - E035 := True; - end if; - if not E033 then - Ada.Streams'Elab_Spec; - E033 := True; - end if; - if not E046 then - System.Finalization_Root'Elab_Spec; - end if; - E046 := True; - if not E008 then - Ada.Exceptions'Elab_Body; - E008 := True; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Spec; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Body; - E048 := True; - end if; - if not E044 then - Ada.Finalization'Elab_Spec; - end if; - E044 := True; - if not E057 then - Ada.Finalization.List_Controller'Elab_Spec; - end if; - E057 := True; - if not E055 then - System.File_Control_Block'Elab_Spec; - E055 := True; - end if; - if not E042 then - System.File_Io'Elab_Body; - E042 := True; - end if; - if not E006 then - Ada.Text_Io'Elab_Spec; - end if; - if not E006 then - Ada.Text_Io'Elab_Body; - E006 := True; - end if; - - Elab_Final_Code := 0; - end adainit; - - -------------- - -- adafinal -- - -------------- - - @findex adafinal - procedure adafinal is - begin - Do_Finalize; - end adafinal; - - ---------- - -- main -- - ---------- - - -- main is actually a function, as in the ANSI C standard, - -- defined to return the exit status. The three parameters - -- are the argument count, argument values and environment - -- pointer. - - @findex Main Program - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer - is - -- The initialize routine performs low level system - -- initialization using a standard library routine which - -- sets up signal handling and performs any other - -- required setup. The routine can be found in file - -- a-init.c. - - @findex __gnat_initialize - procedure initialize; - pragma Import (C, initialize, "__gnat_initialize"); - - -- The finalize routine performs low level system - -- finalization using a standard library routine. The - -- routine is found in file a-final.c and in the standard - -- distribution is a dummy routine that does nothing, so - -- really this is a hook for special user finalization. - - @findex __gnat_finalize - procedure finalize; - pragma Import (C, finalize, "__gnat_finalize"); - - -- We get to the main program of the partition by using - -- pragma Import because if we try to with the unit and - -- call it Ada style, then not only do we waste time - -- recompiling it, but also, we don't really know the right - -- switches (e.g. identifier character set) to be used - -- to compile it. - - procedure Ada_Main_Program; - pragma Import (Ada, Ada_Main_Program, "_ada_hello"); - - -- Start of processing for main - - begin - -- Save global variables - - gnat_argc := argc; - gnat_argv := argv; - gnat_envp := envp; - - -- Call low level system initialization - - Initialize; - - -- Call our generated Ada initialization routine - - adainit; - - -- This is the point at which we want the debugger to get - -- control - - Break_Start; - - -- Now we call the main program of the partition - - Ada_Main_Program; - - -- Perform Ada finalization - - adafinal; - - -- Perform low level system finalization - - Finalize; - - -- Return the proper exit status - return (gnat_exit_status); - end; - - -- This section is entirely comments, so it has no effect on the - -- compilation of the Ada_Main package. It provides the list of - -- object files and linker options, as well as some standard - -- libraries needed for the link. The gnatlink utility parses - -- this b~hello.adb file to read these comment lines to generate - -- the appropriate command line arguments for the call to the - -- system linker. The BEGIN/END lines are used for sentinels for - -- this parsing operation. - - -- The exact file names will of course depend on the environment, - -- host/target and location of files on the host system. - - @findex Object file list - -- BEGIN Object file/option list - -- ./hello.o - -- -L./ - -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ - -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a - -- END Object file/option list - - end ada_main; - - @end smallexample - - @noindent - The Ada code in the above example is exactly what is generated by the - binder. We have added comments to more clearly indicate the function - of each part of the generated @code{Ada_Main} package. - - The code is standard Ada in all respects, and can be processed by any - tools that handle Ada. In particular, it is possible to use the debugger - in Ada mode to debug the generated Ada_Main package. For example, suppose - that for reasons that you do not understand, your program is blowing up - during elaboration of the body of @code{Ada.Text_IO}. To chase this bug - down, you can place a breakpoint on the call: - - @smallexample - Ada.Text_Io'Elab_Body; - @end smallexample - - @noindent - and trace the elaboration routine for this package to find out where - the problem might be (more usually of course you would be debugging - elaboration code in your own application). - - @node Generating the Binder Program in C - @section Generating the Binder Program in C - @noindent - In most normal usage, the default mode of @code{gnatbind} which is to - generate the main package in Ada, as described in the previous section. - In particular, this means that any Ada programmer can read and understand - the generated main program. It can also be debugged just like any other - Ada code provided the @code{-g} switch is used for @code{gnatbind} - and @code{gnatlink}. - - However for some purposes it may be convenient to generate the main - program in C rather than Ada. This may for example be helpful when you - are generating a mixed language program with the main program in C. The - GNAT compiler itself is an example. The use of the @code{-C} switch - for both @code{gnatbind} and @code{gnatlink} will cause the program to - be generated in C (and compiled using the gnu C compiler). The - following shows the C code generated for the same "Hello World" - program: - - @smallexample - - #ifdef __STDC__ - #define PARAMS(paramlist) paramlist - #else - #define PARAMS(paramlist) () - #endif - - extern void __gnat_set_globals - PARAMS ((int, int, int, int, int, int, - void (*) PARAMS ((void)), int, int)); - extern void adafinal PARAMS ((void)); - extern void adainit PARAMS ((void)); - extern void system__standard_library__adafinal PARAMS ((void)); - extern int main PARAMS ((int, char **, char **)); - extern void exit PARAMS ((int)); - extern void __gnat_break_start PARAMS ((void)); - extern void _ada_hello PARAMS ((void)); - extern void __gnat_initialize PARAMS ((void)); - extern void __gnat_finalize PARAMS ((void)); - - extern void ada__exceptions___elabs PARAMS ((void)); - extern void system__exceptions___elabs PARAMS ((void)); - extern void interfaces__c_streams___elabs PARAMS ((void)); - extern void system__exception_table___elabb PARAMS ((void)); - extern void ada__io_exceptions___elabs PARAMS ((void)); - extern void system__stack_checking___elabs PARAMS ((void)); - extern void system__soft_links___elabb PARAMS ((void)); - extern void system__secondary_stack___elabb PARAMS ((void)); - extern void ada__tags___elabs PARAMS ((void)); - extern void ada__tags___elabb PARAMS ((void)); - extern void ada__streams___elabs PARAMS ((void)); - extern void system__finalization_root___elabs PARAMS ((void)); - extern void ada__exceptions___elabb PARAMS ((void)); - extern void system__finalization_implementation___elabs PARAMS ((void)); - extern void system__finalization_implementation___elabb PARAMS ((void)); - extern void ada__finalization___elabs PARAMS ((void)); - extern void ada__finalization__list_controller___elabs PARAMS ((void)); - extern void system__file_control_block___elabs PARAMS ((void)); - extern void system__file_io___elabb PARAMS ((void)); - extern void ada__text_io___elabs PARAMS ((void)); - extern void ada__text_io___elabb PARAMS ((void)); - - extern int __gnat_inside_elab_final_code; - - extern int gnat_argc; - extern char **gnat_argv; - extern char **gnat_envp; - extern int gnat_exit_status; - - char __gnat_version[] = "GNAT Version: 3.15w (20010315)"; - void adafinal () @{ - system__standard_library__adafinal (); - @} - - void adainit () - @{ - extern char ada__exceptions_E; - extern char system__exceptions_E; - extern char interfaces__c_streams_E; - extern char system__exception_table_E; - extern char ada__io_exceptions_E; - extern char system__secondary_stack_E; - extern char system__stack_checking_E; - extern char system__soft_links_E; - extern char ada__tags_E; - extern char ada__streams_E; - extern char system__finalization_root_E; - extern char system__finalization_implementation_E; - extern char ada__finalization_E; - extern char ada__finalization__list_controller_E; - extern char system__file_control_block_E; - extern char system__file_io_E; - extern char ada__text_io_E; - - extern void *__gnat_hello__SDP; - extern void *__gnat_ada__text_io__SDP; - extern void *__gnat_ada__exceptions__SDP; - extern void *__gnat_gnat__heap_sort_a__SDP; - extern void *__gnat_system__exception_table__SDP; - extern void *__gnat_system__machine_state_operations__SDP; - extern void *__gnat_system__secondary_stack__SDP; - extern void *__gnat_system__parameters__SDP; - extern void *__gnat_system__soft_links__SDP; - extern void *__gnat_system__stack_checking__SDP; - extern void *__gnat_system__traceback__SDP; - extern void *__gnat_ada__streams__SDP; - extern void *__gnat_ada__tags__SDP; - extern void *__gnat_system__string_ops__SDP; - extern void *__gnat_interfaces__c_streams__SDP; - extern void *__gnat_system__file_io__SDP; - extern void *__gnat_ada__finalization__SDP; - extern void *__gnat_system__finalization_root__SDP; - extern void *__gnat_system__finalization_implementation__SDP; - extern void *__gnat_system__string_ops_concat_3__SDP; - extern void *__gnat_system__stream_attributes__SDP; - extern void *__gnat_system__file_control_block__SDP; - extern void *__gnat_ada__finalization__list_controller__SDP; - - void **st[23] = @{ - &__gnat_hello__SDP, - &__gnat_ada__text_io__SDP, - &__gnat_ada__exceptions__SDP, - &__gnat_gnat__heap_sort_a__SDP, - &__gnat_system__exception_table__SDP, - &__gnat_system__machine_state_operations__SDP, - &__gnat_system__secondary_stack__SDP, - &__gnat_system__parameters__SDP, - &__gnat_system__soft_links__SDP, - &__gnat_system__stack_checking__SDP, - &__gnat_system__traceback__SDP, - &__gnat_ada__streams__SDP, - &__gnat_ada__tags__SDP, - &__gnat_system__string_ops__SDP, - &__gnat_interfaces__c_streams__SDP, - &__gnat_system__file_io__SDP, - &__gnat_ada__finalization__SDP, - &__gnat_system__finalization_root__SDP, - &__gnat_system__finalization_implementation__SDP, - &__gnat_system__string_ops_concat_3__SDP, - &__gnat_system__stream_attributes__SDP, - &__gnat_system__file_control_block__SDP, - &__gnat_ada__finalization__list_controller__SDP@}; - - extern void ada__exceptions___elabs (); - extern void system__exceptions___elabs (); - extern void interfaces__c_streams___elabs (); - extern void system__exception_table___elabb (); - extern void ada__io_exceptions___elabs (); - extern void system__stack_checking___elabs (); - extern void system__soft_links___elabb (); - extern void system__secondary_stack___elabb (); - extern void ada__tags___elabs (); - extern void ada__tags___elabb (); - extern void ada__streams___elabs (); - extern void system__finalization_root___elabs (); - extern void ada__exceptions___elabb (); - extern void system__finalization_implementation___elabs (); - extern void system__finalization_implementation___elabb (); - extern void ada__finalization___elabs (); - extern void ada__finalization__list_controller___elabs (); - extern void system__file_control_block___elabs (); - extern void system__file_io___elabb (); - extern void ada__text_io___elabs (); - extern void ada__text_io___elabb (); - - void (*ea[23]) () = @{ - adainit, - system__standard_library__adafinal, - ada__exceptions___elabs, - system__exceptions___elabs, - interfaces__c_streams___elabs, - system__exception_table___elabb, - ada__io_exceptions___elabs, - system__stack_checking___elabs, - system__soft_links___elabb, - system__secondary_stack___elabb, - ada__tags___elabs, - ada__tags___elabb, - ada__streams___elabs, - system__finalization_root___elabs, - ada__exceptions___elabb, - system__finalization_implementation___elabs, - system__finalization_implementation___elabb, - ada__finalization___elabs, - ada__finalization__list_controller___elabs, - system__file_control_block___elabs, - system__file_io___elabb, - ada__text_io___elabs, - ada__text_io___elabb@}; - - __gnat_SDP_Table_Build (&st, 23, ea, 23); - __gnat_set_globals ( - -1, /* Main_Priority */ - -1, /* Time_Slice_Value */ - 'b', /* WC_Encoding */ - ' ', /* Locking_Policy */ - ' ', /* Queuing_Policy */ - ' ', /* Tasking_Dispatching_Policy */ - 0, /* Finalization routine address, not used anymore */ - 0, /* Unreserve_All_Interrupts */ - 0); /* Exception_Tracebacks */ - - __gnat_inside_elab_final_code = 1; - - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabs (); - @} - if (system__exceptions_E == 0) @{ - system__exceptions___elabs (); - system__exceptions_E++; - @} - if (interfaces__c_streams_E == 0) @{ - interfaces__c_streams___elabs (); - @} - interfaces__c_streams_E = 1; - if (system__exception_table_E == 0) @{ - system__exception_table___elabb (); - system__exception_table_E++; - @} - if (ada__io_exceptions_E == 0) @{ - ada__io_exceptions___elabs (); - ada__io_exceptions_E++; - @} - if (system__stack_checking_E == 0) @{ - system__stack_checking___elabs (); - @} - if (system__soft_links_E == 0) @{ - system__soft_links___elabb (); - system__soft_links_E++; - @} - system__stack_checking_E = 1; - if (system__secondary_stack_E == 0) @{ - system__secondary_stack___elabb (); - system__secondary_stack_E++; - @} - if (ada__tags_E == 0) @{ - ada__tags___elabs (); - @} - if (ada__tags_E == 0) @{ - ada__tags___elabb (); - ada__tags_E++; - @} - if (ada__streams_E == 0) @{ - ada__streams___elabs (); - ada__streams_E++; - @} - if (system__finalization_root_E == 0) @{ - system__finalization_root___elabs (); - @} - system__finalization_root_E = 1; - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabb (); - ada__exceptions_E++; - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabs (); - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabb (); - system__finalization_implementation_E++; - @} - if (ada__finalization_E == 0) @{ - ada__finalization___elabs (); - @} - ada__finalization_E = 1; - if (ada__finalization__list_controller_E == 0) @{ - ada__finalization__list_controller___elabs (); - @} - ada__finalization__list_controller_E = 1; - if (system__file_control_block_E == 0) @{ - system__file_control_block___elabs (); - system__file_control_block_E++; - @} - if (system__file_io_E == 0) @{ - system__file_io___elabb (); - system__file_io_E++; - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabs (); - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabb (); - ada__text_io_E++; - @} - - __gnat_inside_elab_final_code = 0; - @} - int main (argc, argv, envp) - int argc; - char **argv; - char **envp; - @{ - gnat_argc = argc; - gnat_argv = argv; - gnat_envp = envp; - - __gnat_initialize (); - adainit (); - __gnat_break_start (); - - _ada_hello (); - - system__standard_library__adafinal (); - __gnat_finalize (); - exit (gnat_exit_status); - @} - unsigned helloB = 0x7880BEB3; - unsigned system__standard_libraryB = 0x0D24CBD0; - unsigned system__standard_libraryS = 0x3283DBEB; - unsigned adaS = 0x2359F9ED; - unsigned ada__text_ioB = 0x47C85FC4; - unsigned ada__text_ioS = 0x496FE45C; - unsigned ada__exceptionsB = 0x74F50187; - unsigned ada__exceptionsS = 0x6736945B; - unsigned gnatS = 0x156A40CF; - unsigned gnat__heap_sort_aB = 0x033DABE0; - unsigned gnat__heap_sort_aS = 0x6AB38FEA; - unsigned systemS = 0x0331C6FE; - unsigned system__exceptionsS = 0x20C9ECA4; - unsigned system__exception_tableB = 0x68A22947; - unsigned system__exception_tableS = 0x394BADD5; - unsigned gnat__htableB = 0x08258E1B; - unsigned gnat__htableS = 0x367D5222; - unsigned system__machine_state_operationsB = 0x4F3B7492; - unsigned system__machine_state_operationsS = 0x182F5CF4; - unsigned system__storage_elementsB = 0x2F1EB794; - unsigned system__storage_elementsS = 0x102C83C7; - unsigned system__secondary_stackB = 0x1574B6E9; - unsigned system__secondary_stackS = 0x708E260A; - unsigned system__parametersB = 0x56D770CD; - unsigned system__parametersS = 0x237E39BE; - unsigned system__soft_linksB = 0x08AB6B2C; - unsigned system__soft_linksS = 0x1E2491F3; - unsigned system__stack_checkingB = 0x476457A0; - unsigned system__stack_checkingS = 0x5299FCED; - unsigned system__tracebackB = 0x2971EBDE; - unsigned system__tracebackS = 0x2E9C3122; - unsigned ada__streamsS = 0x7C25DE96; - unsigned ada__tagsB = 0x39ADFFA2; - unsigned ada__tagsS = 0x769A0464; - unsigned system__string_opsB = 0x5EB646AB; - unsigned system__string_opsS = 0x63CED018; - unsigned interfacesS = 0x0357E00A; - unsigned interfaces__c_streamsB = 0x3784FB72; - unsigned interfaces__c_streamsS = 0x2E723019; - unsigned system__file_ioB = 0x623358EA; - unsigned system__file_ioS = 0x31F873E6; - unsigned ada__finalizationB = 0x6843F68A; - unsigned ada__finalizationS = 0x63305874; - unsigned system__finalization_rootB = 0x31E56CE1; - unsigned system__finalization_rootS = 0x23169EF3; - unsigned system__finalization_implementationB = 0x6CCBA70E; - unsigned system__finalization_implementationS = 0x604AA587; - unsigned system__string_ops_concat_3B = 0x572E3F58; - unsigned system__string_ops_concat_3S = 0x01F57876; - unsigned system__stream_attributesB = 0x1D4F93E8; - unsigned system__stream_attributesS = 0x30B2EC3D; - unsigned ada__io_exceptionsS = 0x34054F96; - unsigned system__unsigned_typesS = 0x7B9E7FE3; - unsigned system__file_control_blockS = 0x2FF876A8; - unsigned ada__finalization__list_controllerB = 0x5760634A; - unsigned ada__finalization__list_controllerS = 0x5D851835; - - /* BEGIN ELABORATION ORDER - ada (spec) - gnat (spec) - gnat.heap_sort_a (spec) - gnat.htable (spec) - gnat.htable (body) - interfaces (spec) - system (spec) - system.parameters (spec) - system.standard_library (spec) - ada.exceptions (spec) - system.exceptions (spec) - system.parameters (body) - gnat.heap_sort_a (body) - interfaces.c_streams (spec) - interfaces.c_streams (body) - system.exception_table (spec) - system.exception_table (body) - ada.io_exceptions (spec) - system.storage_elements (spec) - system.storage_elements (body) - system.machine_state_operations (spec) - system.machine_state_operations (body) - system.secondary_stack (spec) - system.stack_checking (spec) - system.soft_links (spec) - system.soft_links (body) - system.stack_checking (body) - system.secondary_stack (body) - system.standard_library (body) - system.string_ops (spec) - system.string_ops (body) - ada.tags (spec) - ada.tags (body) - ada.streams (spec) - system.finalization_root (spec) - system.finalization_root (body) - system.string_ops_concat_3 (spec) - system.string_ops_concat_3 (body) - system.traceback (spec) - system.traceback (body) - ada.exceptions (body) - system.unsigned_types (spec) - system.stream_attributes (spec) - system.stream_attributes (body) - system.finalization_implementation (spec) - system.finalization_implementation (body) - ada.finalization (spec) - ada.finalization (body) - ada.finalization.list_controller (spec) - ada.finalization.list_controller (body) - system.file_control_block (spec) - system.file_io (spec) - system.file_io (body) - ada.text_io (spec) - ada.text_io (body) - hello (body) - END ELABORATION ORDER */ - - /* BEGIN Object file/option list - ./hello.o - -L./ - -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/ - /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a - -lexc - END Object file/option list */ - - @end smallexample - - @noindent - Here again, the C code is exactly what is generated by the binder. The - functions of the various parts of this code correspond in an obvious - manner with the commented Ada code shown in the example in the previous - section. - - @node Consistency-Checking Modes - @section Consistency-Checking Modes - - @noindent - As described in the previous section, by default @code{gnatbind} checks - that object files are consistent with one another and are consistent - with any source files it can locate. The following switches control binder - access to sources. - - @table @code - @item ^-s^/READ_SOURCES=ALL^ - @cindex @code{^-s^/READ_SOURCES=ALL^} (@code{gnatbind}) - Require source files to be present. In this mode, the binder must be - able to locate all source files that are referenced, in order to check - their consistency. In normal mode, if a source file cannot be located it - is simply ignored. If you specify this switch, a missing source - file is an error. - - @item ^-x^/READ_SOURCES=NONE^ - @cindex @code{^-x^/READ_SOURCES=NONE^} (@code{gnatbind}) - Exclude source files. In this mode, the binder only checks that ALI - files are consistent with one another. Source files are not accessed. - The binder runs faster in this mode, and there is still a guarantee that - the resulting program is self-consistent. - If a source file has been edited since it was last compiled, and you - specify this switch, the binder will not detect that the object - file is out of date with respect to the source file. Note that this is the - mode that is automatically used by @code{gnatmake} because in this - case the checking against sources has already been performed by - @code{gnatmake} in the course of compilation (i.e. before binding). - - @ifset vms - @item /READ_SOURCES=AVAILABLE - This is the default mode in which source files are checked if they are - available, and ignored if they are not available. - @end ifset - @end table - - @node Binder Error Message Control - @section Binder Error Message Control - - @noindent - The following switches provide control over the generation of error - messages from the binder: - - @table @code - @item ^-v^/REPORT_ERRORS=VERBOSE^ - @cindex @code{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind}) - Verbose mode. In the normal mode, brief error messages are generated to - @file{stderr}. If this switch is present, a header is written - to @file{stdout} and any error messages are directed to @file{stdout}. - All that is written to @file{stderr} is a brief summary message. - - @item ^-b^/REPORT_ERRORS=BRIEF^ - @cindex @code{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind}) - Generate brief error messages to @file{stderr} even if verbose mode is - specified. This is relevant only when used with the - @code{^-v^/REPORT_ERRORS=VERBOSE^} switch. - - @ifclear vms - @item -m@var{n} - @cindex @code{-m} (@code{gnatbind}) - Limits the number of error messages to @var{n}, a decimal integer in the - range 1-999. The binder terminates immediately if this limit is reached. - - @item -M@var{xxx} - @cindex @code{-M} (@code{gnatbind}) - Renames the generated main program from @code{main} to @code{xxx}. - This is useful in the case of some cross-building environments, where - the actual main program is separate from the one generated - by @code{gnatbind}. - @end ifclear - - @item ^-ws^/WARNINGS=SUPPRESS^ - @cindex @code{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind}) - @cindex Warnings - Suppress all warning messages. - - @item ^-we^/WARNINGS=ERROR^ - @cindex @code{^-we^/WARNINGS=ERROR^} (@code{gnatbind}) - Treat any warning messages as fatal errors. - - @ifset vms - @item /WARNINGS=NORMAL - Standard mode with warnings generated, but warnings do not get treated - as errors. - @end ifset - - @item ^-t^/NOTIME_STAMP_CHECK^ - @cindex @code{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind}) - @cindex Time stamp checks, in binder - @cindex Binder consistency checks - @cindex Consistency checks, in binder - The binder performs a number of consistency checks including: - - @itemize @bullet - @item - Check that time stamps of a given source unit are consistent - @item - Check that checksums of a given source unit are consistent - @item - Check that consistent versions of @code{GNAT} were used for compilation - @item - Check consistency of configuration pragmas as required - @end itemize - - @noindent - Normally failure of such checks, in accordance with the consistency - requirements of the Ada Reference Manual, causes error messages to be - generated which abort the binder and prevent the output of a binder - file and subsequent link to obtain an executable. - - The @code{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages - into warnings, so that - binding and linking can continue to completion even in the presence of such - errors. The result may be a failed link (due to missing symbols), or a - non-functional executable which has undefined semantics. - @emph{This means that - @code{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations, - with extreme care.} - @end table - - @node Elaboration Control - @section Elaboration Control - - @noindent - The following switches provide additional control over the elaboration - order. For full details see @xref{Elaboration Order Handling in GNAT}. - - @table @code - @item ^-p^/PESSIMISTIC_ELABORATION^ - @cindex @code{^-h^/PESSIMISTIC_ELABORATION^} (@code{gnatbind}) - Normally the binder attempts to choose an elaboration order that is - likely to minimize the likelihood of an elaboration order error resulting - in raising a @code{Program_Error} exception. This switch reverses the - action of the binder, and requests that it deliberately choose an order - that is likely to maximize the likelihood of an elaboration error. - This is useful in ensuring portability and avoiding dependence on - accidental fortuitous elaboration ordering. - - Normally it only makes sense to use the @code{-p} switch if dynamic - elaboration checking is used (@option{-gnatE} switch used for compilation). - This is because in the default static elaboration mode, all necessary - @code{Elaborate_All} pragmas are implicitly inserted. These implicit - pragmas are still respected by the binder in @code{-p} mode, so a - safe elaboration order is assured. - @end table - - @node Output Control - @section Output Control - - @noindent - The following switches allow additional control over the output - generated by the binder. - - @table @code - - @item ^-A^/BIND_FILE=ADA^ - @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatbind}) - Generate binder program in Ada (default). The binder program is named - @file{b~@var{mainprog}.adb} by default. This can be changed with - @code{-o} @code{gnatbind} option. - - @item ^-c^/NOOUTPUT^ - @cindex @code{^-c^/NOOUTPUT^} (@code{gnatbind}) - Check only. Do not generate the binder output file. In this mode the - binder performs all error checks but does not generate an output file. - - @item ^-C^/BIND_FILE=C^ - @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatbind}) - Generate binder program in C. The binder program is named - @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind} - option. - - @item ^-e^/ELABORATION_DEPENDENCIES^ - @cindex @code{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind}) - Output complete list of elaboration-order dependencies, showing the - reason for each dependency. This output can be rather extensive but may - be useful in diagnosing problems with elaboration order. The output is - written to @file{stdout}. - - @item ^-h^/HELP^ - @cindex @code{^-h^/HELP^} (@code{gnatbind}) - Output usage information. The output is written to @file{stdout}. - - @item ^-K^/LINKER_OPTION_LIST^ - @cindex @code{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind}) - Output linker options to @file{stdout}. Includes library search paths, - contents of pragmas Ident and Linker_Options, and libraries added - by @code{gnatbind}. - - @item ^-l^/ORDER_OF_ELABORATION^ - @cindex @code{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind}) - Output chosen elaboration order. The output is written to @file{stdout}. - - @item ^-O^/OBJECT_LIST^ - @cindex @code{^-O^/OBJECT_LIST^} (@code{gnatbind}) - Output full names of all the object files that must be linked to provide - the Ada component of the program. The output is written to @file{stdout}. - This list includes the files explicitly supplied and referenced by the user - as well as implicitly referenced run-time unit files. The latter are - omitted if the corresponding units reside in shared libraries. The - directory names for the run-time units depend on the system configuration. - - @item ^-o ^/OUTPUT=^@var{file} - @cindex @code{^-o^/OUTPUT^} (@code{gnatbind}) - Set name of output file to @var{file} instead of the normal - @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada - binder generated body filename. In C mode you would normally give - @var{file} an extension of @file{.c} because it will be a C source program. - Note that if this option is used, then linking must be done manually. - It is not possible to use gnatlink in this case, since it cannot locate - the binder file. - - @item ^-r^/RESTRICTION_LIST^ - @cindex @code{^-r^/RESTRICTION_LIST^} (@code{gnatbind}) - Generate list of @code{pragma Rerstrictions} that could be applied to - the current unit. This is useful for code audit purposes, and also may - be used to improve code generation in some cases. - - @end table - - @node Binding with Non-Ada Main Programs - @section Binding with Non-Ada Main Programs - - @noindent - In our description so far we have assumed that the main - program is in Ada, and that the task of the binder is to generate a - corresponding function @code{main} that invokes this Ada main - program. GNAT also supports the building of executable programs where - the main program is not in Ada, but some of the called routines are - written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). - The following switch is used in this situation: - - @table @code - @item ^-n^/NOMAIN^ - @cindex @code{^-n^/NOMAIN^} (@code{gnatbind}) - No main program. The main program is not in Ada. - @end table - - @noindent - In this case, most of the functions of the binder are still required, - but instead of generating a main program, the binder generates a file - containing the following callable routines: - - @table @code - @item adainit - @findex adainit - You must call this routine to initialize the Ada part of the program by - calling the necessary elaboration routines. A call to @code{adainit} is - required before the first call to an Ada subprogram. - - Note that it is assumed that the basic execution environment must be setup - to be appropriate for Ada execution at the point where the first Ada - subprogram is called. In particular, if the Ada code will do any - floating-point operations, then the FPU must be setup in an appropriate - manner. For the case of the x86, for example, full precision mode is - required. The procedure GNAT.Float_Control.Reset may be used to ensure - that the FPU is in the right state. - - @item adafinal - @findex adafinal - You must call this routine to perform any library-level finalization - required by the Ada subprograms. A call to @code{adafinal} is required - after the last call to an Ada subprogram, and before the program - terminates. - @end table - - @noindent - If the @code{^-n^/NOMAIN^} switch - @cindex Binder, multiple input files - is given, more than one ALI file may appear on - the command line for @code{gnatbind}. The normal @dfn{closure} - calculation is performed for each of the specified units. Calculating - the closure means finding out the set of units involved by tracing - @code{with} references. The reason it is necessary to be able to - specify more than one ALI file is that a given program may invoke two or - more quite separate groups of Ada units. - - The binder takes the name of its output file from the last specified ALI - file, unless overridden by the use of the @code{^-o file^/OUTPUT=file^}. - The output is an Ada unit in source form that can - be compiled with GNAT unless the -C switch is used in which case the - output is a C source file, which must be compiled using the C compiler. - This compilation occurs automatically as part of the @code{gnatlink} - processing. - - Currently the GNAT run time requires a FPU using 80 bits mode - precision. Under targets where this is not the default it is required to - call GNAT.Float_Control.Reset before using floating point numbers (this - include float computation, float input and output) in the Ada code. A - side effect is that this could be the wrong mode for the foreign code - where floating point computation could be broken after this call. - - @node Binding Programs with No Main Subprogram - @section Binding Programs with No Main Subprogram - - @noindent - It is possible to have an Ada program which does not have a main - subprogram. This program will call the elaboration routines of all the - packages, then the finalization routines. - - The following switch is used to bind programs organized in this manner: - - @table @code - @item ^-z^/ZERO_MAIN^ - @cindex @code{^-z^/ZERO_MAIN^} (@code{gnatbind}) - Normally the binder checks that the unit name given on the command line - corresponds to a suitable main subprogram. When this switch is used, - a list of ALI files can be given, and the execution of the program - consists of elaboration of these units in an appropriate order. - @end table - - @node Summary of Binder Switches - @section Summary of Binder Switches - - @noindent - The following are the switches available with @code{gnatbind}: - - @table @code - @item ^-aO^/OBJECT_SEARCH^ - Specify directory to be searched for ALI files. - - @item ^-aI^/SOURCE_SEARCH^ - Specify directory to be searched for source file. - - @item ^-A^/BIND_FILE=ADA^ - Generate binder program in Ada (default) - - @item ^-b^/REPORT_ERRORS=BRIEF^ - Generate brief messages to @file{stderr} even if verbose mode set. - - @item ^-c^/NOOUTPUT^ - Check only, no generation of binder output file. - - @item ^-C^/BIND_FILE=C^ - Generate binder program in C - - @item ^-e^/ELABORATION_DEPENDENCIES^ - Output complete list of elaboration-order dependencies. - - @item -E - Store tracebacks in exception occurrences when the target supports it. - This is the default with the zero cost exception mechanism. - This option is currently supported on the following targets: - all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. - See also the packages @code{GNAT.Traceback} and - @code{GNAT.Traceback.Symbolic} for more information. - Note that on x86 ports, you must not use @code{-fomit-frame-pointer} - @code{gcc} option. - - @item -h - Output usage (help) information - - @item ^-I^/SEARCH^ - Specify directory to be searched for source and ALI files. - - @item ^-I-^/NOCURRENT_DIRECTORY^ - Do not look for sources in the current directory where @code{gnatbind} was - invoked, and do not look for ALI files in the directory containing the - ALI file named in the @code{gnatbind} command line. - - @item ^-l^/ORDER_OF_ELABORATION^ - Output chosen elaboration order. - - @item -Lxxx - Binds the units for library building. In this case the adainit and - adafinal procedures (See @pxref{Binding with Non-Ada Main Programs}) - are renamed to xxxinit and xxxfinal. Implies -n. - @ifclear vms - See @pxref{GNAT and Libraries} for more details. - @end ifclear - - @item -Mxyz - Rename generated main program from main to xyz - - @item ^-m^/ERROR_LIMIT=^@var{n} - Limit number of detected errors to @var{n} (1-999). - @ifset wnt - Furthermore, under Windows, the sources pointed to by the libraries path - set in the registry are not searched for. - @end ifset - - @item ^-n^/NOMAIN^ - No main program. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatbind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item ^-o ^/OUTPUT=^@var{file} - Name the output file @var{file} (default is @file{b~@var{xxx}.adb}). - Note that if this option is used, then linking must be done manually, - gnatlink cannot be used. - - @item ^-O^/OBJECT_LIST^ - Output object list. - - @item -p - Pessimistic (worst-case) elaboration order - - @item ^-s^/READ_SOURCES=ALL^ - Require all source files to be present. - - @ifclear vms - @item -static - Link against a static GNAT run time. - - @item -shared - Link against a shared GNAT run time when available. - @end ifclear - - @item ^-t^/NOTIME_STAMP_CHECK^ - Tolerate time stamp and other consistency errors - - @item -T@var{n} - Set the time slice value to n microseconds. A value of zero means no time - slicing and also indicates to the tasking run time to match as close as - possible to the annex D requirements of the RM. - - @item ^-v^/REPORT_ERRORS=VERBOSE^ - Verbose mode. Write error messages, header, summary output to - @file{stdout}. - - @ifclear vms - @item -w@var{x} - Warning mode (@var{x}=s/e for suppress/treat as error) - @end ifclear - - @ifset vms - @item /WARNINGS=NORMAL - Normal warnings mode. Warnings are issued but ignored - - @item /WARNINGS=SUPPRESS - All warning messages are suppressed - - @item /WARNINGS=ERROR - Warning messages are treated as fatal errors - @end ifset - - @item ^-x^/READ_SOURCES=NONE^ - Exclude source files (check object consistency only). - - @ifset vms - @item /READ_SOURCES=AVAILABLE - Default mode, in which sources are checked for consistency only if - they are available. - @end ifset - - @item ^-z^/ZERO_MAIN^ - No main subprogram. - - @end table - - @ifclear vms - You may obtain this listing by running the program @code{gnatbind} with - no arguments. - @end ifclear - - @node Command-Line Access - @section Command-Line Access - - @noindent - The package @code{Ada.Command_Line} provides access to the command-line - arguments and program name. In order for this interface to operate - correctly, the two variables - - @smallexample - @group - @cartouche - int gnat_argc; - char **gnat_argv; - @end cartouche - @end group - @end smallexample - - @noindent - @findex gnat_argv - @findex gnat_argc - are declared in one of the GNAT library routines. These variables must - be set from the actual @code{argc} and @code{argv} values passed to the - main program. With no @code{^n^/NOMAIN^} present, @code{gnatbind} - generates the C main program to automatically set these variables. - If the @code{^n^/NOMAIN^} switch is used, there is no automatic way to - set these variables. If they are not set, the procedures in - @code{Ada.Command_Line} will not be available, and any attempt to use - them will raise @code{Constraint_Error}. If command line access is - required, your main program must set @code{gnat_argc} and - @code{gnat_argv} from the @code{argc} and @code{argv} values passed to - it. - - @node Search Paths for gnatbind - @section Search Paths for @code{gnatbind} - - @noindent - The binder takes the name of an ALI file as its argument and needs to - locate source files as well as other ALI files to verify object consistency. - - For source files, it follows exactly the same search rules as @code{gcc} - (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the - directories searched are: - - @enumerate - @item - The directory containing the ALI file named in the command line, unless - the switch @code{^-I-^/NOCURRENT_DIRECTORY^} is specified. - - @item - All directories specified by @code{^-I^/SEARCH^} - switches on the @code{gnatbind} - command line, in the order given. - - @item - @findex ADA_OBJECTS_PATH - Each of the directories listed in the value of the - @code{ADA_OBJECTS_PATH} ^environment variable^logical name^. - @ifclear vms - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version - of GNAT). - @end ifclear - @ifset vms - Normally, define this value as a logical name containing a comma separated - list of directory names. - - This variable can also be defined by means of an environment string - (an argument to the DEC C exec* set of functions). - - Logical Name: - @smallexample - DEFINE ANOTHER_PATH FOO:[BAG] - DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] - @end smallexample - - By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] - first, followed by the standard Ada 95 - libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB]. - If this is not redefined, the user will obtain the DEC Ada83 IO packages - (Text_IO, Sequential_IO, etc) - instead of the Ada95 packages. Thus, in order to get the Ada 95 - packages by default, ADA_OBJECTS_PATH must be redefined. - @end ifset - - @item - The content of the "ada_object_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is - specified. - @ifclear vms - @ref{Installing an Ada Library} - @end ifclear - @end enumerate - - @noindent - In the binder the switch @code{^-I^/SEARCH^} - is used to specify both source and - library file paths. Use @code{^-aI^/SOURCE_SEARCH^} - instead if you want to specify - source paths only, and @code{^-aO^/LIBRARY_SEARCH^} - if you want to specify library paths - only. This means that for the binder - @code{^-I^/SEARCH=^}@var{dir} is equivalent to - @code{^-aI^/SOURCE_SEARCH=^}@var{dir} - @code{^-aO^/OBJECT_SEARCH=^}@var{dir}. - The binder generates the bind file (a C language source file) in the - current working directory. - - @findex Ada - @findex System - @findex Interfaces - @findex GNAT - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT Run-Time Library, together with the package - GNAT and its children, which contain a set of useful additional - library functions provided by GNAT. The sources for these units are - needed by the compiler and are kept together in one directory. The ALI - files and object files generated by compiling the RTL are needed by the - binder and the linker and are kept together in one directory, typically - different from the directory containing the sources. In a normal - installation, you need not specify these directory names when compiling - or binding. Either the environment variables or the built-in defaults - cause these files to be found. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Examples of gnatbind Usage - @section Examples of @code{gnatbind} Usage - - @noindent - This section contains a number of examples of using the GNAT binding - utility @code{gnatbind}. - - @table @code - @item gnatbind hello - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{b~hello.adb}. This is the normal, default use of the binder. - - @ifclear vms - @item gnatbind hello -o mainprog.adb - @end ifclear - @ifset vms - @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB - @end ifset - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{mainprog.adb} with the associated spec in - @file{mainprog.ads}. Note that you must specify the body here not the - spec, in the case where the output is in Ada. Note that if this option - is used, then linking must be done manually, since gnatlink will not - be able to find the generated file. - - @ifclear vms - @item gnatbind main -C -o mainprog.c -x - @end ifclear - @ifset vms - @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE - @end ifset - The main program @code{Main} (source program in - @file{main.adb}) is bound, excluding source files from the - consistency checking, generating - the file @file{mainprog.c}. - - @ifclear vms - @item gnatbind -x main_program -C -o mainprog.c - This command is exactly the same as the previous example. Switches may - appear anywhere in the command line, and single letter switches may be - combined into a single switch. - @end ifclear - - @ifclear vms - @item gnatbind -n math dbase -C -o ada-control.c - @end ifclear - @ifset vms - @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c - @end ifset - The main program is in a language other than Ada, but calls to - subprograms in packages @code{Math} and @code{Dbase} appear. This call - to @code{gnatbind} generates the file @file{ada-control.c} containing - the @code{adainit} and @code{adafinal} routines to be called before and - after accessing the Ada units. - @end table - - @node Linking Using gnatlink - @chapter Linking Using @code{gnatlink} - @findex gnatlink - - @noindent - This chapter discusses @code{gnatlink}, a utility program used to link - Ada programs and build an executable file. This is a simple program - that invokes the Unix linker (via the @code{gcc} - command) with a correct list of object files and library references. - @code{gnatlink} automatically determines the list of files and - references for the Ada part of a program. It uses the binder file - generated by the binder to determine this list. - - @menu - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - @end menu - - @node Running gnatlink - @section Running @code{gnatlink} - - @noindent - The form of the @code{gnatlink} command is - - @smallexample - $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}] - [@var{linker options}] - @end smallexample - - @noindent - @file{@var{mainprog}.ali} references the ALI file of the main program. - The @file{.ali} extension of this file can be omitted. From this - reference, @code{gnatlink} locates the corresponding binder file - @file{b~@var{mainprog}.adb} and, using the information in this file along - with the list of non-Ada objects and linker options, constructs a Unix - linker command file to create the executable. - - The arguments following @file{@var{mainprog}.ali} are passed to the - linker uninterpreted. They typically include the names of object files - for units written in other languages than Ada and any library references - required to resolve references in any of these foreign language units, - or in @code{pragma Import} statements in any Ada units. - - @var{linker options} is an optional list of linker specific - switches. The default linker called by gnatlink is @var{gcc} which in - turn calls the appropriate system linker usually called - @var{ld}. Standard options for the linker such as @code{-lmy_lib} or - @code{-Ldir} can be added as is. For options that are not recognized by - @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or - @code{-Wl,} shall be used. Refer to the GCC documentation for - details. Here is an example showing how to generate a linker map - assuming that the underlying linker is GNU ld: - - @smallexample - $ gnatlink my_prog -Wl,-Map,MAPFILE - @end smallexample - - Using @var{linker options} it is possible to set the program stack and - heap size. See @pxref{Setting Stack Size from gnatlink} and - @pxref{Setting Heap Size from gnatlink}. - - @code{gnatlink} determines the list of objects required by the Ada - program and prepends them to the list of objects passed to the linker. - @code{gnatlink} also gathers any arguments set by the use of - @code{pragma Linker_Options} and adds them to the list of arguments - presented to the linker. - - @ifset vms - @code{gnatlink} accepts the following types of extra files on the command - line: objects (.OBJ), libraries (.OLB), shareable images (.EXE), and - options files (.OPT). These are recognized and handled according to their - extension. - @end ifset - - @node Switches for gnatlink - @section Switches for @code{gnatlink} - - @noindent - The following switches are available with the @code{gnatlink} utility: - - @table @code - - @item ^-A^/BIND_FILE=ADA^ - @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatlink}) - The binder has generated code in Ada. This is the default. - - @item ^-C^/BIND_FILE=C^ - @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatlink}) - If instead of generating a file in Ada, the binder has generated one in - C, then the linker needs to know about it. Use this switch to signal - to @code{gnatlink} that the binder has generated C code rather than - Ada code. - - @item -f - @cindex Command line length - @cindex @code{-f} (@code{gnatlink}) - On some targets, the command line length is limited, and @code{gnatlink} - will generate a separate file for the linker if the list of object files - is too long. The @code{-f} flag forces this file to be generated even if - the limit is not exceeded. This is useful in some cases to deal with - special situations where the command line length is exceeded. - - @item ^-g^/DEBUG^ - @cindex Debugging information, including - @cindex @code{^-g^/DEBUG^} (@code{gnatlink}) - The option to include debugging information causes the Ada bind file (in - other words, @file{b~@var{mainprog}.adb}) to be compiled with - @code{^-g^/DEBUG^}. - In addition, the binder does not delete the @file{b~@var{mainprog}.adb}, - @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files. - Without @code{^-g^/DEBUG^}, the binder removes these files by - default. The same procedure apply if a C bind file was generated using - @code{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames are - @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}. - - @ifclear vms - @item -n - @cindex @code{-n} (@code{gnatlink}) - Do not compile the file generated by the binder. This may be used when - a link is rerun with different options, but there is no need to recompile - the binder file. - @end ifclear - - @item ^-v^/VERBOSE^ - @cindex @code{^-v^/VERBOSE^} (@code{gnatlink}) - Causes additional information to be output, including a full list of the - included object files. This switch option is most useful when you want - to see what set of object files are being used in the link step. - - @ifclear vms - @item -v -v - @cindex @code{-v -v} (@code{gnatlink}) - Very verbose mode. Requests that the compiler operate in verbose mode when - it compiles the binder file, and that the system linker run in verbose mode. - @end ifclear - - @item ^-o ^/EXECUTABLE=^@var{exec-name} - @cindex @code{^-o^/EXECUTABLE^} (@code{gnatlink}) - @var{exec-name} specifies an alternate name for the generated - executable program. If this switch is omitted, the executable has the same - name as the main unit. For example, @code{gnatlink try.ali} creates - an executable called @file{^try^TRY.EXE^}. - - @ifclear vms - @item -b @var{target} - @cindex @code{-b} (@code{gnatlink}) - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gnatlink}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatlink}) - Program used for compiling the binder file. The default is - `@code{gcc}'. You need to use quotes around @var{compiler_name} if - @code{compiler_name} contains spaces or other separator characters. As - an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use - @code{foo -x -y} as your compiler. Note that switch @code{-c} is always - inserted after your command name. Thus in the above example the compiler - command that will be used by @code{gnatlink} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --LINK=@var{name} - @cindex @code{--LINK=} (@code{gnatlink}) - @var{name} is the name of the linker to be invoked. This is especially - useful in mixed language programs since languages such as c++ require - their own linker to be used. When this switch is omitted, the default - name for the linker is (@file{gcc}). When this switch is used, the - specified linker is called instead of (@file{gcc}) with exactly the same - parameters that would have been passed to (@file{gcc}) so if the desired - linker requires different parameters it is necessary to use a wrapper - script that massages the parameters before invoking the real linker. It - may be useful to control the exact invocation by using the verbose - switch. - - @end ifclear - - @ifset vms - @item /DEBUG=TRACEBACK - @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink}) - This qualifier causes sufficient information to be included in the - executable file to allow a traceback, but does not include the full - symbol information needed by the debugger. - - @item /IDENTIFICATION="" - "" specifies the string to be stored in the image file identification - field in the image header. It overrides any pragma Ident specified string. - - @item /NOINHIBIT-EXEC - Generate the executable file even if there are linker warnings. - - @item /NOSTART_FILES - Don't link in the object file containing the "main" transfer address. - Used when linking with a foreign language main program compiled with a - Digital compiler. - - @item /STATIC - Prefer linking with object libraries over shareable images, even without - /DEBUG. - @end ifset - - @end table - - @node Setting Stack Size from gnatlink - @section Setting Stack Size from @code{gnatlink} - - @noindent - It is possible to specify the program stack size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --stack=0x10000,0x1000 - @end smallexample - - This set the stack reserve size to 0x10000 bytes and the stack commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--stack=0x1000000 - @end smallexample - - This set the stack reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the stack commit size - because the coma is a separator for this option. - - @end itemize - - @node Setting Heap Size from gnatlink - @section Setting Heap Size from @code{gnatlink} - - @noindent - It is possible to specify the program heap size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --heap=0x10000,0x1000 - @end smallexample - - This set the heap reserve size to 0x10000 bytes and the heap commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--heap=0x1000000 - @end smallexample - - This set the heap reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the heap commit size - because the coma is a separator for this option. - - @end itemize - - @node The GNAT Make Program gnatmake - @chapter The GNAT Make Program @code{gnatmake} - @findex gnatmake - - @menu - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - @end menu - @noindent - A typical development cycle when working on an Ada program consists of - the following steps: - - @enumerate - @item - Edit some sources to fix bugs. - - @item - Add enhancements. - - @item - Compile all sources affected. - - @item - Rebind and relink. - - @item - Test. - @end enumerate - - @noindent - The third step can be tricky, because not only do the modified files - @cindex Dependency rules - have to be compiled, but any files depending on these files must also be - recompiled. The dependency rules in Ada can be quite complex, especially - in the presence of overloading, @code{use} clauses, generics and inlined - subprograms. - - @code{gnatmake} automatically takes care of the third and fourth steps - of this process. It determines which sources need to be compiled, - compiles them, and binds and links the resulting object files. - - Unlike some other Ada make programs, the dependencies are always - accurately recomputed from the new sources. The source based approach of - the GNAT compilation model makes this possible. This means that if - changes to the source program cause corresponding changes in - dependencies, they will always be tracked exactly correctly by - @code{gnatmake}. - - @node Running gnatmake - @section Running @code{gnatmake} - - @noindent - The usual form of the @code{gnatmake} command is - - @smallexample - $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}] - @end smallexample - - @noindent - The only required argument is one @var{file_name}, which specifies - a compilation unit that is a main program. Several @var{file_names} can be - specified: this will result in several executables being built. - If @code{switches} are present, they can be placed before the first - @var{file_name}, between @var{file_names} or after the last @var{file_name}. - If @var{mode_switches} are present, they must always be placed after - the last @var{file_name} and all @code{switches}. - - If you are using standard file extensions (.adb and .ads), then the - extension may be omitted from the @var{file_name} arguments. However, if - you are using non-standard extensions, then it is required that the - extension be given. A relative or absolute directory path can be - specified in a @var{file_name}, in which case, the input source file will - be searched for in the specified directory only. Otherwise, the input - source file will first be searched in the directory where - @code{gnatmake} was invoked and if it is not found, it will be search on - the source path of the compiler as described in - @ref{Search Paths and the Run-Time Library (RTL)}. - - When several @var{file_names} are specified, if an executable needs to be - rebuilt and relinked, all subsequent executables will be rebuilt and - relinked, even if this would not be absolutely necessary. - - All @code{gnatmake} output (except when you specify - @code{^-M^/DEPENDENCIES_LIST^}) is to - @file{stderr}. The output produced by the - @code{^-M^/DEPENDENCIES_LIST^} switch is send to - @file{stdout}. - - @node Switches for gnatmake - @section Switches for @code{gnatmake} - - @noindent - You may specify any of the following switches to @code{gnatmake}: - - @table @code - @ifclear vms - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatmake}) - Program used for compiling. The default is `@code{gcc}'. You need to use - quotes around @var{compiler_name} if @code{compiler_name} contains - spaces or other separator characters. As an example @code{--GCC="foo -x - -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your - compiler. Note that switch @code{-c} is always inserted after your - command name. Thus in the above example the compiler command that will - be used by @code{gnatmake} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --GNATBIND=@var{binder_name} - @cindex @code{--GNATBIND=binder_name} (@code{gnatmake}) - Program used for binding. The default is `@code{gnatbind}'. You need to - use quotes around @var{binder_name} if @var{binder_name} contains spaces - or other separator characters. As an example @code{--GNATBIND="bar -x - -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your - binder. Binder switches that are normally appended by @code{gnatmake} to - `@code{gnatbind}' are now appended to the end of @code{bar -x -y}. - - @item --GNATLINK=@var{linker_name} - @cindex @code{--GNATLINK=linker_name} (@code{gnatmake}) - Program used for linking. The default is `@code{gnatlink}'. You need to - use quotes around @var{linker_name} if @var{linker_name} contains spaces - or other separator characters. As an example @code{--GNATLINK="lan -x - -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your - linker. Linker switches that are normally appended by @code{gnatmake} to - `@code{gnatlink}' are now appended to the end of @code{lan -x -y}. - - @end ifclear - - @item ^-a^/ALL_FILES^ - @cindex @code{^-a^/ALL_FILES^} (@code{gnatmake}) - Consider all files in the make process, even the GNAT internal system - files (for example, the predefined Ada library files), as well as any - locked files. Locked files are files whose ALI file is write-protected. - By default, - @code{gnatmake} does not check these files, - because the assumption is that the GNAT internal files are properly up - to date, and also that any write protected ALI files have been properly - installed. Note that if there is an installation problem, such that one - of these files is not up to date, it will be properly caught by the - binder. - You may have to specify this switch if you are working on GNAT - itself. @code{^-a^/ALL_FILES^} is also useful in conjunction with - @code{^-f^/FORCE_COMPILE^} - if you need to recompile an entire application, - including run-time files, using special configuration pragma settings, - such as a non-standard @code{Float_Representation} pragma. - By default - @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT - internal files with - @ifclear vms - @code{gcc -c -gnatpg} rather than @code{gcc -c}. - @end ifclear - @ifset vms - the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch. - @end ifset - - @item ^-b^/ACTIONS=BIND^ - @cindex @code{^-b^/ACTIONS=BIND^} (@code{gnatmake}) - Bind only. Can be combined with @code{^-c^/ACTIONS=COMPILE^} to do compilation - and binding, but no link. Can be combined with @code{^-l^/ACTIONS=LINK^} - to do binding and linking. When not combined with @code{^-c^/ACTIONS=COMPILE^} - all the units in the closure of the main program must have been previously - compiled and must be up to date. The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item ^-c^/ACTIONS=COMPILE^ - @cindex @code{^-c^/ACTIONS=COMPILE^} (@code{gnatmake}) - Compile only. Do not perform binding, except when @code{^-b^/ACTIONS=BIND^} - is also specified. Do not perform linking, except if both - @code{^-b^/ACTIONS=BIND^} and - @code{^-l^/ACTIONS=LINK^} are also specified. - If the root unit specified by @var{file_name} is not a main unit, this is the - default. Otherwise @code{gnatmake} will attempt binding and linking - unless all objects are up to date and the executable is more recent than - the objects. - - @item ^-C^/MAPPING^ - @cindex @code{^-C^/MAPPING^} (@code{gnatmake}) - Use a mapping file. A mapping file is a way to communicate to the compiler - two mappings: from unit names to file names (without any directory information) - and from file names to path names (with full directory information). - These mappings are used by the compiler to short-circuit the path search. - When @code{gnatmake} is invoked with this switch, it will create a mapping - file, initially populated by the project manager, if @code{-P} is used, - otherwise initially empty. Each invocation of the compiler will add the newly - accessed sources to the mapping file. This will improve the source search - during the next invocation of the compiler. - - @item ^-f^/FORCE_COMPILE^ - @cindex @code{^-f^/FORCE_COMPILE^} (@code{gnatmake}) - Force recompilations. Recompile all sources, even though some object - files may be up to date, but don't recompile predefined or GNAT internal - files or locked files (files with a write-protected ALI file), - unless the @code{^-a^/ALL_FILES^} switch is also specified. - - @item - @item ^-i^/IN_PLACE^ - @cindex @code{^-i^/IN_PLACE^} (@code{gnatmake}) - In normal mode, @code{gnatmake} compiles all object files and ALI files - into the current directory. If the @code{^-i^/IN_PLACE^} switch is used, - then instead object files and ALI files that already exist are overwritten - in place. This means that once a large project is organized into separate - directories in the desired manner, then @code{gnatmake} will automatically - maintain and update this organization. If no ALI files are found on the - Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), - the new object and ALI files are created in the - directory containing the source being compiled. If another organization - is desired, where objects and sources are kept in different directories, - a useful technique is to create dummy ALI files in the desired directories. - When detecting such a dummy file, @code{gnatmake} will be forced to recompile - the corresponding source file, and it will be put the resulting object - and ALI files in the directory where it found the dummy file. - - @item ^-j^/PROCESSES=^@var{n} - @cindex @code{^-j^/PROCESSES^} (@code{gnatmake}) - @cindex Parallel make - Use @var{n} processes to carry out the (re)compilations. On a - multiprocessor machine compilations will occur in parallel. In the - event of compilation errors, messages from various compilations might - get interspersed (but @code{gnatmake} will give you the full ordered - list of failing compiles at the end). If this is problematic, rerun - the make process with n set to 1 to get a clean list of messages. - - @item ^-k^/CONTINUE_ON_ERROR^ - @cindex @code{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake}) - Keep going. Continue as much as possible after a compilation error. To - ease the programmer's task in case of compilation errors, the list of - sources for which the compile fails is given when @code{gnatmake} - terminates. - - If @code{gnatmake} is invoked with several @file{file_names} and with this - switch, if there are compilation errors when building an executable, - @code{gnatmake} will not attempt to build the following executables. - - @item ^-l^/ACTIONS=LINK^ - @cindex @code{^-l^/ACTIONS=LINK^} (@code{gnatmake}) - Link only. Can be combined with @code{^-b^/ACTIONS=BIND^} to binding - and linking. Linking will not be performed if combined with - @code{^-c^/ACTIONS=COMPILE^} - but not with @code{^-b^/ACTIONS=BIND^}. - When not combined with @code{^-b^/ACTIONS=BIND^} - all the units in the closure of the main program must have been previously - compiled and must be up to date, and the main program need to have been bound. - The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item ^-m^/MINIMAL_RECOMPILATION^ - @cindex @code{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake}) - Specifies that the minimum necessary amount of recompilations - be performed. In this mode @code{gnatmake} ignores time - stamp differences when the only - modifications to a source file consist in adding/removing comments, - empty lines, spaces or tabs. This means that if you have changed the - comments in a source file or have simply reformatted it, using this - switch will tell gnatmake not to recompile files that depend on it - (provided other sources on which these files depend have undergone no - semantic modifications). Note that the debugging information may be - out of date with respect to the sources if the @code{-m} switch causes - a compilation to be switched, so the use of this switch represents a - trade-off between compilation time and accurate debugging information. - - @item ^-M^/DEPENDENCIES_LIST^ - @cindex Dependencies, producing list - @cindex @code{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake}) - Check if all objects are up to date. If they are, output the object - dependences to @file{stdout} in a form that can be directly exploited in - a @file{Makefile}. By default, each source file is prefixed with its - (relative or absolute) directory name. This name is whatever you - specified in the various @code{^-aI^/SOURCE_SEARCH^} - and @code{^-I^/SEARCH^} switches. If you use - @code{gnatmake ^-M^/DEPENDENCIES_LIST^} - @code{^-q^/QUIET^} - (see below), only the source file names, - without relative paths, are output. If you just specify the - @code{^-M^/DEPENDENCIES_LIST^} - switch, dependencies of the GNAT internal system files are omitted. This - is typically what you want. If you also specify - the @code{^-a^/ALL_FILES^} switch, - dependencies of the GNAT internal files are also listed. Note that - dependencies of the objects in external Ada libraries (see switch - @code{^-aL^/SKIP_MISSING=^}@var{dir} in the following list) are never reported. - - @item ^-n^/DO_OBJECT_CHECK^ - @cindex @code{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake}) - Don't compile, bind, or link. Checks if all objects are up to date. - If they are not, the full name of the first file that needs to be - recompiled is printed. - Repeated use of this option, followed by compiling the indicated source - file, will eventually result in recompiling all required units. - - @item ^-o ^/EXECUTABLE=^@var{exec_name} - @cindex @code{^-o^/EXECUTABLE^} (@code{gnatmake}) - Output executable name. The name of the final executable program will be - @var{exec_name}. If the @code{^-o^/EXECUTABLE^} switch is omitted the default - name for the executable will be the name of the input file in appropriate form - for an executable file on the host system. - - This switch cannot be used when invoking @code{gnatmake} with several - @file{file_names}. - - @item ^-q^/QUIET^ - @cindex @code{^-q^/QUIET^} (@code{gnatmake}) - Quiet. When this flag is not set, the commands carried out by - @code{gnatmake} are displayed. - - @item ^-s^/SWITCH_CHECK/^ - @cindex @code{^-s^/SWITCH_CHECK^} (@code{gnatmake}) - Recompile if compiler switches have changed since last compilation. - All compiler switches but -I and -o are taken into account in the - following way: - orders between different ``first letter'' switches are ignored, but - orders between same switches are taken into account. For example, - @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent - to @code{-O -g}. - - @item ^-u^/UNIQUE^ - @cindex @code{^-u^/UNIQUE^} (@code{gnatmake}) - Unique. Recompile at most the main file. It implies -c. Combined with - -f, it is equivalent to calling the compiler directly. - - @item ^-v^/REASONS^ - @cindex @code{^-v^/REASONS^} (@code{gnatmake}) - Verbose. Displays the reason for all recompilations @code{gnatmake} - decides are necessary. - - @item ^-z^/NOMAIN^ - @cindex @code{^-z^/NOMAIN^} (@code{gnatmake}) - No main subprogram. Bind and link the program even if the unit name - given on the command line is a package name. The resulting executable - will execute the elaboration routines of the package and its closure, - then the finalization routines. - - @item @code{gcc} @asis{switches} - @ifclear vms - The switch @code{-g} or any uppercase switch (other than @code{-A}, - @code{-L} or - @code{-S}) or any switch that is more than one character is passed to - @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.) - @end ifclear - @ifset vms - Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE} - but is recognizable as a valid qualifier for @code{GNAT COMPILE} is - automatically treated as a compiler switch, and passed on to all - compilations that are carried out. - @end ifset - @end table - - @noindent - Source and library search path switches: - - @table @code - @item ^-aI^/SOURCE_SEARCH=^@var{dir} - @cindex @code{^-aI^/SOURCE_SEARCH^} (@code{gnatmake}) - When looking for source files also look in directory @var{dir}. - The order in which source files search is undertaken is - described in @ref{Search Paths and the Run-Time Library (RTL)}. - - @item ^-aL^/SKIP_MISSING=^@var{dir} - @cindex @code{^-aL^/SKIP_MISSING^} (@code{gnatmake}) - Consider @var{dir} as being an externally provided Ada library. - Instructs @code{gnatmake} to skip compilation units whose @file{.ali} - files have been located in directory @var{dir}. This allows you to have - missing bodies for the units in @var{dir} and to ignore out of date bodies - for the same units. You still need to specify - the location of the specs for these units by using the switches - @code{^-aI^/SOURCE_SEARCH=^@var{dir}} - or @code{^-I^/SEARCH=^@var{dir}}. - Note: this switch is provided for compatibility with previous versions - of @code{gnatmake}. The easier method of causing standard libraries - to be excluded from consideration is to write-protect the corresponding - ALI files. - - @item ^-aO^/OBJECT_SEARCH=^@var{dir} - @cindex @code{^-aO^/OBJECT_SEARCH^} (@code{gnatmake}) - When searching for library and object files, look in directory - @var{dir}. The order in which library files are searched is described in - @ref{Search Paths for gnatbind}. - - @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir} - @cindex Search paths, for @code{gnatmake} - @cindex @code{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake}) - Equivalent to @code{^-aL^/SKIP_MISSING=^@var{dir} - ^-aI^/SOURCE_SEARCH=^@var{dir}}. - - @item ^-I^/SEARCH=^@var{dir} - @cindex @code{^-I^/SEARCH^} (@code{gnatmake}) - Equivalent to @code{^-aO^/OBJECT_SEARCH=^@var{dir} - ^-aI^/SOURCE_SEARCH=^@var{dir}}. - - @item ^-I-^/NOCURRENT_DIRECTORY^ - @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake}) - @cindex Source files, suppressing search - Do not look for source files in the directory containing the source - file named in the command line. - Do not look for ALI or object files in the directory - where @code{gnatmake} was invoked. - - @item ^-L^/LIBRARY_SEARCH=^@var{dir} - @cindex @code{^-L^/LIBRARY_SEARCH^} (@code{gnatmake}) - @cindex Linker libraries - Add directory @var{dir} to the list of directories in which the linker - @ifset wnt - Furthermore, under Windows, the sources pointed to by the libraries path - set in the registry are not searched for. - @end ifset - will search for libraries. This is equivalent to - @code{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}. - - @item -nostdinc - @cindex @code{-nostdinc} (@code{gnatmake}) - Do not look for source files in the system default directory. - - @item -nostdlib - @cindex @code{-nostdlib} (@code{gnatmake}) - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatmake}) - Specifies the default location of the runtime library. We look for the runtime - in the following directories, and stop as soon as a valid runtime is found - ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present): - - @itemize @bullet - @item /$rts_path - - @item /$rts_path - - @item /rts-$rts_path - @end itemize - - @noindent - The selected path is handled like a normal RTS path. - - @end table - - @node Mode Switches for gnatmake - @section Mode Switches for @code{gnatmake} - - @noindent - The mode switches (referred to as @code{mode_switches}) allow the - inclusion of switches that are to be passed to the compiler itself, the - binder or the linker. The effect of a mode switch is to cause all - subsequent switches up to the end of the switch list, or up to the next - mode switch, to be interpreted as switches to be passed on to the - designated component of GNAT. - - @table @code - @item -cargs @var{switches} - @cindex @code{-cargs} (@code{gnatmake}) - Compiler switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all compile steps performed by @code{gnatmake}. - - @item -bargs @var{switches} - @cindex @code{-bargs} (@code{gnatmake}) - Binder switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all bind steps performed by @code{gnatmake}. - - @item -largs @var{switches} - @cindex @code{-largs} (@code{gnatmake}) - Linker switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all link steps performed by @code{gnatmake}. - @end table - - @node Notes on the Command Line - @section Notes on the Command Line - - @noindent - This section contains some additional useful notes on the operation - of the @code{gnatmake} command. - - @itemize @bullet - @item - @cindex Recompilation, by @code{gnatmake} - If @code{gnatmake} finds no ALI files, it recompiles the main program - and all other units required by the main program. - This means that @code{gnatmake} - can be used for the initial compile, as well as during subsequent steps of - the development cycle. - - @item - If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb} - is a subunit or body of a generic unit, @code{gnatmake} recompiles - @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a - warning. - - @item - In @code{gnatmake} the switch @code{^-I^/SEARCH^} - is used to specify both source and - library file paths. Use @code{^-aI^/SOURCE_SEARCH^} - instead if you just want to specify - source paths only and @code{^-aO^/OBJECT_SEARCH^} - if you want to specify library paths - only. - - @item - @code{gnatmake} examines both an ALI file and its corresponding object file - for consistency. If an ALI is more recent than its corresponding object, - or if the object file is missing, the corresponding source will be recompiled. - Note that @code{gnatmake} expects an ALI and the corresponding object file - to be in the same directory. - - @item - @code{gnatmake} will ignore any files whose ALI file is write-protected. - This may conveniently be used to exclude standard libraries from - consideration and in particular it means that the use of the - @code{^-f^/FORCE_COMPILE^} switch will not recompile these files - unless @code{^-a^/ALL_FILES^} is also specified. - - @item - @code{gnatmake} has been designed to make the use of Ada libraries - particularly convenient. Assume you have an Ada library organized - as follows: ^@var{obj-dir}^[@var{OBJ_DIR}]^ contains the objects and ALI files for - of your Ada compilation units, - whereas ^@var{include-dir}^[@var{INCLUDE_DIR}]^ contains the - specs of these units, but no bodies. Then to compile a unit - stored in @code{main.adb}, which uses this Ada library you would just type - - @smallexample - @ifclear vms - $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main - @end ifclear - @ifset vms - $ gnatmake /SOURCE_SEARCH=[@var{INCLUDE_DIR}] - /SKIP_MISSING=[@var{OBJ_DIR}] main - @end ifset - @end smallexample - - @item - Using @code{gnatmake} along with the - @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^} - switch provides a mechanism for avoiding unnecessary rcompilations. Using - this switch, - you can update the comments/format of your - source files without having to recompile everything. Note, however, that - adding or deleting lines in a source files may render its debugging - info obsolete. If the file in question is a spec, the impact is rather - limited, as that debugging info will only be useful during the - elaboration phase of your program. For bodies the impact can be more - significant. In all events, your debugger will warn you if a source file - is more recent than the corresponding object, and alert you to the fact - that the debugging information may be out of date. - @end itemize - - @node How gnatmake Works - @section How @code{gnatmake} Works - - @noindent - Generally @code{gnatmake} automatically performs all necessary - recompilations and you don't need to worry about how it works. However, - it may be useful to have some basic understanding of the @code{gnatmake} - approach and in particular to understand how it uses the results of - previous compilations without incorrectly depending on them. - - First a definition: an object file is considered @dfn{up to date} if the - corresponding ALI file exists and its time stamp predates that of the - object file and if all the source files listed in the - dependency section of this ALI file have time stamps matching those in - the ALI file. This means that neither the source file itself nor any - files that it depends on have been modified, and hence there is no need - to recompile this file. - - @code{gnatmake} works by first checking if the specified main unit is up - to date. If so, no compilations are required for the main unit. If not, - @code{gnatmake} compiles the main program to build a new ALI file that - reflects the latest sources. Then the ALI file of the main unit is - examined to find all the source files on which the main program depends, - and @code{gnatmake} recursively applies the above procedure on all these files. - - This process ensures that @code{gnatmake} only trusts the dependencies - in an existing ALI file if they are known to be correct. Otherwise it - always recompiles to determine a new, guaranteed accurate set of - dependencies. As a result the program is compiled "upside down" from what may - be more familiar as the required order of compilation in some other Ada - systems. In particular, clients are compiled before the units on which - they depend. The ability of GNAT to compile in any order is critical in - allowing an order of compilation to be chosen that guarantees that - @code{gnatmake} will recompute a correct set of new dependencies if - necessary. - - When invoking @code{gnatmake} with several @var{file_names}, if a unit is - imported by several of the executables, it will be recompiled at most once. - - @node Examples of gnatmake Usage - @section Examples of @code{gnatmake} Usage - - @table @code - @item gnatmake hello.adb - Compile all files necessary to bind and link the main program - @file{hello.adb} (containing unit @code{Hello}) and bind and link the - resulting object files to generate an executable file @file{^hello^HELLO.EXE^}. - - @item gnatmake main1 main2 main3 - Compile all files necessary to bind and link the main programs - @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb} - (containing unit @code{Main2}) and @file{main3.adb} - (containing unit @code{Main3}) and bind and link the resulting object files - to generate three executable files @file{^main1^MAIN1.EXE^}, - @file{^main2^MAIN2.EXE^} - and @file{^main3^MAIN3.EXE^}. - - @ifclear vms - @item gnatmake -q Main_Unit -cargs -O2 -bargs -l - @end ifclear - - @ifset vms - @item gnatmake Main_Unit /QUIET /COMPILER_QUALIFIERS /OPTIMIZE=ALL /BINDER_QUALIFIERS /ORDER_OF_ELABORATION - @end ifset - Compile all files necessary to bind and link the main program unit - @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will - be done with optimization level 2 and the order of elaboration will be - listed by the binder. @code{gnatmake} will operate in quiet mode, not - displaying commands it is executing. - @end table - - @node Renaming Files Using gnatchop - @chapter Renaming Files Using @code{gnatchop} - @findex gnatchop - - @noindent - This chapter discusses how to handle files with multiple units by using - the @code{gnatchop} utility. This utility is also useful in renaming - files to meet the standard GNAT default file naming conventions. - - @menu - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - @end menu - - @node Handling Files with Multiple Units - @section Handling Files with Multiple Units - - @noindent - The basic compilation model of GNAT requires that a file submitted to the - compiler have only one unit and there be a strict correspondence - between the file name and the unit name. - - The @code{gnatchop} utility allows both of these rules to be relaxed, - allowing GNAT to process files which contain multiple compilation units - and files with arbitrary file names. @code{gnatchop} - reads the specified file and generates one or more output files, - containing one unit per file. The unit and the file name correspond, - as required by GNAT. - - If you want to permanently restructure a set of "foreign" files so that - they match the GNAT rules, and do the remaining development using the - GNAT structure, you can simply use @code{gnatchop} once, generate the - new set of files and work with them from that point on. - - Alternatively, if you want to keep your files in the "foreign" format, - perhaps to maintain compatibility with some other Ada compilation - system, you can set up a procedure where you use @code{gnatchop} each - time you compile, regarding the source files that it writes as temporary - files that you throw away. - - @node Operating gnatchop in Compilation Mode - @section Operating gnatchop in Compilation Mode - - @noindent - The basic function of @code{gnatchop} is to take a file with multiple units - and split it into separate files. The boundary between files is reasonably - clear, except for the issue of comments and pragmas. In default mode, the - rule is that any pragmas between units belong to the previous unit, except - that configuration pragmas always belong to the following unit. Any comments - belong to the following unit. These rules - almost always result in the right choice of - the split point without needing to mark it explicitly and most users will - find this default to be what they want. In this default mode it is incorrect to - submit a file containing only configuration pragmas, or one that ends in - configuration pragmas, to @code{gnatchop}. - - However, using a special option to activate "compilation mode", - @code{gnatchop} - can perform another function, which is to provide exactly the semantics - required by the RM for handling of configuration pragmas in a compilation. - In the absence of configuration pragmas (at the main file level), this - option has no effect, but it causes such configuration pragmas to be handled - in a quite different manner. - - First, in compilation mode, if @code{gnatchop} is given a file that consists of - only configuration pragmas, then this file is appended to the - @file{gnat.adc} file in the current directory. This behavior provides - the required behavior described in the RM for the actions to be taken - on submitting such a file to the compiler, namely that these pragmas - should apply to all subsequent compilations in the same compilation - environment. Using GNAT, the current directory, possibly containing a - @file{gnat.adc} file is the representation - of a compilation environment. For more information on the - @file{gnat.adc} file, see the section on handling of configuration - pragmas @pxref{Handling of Configuration Pragmas}. - - Second, in compilation mode, if @code{gnatchop} - is given a file that starts with - configuration pragmas, and contains one or more units, then these - configuration pragmas are prepended to each of the chopped files. This - behavior provides the required behavior described in the RM for the - actions to be taken on compiling such a file, namely that the pragmas - apply to all units in the compilation, but not to subsequently compiled - units. - - Finally, if configuration pragmas appear between units, they are appended - to the previous unit. This results in the previous unit being illegal, - since the compiler does not accept configuration pragmas that follow - a unit. This provides the required RM behavior that forbids configuration - pragmas other than those preceding the first compilation unit of a - compilation. - - For most purposes, @code{gnatchop} will be used in default mode. The - compilation mode described above is used only if you need exactly - accurate behavior with respect to compilations, and you have files - that contain multiple units and configuration pragmas. In this - circumstance the use of @code{gnatchop} with the compilation mode - switch provides the required behavior, and is for example the mode - in which GNAT processes the ACVC tests. - - @node Command Line for gnatchop - @section Command Line for @code{gnatchop} - - @noindent - The @code{gnatchop} command has the form: - - @smallexample - $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...] - [@var{directory}] - @end smallexample - - @noindent - The only required argument is the file name of the file to be chopped. - There are no restrictions on the form of this file name. The file itself - contains one or more Ada units, in normal GNAT format, concatenated - together. As shown, more than one file may be presented to be chopped. - - When run in default mode, @code{gnatchop} generates one output file in - the current directory for each unit in each of the files. - - @var{directory}, if specified, gives the name of the directory to which - the output files will be written. If it is not specified, all files are - written to the current directory. - - For example, given a - file called @file{hellofiles} containing - - @smallexample - @group - @cartouche - @b{procedure} hello; - - @b{with} Text_IO; @b{use} Text_IO; - @b{procedure} hello @b{is} - @b{begin} - Put_Line ("Hello"); - @b{end} hello; - @end cartouche - @end group - @end smallexample - - @noindent - the command - - @smallexample - $ gnatchop ^hellofiles^HELLOFILES.^ - @end smallexample - - @noindent - generates two files in the current directory, one called - @file{hello.ads} containing the single line that is the procedure spec, - and the other called @file{hello.adb} containing the remaining text. The - original file is not affected. The generated files can be compiled in - the normal manner. - - @node Switches for gnatchop - @section Switches for @code{gnatchop} - - @noindent - @code{gnatchop} recognizes the following switches: - - @table @code - - @item ^-c^/COMPILATION^ - @cindex @code{^-c^/COMPILATION^} (@code{gnatchop}) - Causes @code{gnatchop} to operate in compilation mode, in which - configuration pragmas are handled according to strict RM rules. See - previous section for a full description of this mode. - - @ifclear vms - @item -gnatxxx - This passes the given @option{-gnatxxx} switch to @code{gnat} which is - used to parse the given file. Not all @code{xxx} options make sense, - but for example, the use of @option{-gnati2} allows @code{gnatchop} to - process a source file that uses Latin-2 coding for identifiers. - @end ifclear - - @item ^-h^/HELP^ - Causes @code{gnatchop} to generate a brief help summary to the standard - output file showing usage information. - - @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^ - @cindex @code{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop}) - Limit generated file names to the specified number @code{mm} - of characters. - This is useful if the - resulting set of files is required to be interoperable with systems - which limit the length of file names. - @ifset vms - If no value is given, or - if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given, - a default of 39, suitable for OpenVMS Alpha - Systems, is assumed - @end ifset - @ifclear vms - No space is allowed between the @code{-k} and the numeric value. The numeric - value may be omitted in which case a default of @code{-k8}, - suitable for use - with DOS-like file systems, is used. If no @code{-k} switch - is present then - there is no limit on the length of file names. - @end ifclear - - @item ^-p^/PRESERVE^ - @cindex @code{^-p^/PRESERVE^} (@code{gnatchop}) - Causes the file ^modification^creation^ time stamp of the input file to be - preserved and used for the time stamp of the output file(s). This may be - useful for preserving coherency of time stamps in an enviroment where - @code{gnatchop} is used as part of a standard build process. - - @item ^-q^/QUIET^ - @cindex @code{^-q^/QUIET^} (@code{gnatchop}) - Causes output of informational messages indicating the set of generated - files to be suppressed. Warnings and error messages are unaffected. - - @item ^-r^/REFERENCE^ - @cindex @code{^-r^/REFERENCE^} (@code{gnatchop}) - @findex Source_Reference - Generate @code{Source_Reference} pragmas. Use this switch if the output - files are regarded as temporary and development is to be done in terms - of the original unchopped file. This switch causes - @code{Source_Reference} pragmas to be inserted into each of the - generated files to refers back to the original file name and line number. - The result is that all error messages refer back to the original - unchopped file. - In addition, the debugging information placed into the object file (when - the @code{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified) also - refers back to this original file so that tools like profilers and - debuggers will give information in terms of the original unchopped file. - - If the original file to be chopped itself contains - a @code{Source_Reference} - pragma referencing a third file, then gnatchop respects - this pragma, and the generated @code{Source_Reference} pragmas - in the chopped file refer to the original file, with appropriate - line numbers. This is particularly useful when @code{gnatchop} - is used in conjunction with @code{gnatprep} to compile files that - contain preprocessing statements and multiple units. - - @item ^-v^/VERBOSE^ - @cindex @code{^-v^/VERBOSE^} (@code{gnatchop}) - Causes @code{gnatchop} to operate in verbose mode. The version - number and copyright notice are output, as well as exact copies of - the gnat1 commands spawned to obtain the chop control information. - - @item ^-w^/OVERWRITE^ - @cindex @code{^-w^/OVERWRITE^} (@code{gnatchop}) - Overwrite existing file names. Normally @code{gnatchop} regards it as a - fatal error if there is already a file with the same name as a - file it would otherwise output, in other words if the files to be - chopped contain duplicated units. This switch bypasses this - check, and causes all but the last instance of such duplicated - units to be skipped. - - @ifclear vms - @item --GCC=xxxx - @cindex @code{--GCC=} (@code{gnatchop}) - Specify the path of the GNAT parser to be used. When this switch is used, - no attempt is made to add the prefix to the GNAT parser executable. - @end ifclear - @end table - - @node Examples of gnatchop Usage - @section Examples of @code{gnatchop} Usage - - @table @code - @ifset vms - @item gnatchop /OVERWRITE HELLO_S.ADA [ICHBIAH.FILES] - @end ifset - @ifclear vms - @item gnatchop -w hello_s.ada ichbiah/files - @end ifclear - - Chops the source file @file{hello_s.ada}. The output files will be - placed in the directory @file{^ichbiah/files^[ICHBIAH.FILES]^}, - overwriting any - files with matching names in that directory (no files in the current - directory are modified). - - @item gnatchop ^archive^ARCHIVE.^ - Chops the source file @file{^archive^ARCHIVE.^} - into the current directory. One - useful application of @code{gnatchop} is in sending sets of sources - around, for example in email messages. The required sources are simply - concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^ - command), and then - @code{gnatchop} is used at the other end to reconstitute the original - file names. - - @item gnatchop file1 file2 file3 direc - Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing - the resulting files in the directory @file{direc}. Note that if any units - occur more than once anywhere within this set of files, an error message - is generated, and no files are written. To override this check, use the - @code{^-w^/OVERWRITE^} switch, - in which case the last occurrence in the last file will - be the one that is output, and earlier duplicate occurrences for a given - unit will be skipped. - @end table - - @node Configuration Pragmas - @chapter Configuration Pragmas - @cindex Configuration pragmas - @cindex Pragmas, configuration - - @noindent - In Ada 95, configuration pragmas include those pragmas described as - such in the Ada 95 Reference Manual, as well as - implementation-dependent pragmas that are configuration pragmas. See the - individual descriptions of pragmas in the GNAT Reference Manual for - details on these additional GNAT-specific configuration pragmas. Most - notably, the pragma @code{Source_File_Name}, which allows - specifying non-default names for source files, is a configuration - pragma. The following is a complete list of configuration pragmas - recognized by @code{GNAT}: - - @smallexample - Ada_83 - Ada_95 - C_Pass_By_Copy - Component_Alignment - Discard_Names - Elaboration_Checks - Eliminate - Extend_System - Extensions_Allowed - External_Name_Casing - Float_Representation - Initialize_Scalars - License - Locking_Policy - Long_Float - No_Run_Time - Normalize_Scalars - Polling - Propagate_Exceptions - Queuing_Policy - Ravenscar - Restricted_Run_Time - Restrictions - Reviewable - Source_File_Name - Style_Checks - Suppress - Task_Dispatching_Policy - Unsuppress - Use_VADS_Size - Warnings - Validity_Checks - @end smallexample - - @menu - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - @end menu - - @node Handling of Configuration Pragmas - @section Handling of Configuration Pragmas - - Configuration pragmas may either appear at the start of a compilation - unit, in which case they apply only to that unit, or they may apply to - all compilations performed in a given compilation environment. - - GNAT also provides the @code{gnatchop} utility to provide an automatic - way to handle configuration pragmas following the semantics for - compilations (that is, files with multiple units), described in the RM. - See section @pxref{Operating gnatchop in Compilation Mode} for details. - However, for most purposes, it will be more convenient to edit the - @file{gnat.adc} file that contains configuration pragmas directly, - as described in the following section. - - @node The Configuration Pragmas Files - @section The Configuration Pragmas Files - @cindex @file{gnat.adc} - - @noindent - In GNAT a compilation environment is defined by the current - directory at the time that a compile command is given. This current - directory is searched for a file whose name is @file{gnat.adc}. If - this file is present, it is expected to contain one or more - configuration pragmas that will be applied to the current compilation. - However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not - considered. - - Configuration pragmas may be entered into the @file{gnat.adc} file - either by running @code{gnatchop} on a source file that consists only of - configuration pragmas, or more conveniently by - direct editing of the @file{gnat.adc} file, which is a standard format - source file. - - In addition to @file{gnat.adc}, one additional file containing configuration - pragmas may be applied to the current compilation using the switch - @option{-gnatec}@var{path}. @var{path} must designate an existing file that - contains only configuration pragmas. These configuration pragmas are - in addition to those found in @file{gnat.adc} (provided @file{gnat.adc} - is present and switch @option{-gnatA} is not used). - - It is allowed to specify several switches @option{-gnatec}, however only - the last one on the command line will be taken into account. - - @ifset vms - Of special interest to GNAT OpenVMS Alpha is the following configuration pragma: - - @smallexample - @cartouche - @b{pragma} Extend_System (Aux_DEC); - @end cartouche - @end smallexample - - @noindent - In the presence of this pragma, GNAT adds to the definition of the - predefined package SYSTEM all the additional types and subprograms that are - defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details. - @end ifset - - @node Handling Arbitrary File Naming Conventions Using gnatname - @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} - @cindex Arbitrary File Naming Conventions - - @menu - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - @end menu - - @node Arbitrary File Naming Conventions - @section Arbitrary File Naming Conventions - - @noindent - The GNAT compiler must be able to know the source file name of a compilation unit. - When using the standard GNAT default file naming conventions (@code{.ads} for specs, - @code{.adb} for bodies), the GNAT compiler does not need additional information. - - @noindent - When the source file names do not follow the standard GNAT default file naming - conventions, the GNAT compiler must be given additional information through - a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file. - When the non standard file naming conventions are well-defined, a small number of - pragmas @code{Source_File_Name} specifying a naming pattern - (see @ref{Alternative File Naming Schemes}) may be sufficient. However, - if the file naming conventions are irregular or arbitrary, a number - of pragma @code{Source_File_Name} for individual compilation units must be defined. - To help maintain the correspondence between compilation unit names and - source file names within the compiler, - GNAT provides a tool @code{gnatname} to generate the required pragmas for a - set of files. - - @node Running gnatname - @section Running @code{gnatname} - - @noindent - The usual form of the @code{gnatname} command is - - @smallexample - $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}] - @end smallexample - - @noindent - All of the arguments are optional. If invoked without any argument, - @code{gnatname} will display its usage. - - @noindent - When used with at least one naming pattern, @code{gnatname} will attempt to - find all the compilation units in files that follow at least one of the - naming patterns. To find these compilation units, - @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all - regular files. - - @noindent - One or several Naming Patterns may be given as arguments to @code{gnatname}. - Each Naming Pattern is enclosed between double quotes. - A Naming Pattern is a regular expression similar to the wildcard patterns - used in file names by the Unix shells or the DOS prompt. - - @noindent - Examples of Naming Patterns are - - @smallexample - "*.[12].ada" - "*.ad[sb]*" - "body_*" "spec_*" - @end smallexample - - @noindent - For a more complete description of the syntax of Naming Patterns, see the second kind - of regular expressions described in @file{g-regexp.ads} (the "Glob" regular - expressions). - - @noindent - When invoked with no switches, @code{gnatname} will create a configuration - pragmas file @file{gnat.adc} in the current working directory, with pragmas - @code{Source_File_Name} for each file that contains a valid Ada unit. - - @node Switches for gnatname - @section Switches for @code{gnatname} - - @noindent - Switches for @code{gnatname} must precede any specified Naming Pattern. - - @noindent - You may specify any of the following switches to @code{gnatname}: - - @table @code - - @item -c@file{file} - @cindex @code{-c} (@code{gnatname}) - Create a configuration pragmas file @file{file} (instead of the default - @file{gnat.adc}). There may be zero, one or more space between @code{-c} and - @file{file}. @file{file} may include directory information. @file{file} must be - writeable. There may be only one switch @code{-c}. When a switch @code{-c} is - specified, no switch @code{-P} may be specified (see below). - - @item -d@file{dir} - @cindex @code{-d} (@code{gnatname}) - Look for source files in directory @file{dir}. There may be zero, one or more spaces - between @code{-d} and @file{dir}. When a switch @code{-d} is specified, - the current working directory will not be searched for source files, unless it - is explictly - specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be - specified. If @file{dir} is a relative path, it is relative to the directory of - the configuration pragmas file specified with switch @code{-c}, or to the directory - of the project file specified with switch @code{-P} or, if neither switch @code{-c} - nor switch @code{-P} are specified, it is relative to the current working - directory. The directory - specified with switch @code{-c} must exist and be readable. - - @item -D@file{file} - @cindex @code{-D} (@code{gnatname}) - Look for source files in all directories listed in text file @file{file}. There may be - zero, one or more spaces between @code{-d} and @file{dir}. @file{file} - must be an existing, readable text file. Each non empty line in @file{file} must be - a directory. Specifying switch @code{-D} is equivalent to specifying as many switches - @code{-d} as there are non empty lines in @file{file}. - - @item -h - @cindex @code{-h} (@code{gnatname}) - Output usage (help) information. The output is written to @file{stdout}. - - @item -P@file{proj} - @cindex @code{-P} (@code{gnatname}) - Create or update project file @file{proj}. There may be zero, one or more space - between @code{-P} and @file{proj}. @file{proj} may include directory information. - @file{proj} must be writeable. There may be only one switch @code{-P}. - When a switch @code{-P} is specified, no switch @code{-c} may be specified. - - @item -v - @cindex @code{-v} (@code{gnatname}) - Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes - name of the file written, the name of the directories to search and, for each file - in those directories whose name matches at least one of the Naming Patterns, an - indication of whether the file contains a unit, and if so the name of the unit. - - @item -v -v - Very Verbose mode. In addition to the output produced in verbose mode, for each file - in the searched directories whose name matches none of the Naming Patterns, an - indication is given that there is no match. - - @item -x@file{pattern} - Excluded patterns. Using this switch, it is possible to exclude some files - that would match the name patterns. For example, - @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files - with the @file{.ada} extension, except those whose names end with - @file{_nt.ada}. - - @end table - - @node Examples of gnatname Usage - @section Examples of @code{gnatname} Usage - - @smallexample - $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" - @end smallexample - - In this example, the directory @file{/home/me} must already exist and be - writeable. In addition, the directory @file{/home/me/sources} (specified by - @code{-d sources}) must exist and be readable. Note the optional spaces after - @code{-c} and @code{-d}. - - @smallexample - $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" - @end smallexample - - Note that several switches @code{-d} may be used, even in conjunction with one - or several switches @code{-D}. Several Naming Patterns and one excluded pattern - are used in this example. - - - @c ***************************************** - @c * G N A T P r o j e c t M a n a g e r * - @c ***************************************** - @node GNAT Project Manager - @chapter GNAT Project Manager - - @menu - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - @end menu - - - @c **************** - @c * Introduction * - @c **************** - - @node Introduction - @section Introduction - - @noindent - This chapter describes GNAT's @emph{Project Manager}, a facility that - lets you configure various properties for a collection of source files. In - particular, you can specify: - @itemize @bullet - @item - The directory or set of directories containing the source files, and/or the - names of the specific source files themselves - @item - The directory in which the compiler's output - (@file{ALI} files, object files, tree files) will be placed - @item - The directory in which the executable programs will be placed - @item - Switch settings for any of the project-enabled tools (@command{gnatmake}, - compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind}); - you can apply these settings either globally or to individual units - @item - The source files containing the main subprogram(s) to be built - @item - The source programming language(s) (currently Ada and/or C) - @item - Source file naming conventions; you can specify these either globally or for - individual units - @end itemize - - @menu - * Project Files:: - @end menu - - @node Project Files - @subsection Project Files - - @noindent - A @dfn{project} is a specific set of values for these properties. You can - define a project's settings in a @dfn{project file}, a text file with an - Ada-like syntax; a property value is either a string or a list of strings. - Properties that are not explicitly set receive default values. A project - file may interrogate the values of @dfn{external variables} (user-defined - command-line switches or environment variables), and it may specify property - settings conditionally, based on the value of such variables. - - In simple cases, a project's source files depend only on other source files - in the same project, or on the predefined libraries. ("Dependence" is in - the technical sense; for example, one Ada unit "with"ing another.) However, - the Project Manager also allows much more sophisticated arrangements, - with the source files in one project depending on source files in other - projects: - @itemize @bullet - @item - One project can @emph{import} other projects containing needed source files. - @item - You can organize GNAT projects in a hierarchy: a @emph{child} project - can extend a @emph{parent} project, inheriting the parent's source files and - optionally overriding any of them with alternative versions - @end itemize - - @noindent - More generally, the Project Manager lets you structure large development - efforts into hierarchical subsystems, with build decisions deferred to the - subsystem level and thus different compilation environments (switch settings) - used for different subsystems. - - The Project Manager is invoked through the @option{-P@emph{projectfile}} - switch to @command{gnatmake} or to the @command{gnat} front driver. - If you want to define (on the command line) an external variable that is - queried by the project file, additionally use the - @option{-X@emph{vbl}=@emph{value}} switch. - The Project Manager parses and interprets the project file, and drives the - invoked tool based on the project settings. - - The Project Manager supports a wide range of development strategies, - for systems of all sizes. Some typical practices that are easily handled: - @itemize @bullet - @item - Using a common set of source files, but generating object files in different - directories via different switch settings - @item - Using a mostly-shared set of source files, but with different versions of - some unit or units - @end itemize - - @noindent - The destination of an executable can be controlled inside a project file - using the @option{-o} switch. In the absence of such a switch either inside - the project file or on the command line, any executable files generated by - @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified - in the project file. If no @code{Exec_Dir} is specified, they will be placed - in the object directory of the project. - - You can use project files to achieve some of the effects of a source - versioning system (for example, defining separate projects for - the different sets of sources that comprise different releases) but the - Project Manager is independent of any source configuration management tools - that might be used by the developers. - - The next section introduces the main features of GNAT's project facility - through a sequence of examples; subsequent sections will present the syntax - and semantics in more detail. - - - @c ***************************** - @c * Examples of Project Files * - @c ***************************** - - @node Examples of Project Files - @section Examples of Project Files - @noindent - This section illustrates some of the typical uses of project files and - explains their basic structure and behavior. - - @menu - * Common Sources with Different Switches and Different Output Directories:: - * Using External Variables:: - * Importing Other Projects:: - * Extending a Project:: - @end menu - - @node Common Sources with Different Switches and Different Output Directories - @subsection Common Sources with Different Switches and Different Output Directories - - @menu - * Source Files:: - * Specifying the Object Directory:: - * Specifying the Exec Directory:: - * Project File Packages:: - * Specifying Switch Settings:: - * Main Subprograms:: - * Source File Naming Conventions:: - * Source Language(s):: - @end menu - - @noindent - Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and - @file{proc.adb} are in the @file{/common} directory. The file - @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s - package @code{Pack}. We want to compile these source files under two sets - of switches: - @itemize @bullet - @item - When debugging, we want to pass the @option{-g} switch to @command{gnatmake}, - and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the - compiler; the compiler's output is to appear in @file{/common/debug} - @item - When preparing a release version, we want to pass the @option{-O2} switch to - the compiler; the compiler's output is to appear in @file{/common/release} - @end itemize - - @noindent - The GNAT project files shown below, respectively @file{debug.gpr} and - @file{release.gpr} in the @file{/common} directory, achieve these effects. - - Diagrammatically: - @smallexample - @group - /common - debug.gpr - release.gpr - pack.ads - pack.adb - proc.adb - @end group - @group - /common/debug @{-g, -gnata, -gnato, -gnatE@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @group - /common/release @{-O2@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @end smallexample - Here are the project files: - @smallexample - @group - project Debug is - for Object_Dir use "debug"; - for Main use ("proc"); - - package Builder is - for Default_Switches ("Ada") use ("-g"); - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") - use ("-fstack-check", "-gnata", "-gnato", "-gnatE"); - end Compiler; - end Debug; - @end group - @end smallexample - - @smallexample - @group - project Release is - for Object_Dir use "release"; - for Exec_Dir use "."; - for Main use ("proc"); - - package Compiler is - for Default_Switches ("Ada") use ("-O2"); - end Compiler; - end Release; - @end group - @end smallexample - - @noindent - The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case - insensitive), and analogously the project defined by @file{release.gpr} is - @code{"Release"}. For consistency the file should have the same name as the - project, and the project file's extension should be @code{"gpr"}. These - conventions are not required, but a warning is issued if they are not followed. - - If the current directory is @file{/temp}, then the command - @smallexample - gnatmake -P/common/debug.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/debug}, and the @code{proc} - executable also in @file{/common/debug}, using the switch settings defined in - the project file. - - Likewise, the command - @smallexample - gnatmake -P/common/release.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/release}, and the @code{proc} - executable in @file{/common}, using the switch settings from the project file. - - @node Source Files - @unnumberedsubsubsec Source Files - - @noindent - If a project file does not explicitly specify a set of source directories or - a set of source files, then by default the project's source files are the - Ada source files in the project file directory. Thus @file{pack.ads}, - @file{pack.adb}, and @file{proc.adb} are the source files for both projects. - - @node Specifying the Object Directory - @unnumberedsubsubsec Specifying the Object Directory - - @noindent - Several project properties are modeled by Ada-style @emph{attributes}; - you define the property by supplying the equivalent of an Ada attribute - definition clause in the project file. - A project's object directory is such a property; the corresponding - attribute is @code{Object_Dir}, and its value is a string expression. A - directory may be specified either as absolute or as relative; in the latter - case, it is relative to the project file directory. Thus the compiler's - output is directed to @file{/common/debug} (for the @code{Debug} project) - and to @file{/common/release} (for the @code{Release} project). If - @code{Object_Dir} is not specified, then the default is the project file - directory. - - @node Specifying the Exec Directory - @unnumberedsubsubsec Specifying the Exec Directory - - @noindent - A project's exec directory is another property; the corresponding - attribute is @code{Exec_Dir}, and its value is also a string expression, - either specified as relative or absolute. If @code{Exec_Dir} is not specified, - then the default is the object directory (which may also be the project file - directory if attribute @code{Object_Dir} is not specified). Thus the executable - is placed in @file{/common/debug} for the @code{Debug} project (attribute - @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release} - project. - - @node Project File Packages - @unnumberedsubsubsec Project File Packages - - @noindent - A GNAT tool integrated with the Project Manager is modeled by a - corresponding package in the project file. - The @code{Debug} project defines the packages @code{Builder} - (for @command{gnatmake}) and @code{Compiler}; - the @code{Release} project defines only the @code{Compiler} package. - - The Ada package syntax is not to be taken literally. Although packages in - project files bear a surface resemblance to packages in Ada source code, the - notation is simply a way to convey a grouping of properties for a named - entity. Indeed, the package names permitted in project files are restricted - to a predefined set, corresponding to the project-aware tools, and the contents - of packages are limited to a small set of constructs. - The packages in the example above contain attribute definitions. - - - @node Specifying Switch Settings - @unnumberedsubsubsec Specifying Switch Settings - - @noindent - Switch settings for a project-aware tool can be specified through attributes - in the package corresponding to the tool. - The example above illustrates one of the relevant attributes, - @code{Default_Switches}, defined in the packages in both project files. - Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is - known as an @emph{associative array}. When you define this attribute, you must - supply an "index" (a literal string), and the effect of the attribute - definition is to set the value of the "array" at the specified "index". - For the @code{Default_Switches} attribute, the index is a programming - language (in our case, Ada) , and the value specified (after @code{use}) - must be a list of string expressions. - - The attributes permitted in project files are restricted to a predefined set. - Some may appear at project level, others in packages. - For any attribute that is an associate array, the index must always be a - literal string, but the restrictions on this string (e.g., a file name or a - language name) depend on the individual attribute. - Also depending on the attribute, its specified value will need to be either a - string or a string list. - - In the @code{Debug} project, we set the switches for two tools, - @command{gnatmake} and the compiler, and thus we include corresponding - packages, with each package defining the @code{Default_Switches} attribute - with index @code{"Ada"}. - Note that the package corresponding to - @command{gnatmake} is named @code{Builder}. The @code{Release} project is - similar, but with just the @code{Compiler} package. - - In project @code{Debug} above the switches starting with @option{-gnat} that - are specified in package @code{Compiler} could have been placed in package - @code{Builder}, since @command{gnatmake} transmits all such switches to the - compiler. - - @node Main Subprograms - @unnumberedsubsubsec Main Subprograms - - @noindent - One of the properties of a project is its list of main subprograms (actually - a list of names of source files containing main subprograms, with the file - extension optional. This property is captured in the @code{Main} attribute, - whose value is a list of strings. If a project defines the @code{Main} - attribute, then you do not need to identify the main subprogram(s) when - invoking @command{gnatmake} (see @ref{gnatmake and Project Files}). - - @node Source File Naming Conventions - @unnumberedsubsubsec Source File Naming Conventions - - @noindent - Since the project files do not specify any source file naming conventions, - the GNAT defaults are used. The mechanism for defining source file naming - conventions -- a package named @code{Naming} -- will be described below - (@pxref{Naming Schemes}). - - @node Source Language(s) - @unnumberedsubsubsec Source Language(s) - - @noindent - Since the project files do not specify a @code{Languages} attribute, by - default the GNAT tools assume that the language of the project file is Ada. - More generally, a project can comprise source files - in Ada, C, and/or other languages. - - @node Using External Variables - @subsection Using External Variables - - @noindent - Instead of supplying different project files for debug and release, we can - define a single project file that queries an external variable (set either - on the command line or via an environment variable) in order to - conditionally define the appropriate settings. Again, assume that the - source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are - located in directory @file{/common}. The following project file, - @file{build.gpr}, queries the external variable named @code{STYLE} and - defines an object directory and switch settings based on whether the value - is @code{"deb"} (debug) or @code{"rel"} (release), where the default is - @code{"deb"}. - - @smallexample - @group - project Build is - for Main use ("proc"); - - type Style_Type is ("deb", "rel"); - Style : Style_Type := external ("STYLE", "deb"); - - case Style is - when "deb" => - for Object_Dir use "debug"; - - when "rel" => - for Object_Dir use "release"; - for Exec_Dir use "."; - end case; - @end group - - @group - package Builder is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-g"); - end case; - - end Builder; - @end group - - @group - package Compiler is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE"); - - when "rel" => - for Default_Switches ("Ada") use ("-O2"); - end case; - - end Compiler; - - end Build; - @end group - @end smallexample - - @noindent - @code{Style_Type} is an example of a @emph{string type}, which is the project - file analog of an Ada enumeration type but containing string literals rather - than identifiers. @code{Style} is declared as a variable of this type. - - The form @code{external("STYLE", "deb")} is known as an - @emph{external reference}; its first argument is the name of an - @emph{external variable}, and the second argument is a default value to be - used if the external variable doesn't exist. You can define an external - variable on the command line via the @option{-X} switch, or you can use an - environment variable as an external variable. - - Each @code{case} construct is expanded by the Project Manager based on the - value of @code{Style}. Thus the command - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=deb - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{debug.gpr} in the earlier example. So is the command - @smallexample - gnatmake -P/common/build.gpr - @end smallexample - - @noindent - since @code{"deb"} is the default for @code{STYLE}. - - Analogously, - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=rel - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{release.gpr} in the earlier example. - - - @node Importing Other Projects - @subsection Importing Other Projects - - @noindent - A compilation unit in a source file in one project may depend on compilation - units in source files in other projects. To obtain this behavior, the - dependent project must @emph{import} the projects containing the needed source - files. This effect is embodied in syntax similar to an Ada @code{with} clause, - but the "with"ed entities are strings denoting project files. - - As an example, suppose that the two projects @code{GUI_Proj} and - @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and - @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm}, - respectively. Assume that the source files for @code{GUI_Proj} are - @file{gui.ads} and @file{gui.adb}, and that the source files for - @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of - files located in its respective project file directory. Diagrammatically: - - @smallexample - @group - /gui - gui_proj.gpr - gui.ads - gui.adb - @end group - - @group - /comm - comm_proj.gpr - comm.ads - comm.adb - @end group - @end smallexample - - @noindent - We want to develop an application in directory @file{/app} that "with"s the - packages @code{GUI} and @code{Comm}, using the properties of the - corresponding project files (e.g. the switch settings and object directory). - Skeletal code for a main procedure might be something like the following: - - @smallexample - @group - with GUI, Comm; - procedure App_Main is - ... - begin - ... - end App_Main; - @end group - @end smallexample - - @noindent - Here is a project file, @file{app_proj.gpr}, that achieves the desired - effect: - - @smallexample - @group - with "/gui/gui_proj", "/comm/comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Building an executable is achieved through the command: - @smallexample - gnatmake -P/app/app_proj - @end smallexample - @noindent - which will generate the @code{app_main} executable in the directory where - @file{app_proj.gpr} resides. - - If an imported project file uses the standard extension (@code{gpr}) then - (as illustrated above) the @code{with} clause can omit the extension. - - Our example specified an absolute path for each imported project file. - Alternatively, you can omit the directory if either - @itemize @bullet - @item - The imported project file is in the same directory as the importing project - file, or - @item - You have defined an environment variable @code{ADA_PROJECT_PATH} that - includes the directory containing the needed project file. - @end itemize - - @noindent - Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and - @file{/comm}, then our project file @file{app_proj.gpr} could be written as - follows: - - @smallexample - @group - with "gui_proj", "comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Importing other projects raises the possibility of ambiguities. For - example, the same unit might be present in different imported projects, or - it might be present in both the importing project and an imported project. - Both of these conditions are errors. Note that in the current version of - the Project Manager, it is illegal to have an ambiguous unit even if the - unit is never referenced by the importing project. This restriction may be - relaxed in a future release. - - @node Extending a Project - @subsection Extending a Project - - @noindent - A common situation in large software systems is to have multiple - implementations for a common interface; in Ada terms, multiple versions of a - package body for the same specification. For example, one implementation - might be safe for use in tasking programs, while another might only be used - in sequential applications. This can be modeled in GNAT using the concept - of @emph{project extension}. If one project (the "child") @emph{extends} - another project (the "parent") then by default all source files of the - parent project are inherited by the child, but the child project can - override any of the parent's source files with new versions, and can also - add new files. This facility is the project analog of extension in - Object-Oriented Programming. Project hierarchies are permitted (a child - project may be the parent of yet another project), and a project that - inherits one project can also import other projects. - - As an example, suppose that directory @file{/seq} contains the project file - @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb}, - and @file{proc.adb}: - - @smallexample - @group - /seq - pack.ads - pack.adb - proc.adb - seq_proj.gpr - @end group - @end smallexample - - @noindent - Note that the project file can simply be empty (that is, no attribute or - package is defined): - - @smallexample - @group - project Seq_Proj is - end Seq_Proj; - @end group - @end smallexample - - @noindent - implying that its source files are all the Ada source files in the project - directory. - - Suppose we want to supply an alternate version of @file{pack.adb}, in - directory @file{/tasking}, but use the existing versions of @file{pack.ads} - and @file{proc.adb}. We can define a project @code{Tasking_Proj} that - inherits @code{Seq_Proj}: - - @smallexample - @group - /tasking - pack.adb - tasking_proj.gpr - @end group - - @group - project Tasking_Proj extends "/seq/seq_proj" is - end Tasking_Proj; - @end group - @end smallexample - - @noindent - The version of @file{pack.adb} used in a build depends on which project file - is specified. - - Note that we could have designed this using project import rather than - project inheritance; a @code{base} project would contain the sources for - @file{pack.ads} and @file{proc.adb}, a sequential project would import - @code{base} and add @file{pack.adb}, and likewise a tasking project would - import @code{base} and add a different version of @file{pack.adb}. The - choice depends on whether other sources in the original project need to be - overridden. If they do, then project extension is necessary, otherwise, - importing is sufficient. - - - @c *********************** - @c * Project File Syntax * - @c *********************** - - @node Project File Syntax - @section Project File Syntax - - @menu - * Basic Syntax:: - * Packages:: - * Expressions:: - * String Types:: - * Variables:: - * Attributes:: - * Associative Array Attributes:: - * case Constructions:: - @end menu - - @noindent - This section describes the structure of project files. - - A project may be an @emph{independent project}, entirely defined by a single - project file. Any Ada source file in an independent project depends only - on the predefined library and other Ada source files in the same project. - - @noindent - A project may also @dfn{depend on} other projects, in either or both of the following ways: - @itemize @bullet - @item It may import any number of projects - @item It may extend at most one other project - @end itemize - - @noindent - The dependence relation is a directed acyclic graph (the subgraph reflecting - the "extends" relation is a tree). - - A project's @dfn{immediate sources} are the source files directly defined by - that project, either implicitly by residing in the project file's directory, - or explicitly through any of the source-related attributes described below. - More generally, a project @var{proj}'s @dfn{sources} are the immediate sources - of @var{proj} together with the immediate sources (unless overridden) of any - project on which @var{proj} depends (either directly or indirectly). - - @node Basic Syntax - @subsection Basic Syntax - - @noindent - As seen in the earlier examples, project files have an Ada-like syntax. - The minimal project file is: - @smallexample - @group - project Empty is - - end Empty; - @end group - @end smallexample - - @noindent - The identifier @code{Empty} is the name of the project. - This project name must be present after the reserved - word @code{end} at the end of the project file, followed by a semi-colon. - - Any name in a project file, such as the project name or a variable name, - has the same syntax as an Ada identifier. - - The reserved words of project files are the Ada reserved words plus - @code{extends}, @code{external}, and @code{project}. Note that the only Ada - reserved words currently used in project file syntax are: - - @itemize @bullet - @item - @code{case} - @item - @code{end} - @item - @code{for} - @item - @code{is} - @item - @code{others} - @item - @code{package} - @item - @code{renames} - @item - @code{type} - @item - @code{use} - @item - @code{when} - @item - @code{with} - @end itemize - - @noindent - Comments in project files have the same syntax as in Ada, two consecutives - hyphens through the end of the line. - - @node Packages - @subsection Packages - - @noindent - A project file may contain @emph{packages}. The name of a package must be one - of the identifiers (case insensitive) from a predefined list, and a package - with a given name may only appear once in a project file. The predefined list - includes the following packages: - - @itemize @bullet - @item - @code{Naming} - @item - @code{Builder} - @item - @code{Compiler} - @item - @code{Binder} - @item - @code{Linker} - @item - @code{Finder} - @item - @code{Cross_Reference} - @item - @code{gnatls} - @end itemize - - @noindent - (The complete list of the package names and their attributes can be found - in file @file{prj-attr.adb}). - - @noindent - In its simplest form, a package may be empty: - - @smallexample - @group - project Simple is - package Builder is - end Builder; - end Simple; - @end group - @end smallexample - - @noindent - A package may contain @emph{attribute declarations}, - @emph{variable declarations} and @emph{case constructions}, as will be - described below. - - When there is ambiguity between a project name and a package name, - the name always designates the project. To avoid possible confusion, it is - always a good idea to avoid naming a project with one of the - names allowed for packages or any name that starts with @code{gnat}. - - - @node Expressions - @subsection Expressions - - @noindent - An @emph{expression} is either a @emph{string expression} or a - @emph{string list expression}. - - A @emph{string expression} is either a @emph{simple string expression} or a - @emph{compound string expression}. - - A @emph{simple string expression} is one of the following: - @itemize @bullet - @item A literal string; e.g.@code{"comm/my_proj.gpr"} - @item A string-valued variable reference (see @ref{Variables}) - @item A string-valued attribute reference (see @ref{Attributes}) - @item An external reference (see @ref{External References in Project Files}) - @end itemize - - @noindent - A @emph{compound string expression} is a concatenation of string expressions, - using @code{"&"} - @smallexample - Path & "/" & File_Name & ".ads" - @end smallexample - - @noindent - A @emph{string list expression} is either a - @emph{simple string list expression} or a - @emph{compound string list expression}. - - A @emph{simple string list expression} is one of the following: - @itemize @bullet - @item A parenthesized list of zero or more string expressions, separated by commas - @smallexample - File_Names := (File_Name, "gnat.adc", File_Name & ".orig"); - Empty_List := (); - @end smallexample - @item A string list-valued variable reference - @item A string list-valued attribute reference - @end itemize - - @noindent - A @emph{compound string list expression} is the concatenation (using - @code{"&"}) of a simple string list expression and an expression. Note that - each term in a compound string list expression, except the first, may be - either a string expression or a string list expression. - - @smallexample - @group - File_Name_List := () & File_Name; -- One string in this list - Extended_File_Name_List := File_Name_List & (File_Name & ".orig"); - -- Two strings - Big_List := File_Name_List & Extended_File_Name_List; - -- Concatenation of two string lists: three strings - Illegal_List := "gnat.adc" & Extended_File_Name_List; - -- Illegal: must start with a string list - @end group - @end smallexample - - - @node String Types - @subsection String Types - - @noindent - The value of a variable may be restricted to a list of string literals. - The restricted list of string literals is given in a - @emph{string type declaration}. - - Here is an example of a string type declaration: - - @smallexample - type OS is ("NT, "nt", "Unix", "Linux", "other OS"); - @end smallexample - - @noindent - Variables of a string type are called @emph{typed variables}; all other - variables are called @emph{untyped variables}. Typed variables are - particularly useful in @code{case} constructions - (see @ref{case Constructions}). - - A string type declaration starts with the reserved word @code{type}, followed - by the name of the string type (case-insensitive), followed by the reserved - word @code{is}, followed by a parenthesized list of one or more string literals - separated by commas, followed by a semicolon. - - The string literals in the list are case sensitive and must all be different. - They may include any graphic characters allowed in Ada, including spaces. - - A string type may only be declared at the project level, not inside a package. - - A string type may be referenced by its name if it has been declared in the same - project file, or by its project name, followed by a dot, - followed by the string type name. - - - @node Variables - @subsection Variables - - @noindent - A variable may be declared at the project file level, or in a package. - Here are some examples of variable declarations: - - @smallexample - @group - This_OS : OS := external ("OS"); -- a typed variable declaration - That_OS := "Linux"; -- an untyped variable declaration - @end group - @end smallexample - - @noindent - A @emph{typed variable declaration} includes the variable name, followed by a colon, - followed by the name of a string type, followed by @code{:=}, followed by - a simple string expression. - - An @emph{untyped variable declaration} includes the variable name, - followed by @code{:=}, followed by an expression. Note that, despite the - terminology, this form of "declaration" resembles more an assignment - than a declaration in Ada. It is a declaration in several senses: - @itemize @bullet - @item - The variable name does not need to be defined previously - @item - The declaration establishes the @emph{kind} (string versus string list) of the - variable, and later declarations of the same variable need to be consistent - with this - @end itemize - - @noindent - A string variable declaration (typed or untyped) declares a variable - whose value is a string. This variable may be used as a string expression. - @smallexample - File_Name := "readme.txt"; - Saved_File_Name := File_Name & ".saved"; - @end smallexample - - @noindent - A string list variable declaration declares a variable whose value is a list - of strings. The list may contain any number (zero or more) of strings. - - @smallexample - Empty_List := (); - List_With_One_Element := ("-gnaty"); - List_With_Two_Elements := List_With_One_Element & "-gnatg"; - Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada" - "pack2.ada", "util_.ada", "util.ada"); - @end smallexample - - @noindent - The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable. - - The same untyped variable may be declared several times. - In this case, the new value replaces the old one, - and any subsequent reference to the variable uses the new value. - However, as noted above, if a variable has been declared as a string, all subsequent - declarations must give it a string value. Similarly, if a variable has - been declared as a string list, all subsequent declarations - must give it a string list value. - - A @emph{variable reference} may take several forms: - - @itemize @bullet - @item The simple variable name, for a variable in the current package (if any) or in the current project - @item A context name, followed by a dot, followed by the variable name. - @end itemize - - @noindent - A @emph{context} may be one of the following: - - @itemize @bullet - @item The name of an existing package in the current project - @item The name of an imported project of the current project - @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly) - @item An imported/parent project name, followed by a dot, followed by a package name - @end itemize - - @noindent - A variable reference may be used in an expression. - - - @node Attributes - @subsection Attributes - - @noindent - A project (and its packages) may have @emph{attributes} that define the project's properties. - Some attributes have values that are strings; - others have values that are string lists. - - There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays} - (see @ref{Associative Array Attributes}). - - The names of the attributes are restricted; there is a list of project - attributes, and a list of package attributes for each package. - The names are not case sensitive. - - The project attributes are as follows (all are simple attributes): - - @multitable @columnfractions .4 .3 - @item @emph{Attribute Name} - @tab @emph{Value} - @item @code{Source_Files} - @tab string list - @item @code{Source_Dirs} - @tab string list - @item @code{Source_List_File} - @tab string - @item @code{Object_Dir} - @tab string - @item @code{Exec_Dir} - @tab string - @item @code{Main} - @tab string list - @item @code{Languages} - @tab string list - @item @code{Library_Dir} - @tab string - @item @code{Library_Name} - @tab string - @item @code{Library_Kind} - @tab string - @item @code{Library_Elaboration} - @tab string - @item @code{Library_Version} - @tab string - @end multitable - - @noindent - The attributes for package @code{Naming} are as follows - (see @ref{Naming Schemes}): - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Specification_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Implementation_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Separate_Suffix} - @tab simple attribute - @tab n/a - @tab string - @item @code{Casing} - @tab simple attribute - @tab n/a - @tab string - @item @code{Dot_Replacement} - @tab simple attribute - @tab n/a - @tab string - @item @code{Specification} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Implementation} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Specification_Exceptions} - @tab associative array - @tab language name - @tab string list - @item @code{Implementation_Exceptions} - @tab associative array - @tab language name - @tab string list - @end multitable - - @noindent - The attributes for package @code{Builder}, @code{Compiler}, @code{Binder}, - @code{Linker}, @code{Cross_Reference}, and @code{Finder} - are as follows (see @ref{Switches and Project Files}). - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Default_Switches} - @tab associative array - @tab language name - @tab string list - @item @code{Switches} - @tab associative array - @tab file name - @tab string list - @end multitable - - @noindent - In addition, package @code{Builder} has a single string attribute - @code{Local_Configuration_Pragmas} and package @code{Builder} has a single - string attribute @code{Global_Configuration_Pragmas}. - - @noindent - The attribute for package @code{Glide} are not documented: they are for - internal use only. - - @noindent - Each simple attribute has a default value: the empty string (for string-valued - attributes) and the empty list (for string list-valued attributes). - - Similar to variable declarations, an attribute declaration defines a new value - for an attribute. - - Examples of simple attribute declarations: - - @smallexample - for Object_Dir use "objects"; - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - @noindent - A @dfn{simple attribute declaration} starts with the reserved word @code{for}, - followed by the name of the attribute, followed by the reserved word - @code{use}, followed by an expression (whose kind depends on the attribute), - followed by a semicolon. - - Attributes may be referenced in expressions. - The general form for such a reference is @code{'}: - the entity for which the attribute is defined, - followed by an apostrophe, followed by the name of the attribute. - For associative array attributes, a litteral string between parentheses - need to be supplied as index. - - Examples are: - - @smallexample - project'Object_Dir - Naming'Dot_Replacement - Imported_Project'Source_Dirs - Imported_Project.Naming'Casing - Builder'Default_Switches("Ada") - @end smallexample - - @noindent - The entity may be: - @itemize @bullet - @item @code{project} for an attribute of the current project - @item The name of an existing package of the current project - @item The name of an imported project - @item The name of a parent project (extended by the current project) - @item An imported/parent project name, followed by a dot, - followed by a package name - @end itemize - - @noindent - Example: - @smallexample - @group - project Prj is - for Source_Dirs use project'Source_Dirs & "units"; - for Source_Dirs use project'Source_Dirs & "test/drivers" - end Prj; - @end group - @end smallexample - - @noindent - In the first attribute declaration, initially the attribute @code{Source_Dirs} - has the default value: an empty string list. After this declaration, - @code{Source_Dirs} is a string list of one element: "units". - After the second attribute declaration @code{Source_Dirs} is a string list of - two elements: "units" and "test/drivers". - - Note: this example is for illustration only. In practice, - the project file would contain only one attribute declaration: - - @smallexample - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - - @node Associative Array Attributes - @subsection Associative Array Attributes - - @noindent - Some attributes are defined as @emph{associative arrays}. An associative - array may be regarded as a function that takes a string as a parameter - and delivers a string or string list value as its result. - - Here are some examples of associative array attribute declarations: - - @smallexample - for Implementation ("main") use "Main.ada"; - for Switches ("main.ada") use ("-v", "-gnatv"); - for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g"; - @end smallexample - - @noindent - Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the - attribute, replacing the previous setting. - - - @node case Constructions - @subsection @code{case} Constructions - - @noindent - A @code{case} construction is used in a project file to effect conditional - behavior. - Here is a typical example: - - @smallexample - @group - project MyProj is - type OS_Type is ("Linux", "Unix", "NT", "VMS"); - - OS : OS_Type := external ("OS", "Linux"); - @end group - - @group - package Compiler is - case OS is - when "Linux" | "Unix" => - for Default_Switches ("Ada") use ("-gnath"); - when "NT" => - for Default_Switches ("Ada") use ("-gnatP"); - when others => - end case; - end Compiler; - end MyProj; - @end group - @end smallexample - - @noindent - The syntax of a @code{case} construction is based on the Ada case statement - (although there is no @code{null} construction for empty alternatives). - - Following the reserved word @code{case} there is the case variable (a typed - string variable), the reserved word @code{is}, and then a sequence of one or - more alternatives. - Each alternative comprises the reserved word @code{when}, either a list of - literal strings separated by the @code{"|"} character or the reserved word - @code{others}, and the @code{"=>"} token. - Each literal string must belong to the string type that is the type of the - case variable. - An @code{others} alternative, if present, must occur last. - The @code{end case;} sequence terminates the case construction. - - After each @code{=>}, there are zero or more constructions. The only - constructions allowed in a case construction are other case constructions and - attribute declarations. String type declarations, variable declarations and - package declarations are not allowed. - - The value of the case variable is often given by an external reference - (see @ref{External References in Project Files}). - - - @c **************************************** - @c * Objects and Sources in Project Files * - @c **************************************** - - @node Objects and Sources in Project Files - @section Objects and Sources in Project Files - - @menu - * Object Directory:: - * Exec Directory:: - * Source Directories:: - * Source File Names:: - @end menu - - @noindent - Each project has exactly one object directory and one or more source - directories. The source directories must contain at least one source file, - unless the project file explicitly specifies that no source files are present - (see @ref{Source File Names}). - - - @node Object Directory - @subsection Object Directory - - @noindent - The object directory for a project is the directory containing the compiler's - output (such as @file{ALI} files and object files) for the project's immediate - sources. Note that for inherited sources (when extending a parent project) the - parent project's object directory is used. - - The object directory is given by the value of the attribute @code{Object_Dir} - in the project file. - - @smallexample - for Object_Dir use "objects"; - @end smallexample - - @noindent - The attribute @var{Object_Dir} has a string value, the path name of the object - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be readable and writable. - - By default, when the attribute @code{Object_Dir} is not given an explicit value - or when its value is the empty string, the object directory is the same as the - directory containing the project file. - - - @node Exec Directory - @subsection Exec Directory - - @noindent - The exec directory for a project is the directory containing the executables - for the project's main subprograms. - - The exec directory is given by the value of the attribute @code{Exec_Dir} - in the project file. - - @smallexample - for Exec_Dir use "executables"; - @end smallexample - - @noindent - The attribute @var{Exec_Dir} has a string value, the path name of the exec - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be writable. - - By default, when the attribute @code{Exec_Dir} is not given an explicit value - or when its value is the empty string, the exec directory is the same as the - object directory of the project file. - - - @node Source Directories - @subsection Source Directories - - @noindent - The source directories of a project are specified by the project file - attribute @code{Source_Dirs}. - - This attribute's value is a string list. If the attribute is not given an - explicit value, then there is only one source directory, the one where the - project file resides. - - A @code{Source_Dirs} attribute that is explicitly defined to be the empty list, - as in - - @smallexample - for Source_Dirs use (); - @end smallexample - - @noindent - indicates that the project contains no source files. - - Otherwise, each string in the string list designates one or more - source directories. - - @smallexample - for Source_Dirs use ("sources", "test/drivers"); - @end smallexample - - @noindent - If a string in the list ends with @code{"/**"}, then the directory whose path - name precedes the two asterisks, as well as all its subdirectories - (recursively), are source directories. - - @smallexample - for Source_Dirs use ("/system/sources/**"); - @end smallexample - - @noindent - Here the directory @code{/system/sources} and all of its subdirectories - (recursively) are source directories. - - To specify that the source directories are the directory of the project file - and all of its subdirectories, you can declare @code{Source_Dirs} as follows: - @smallexample - for Source_Dirs use ("./**"); - @end smallexample - - @noindent - Each of the source directories must exist and be readable. - - - @node Source File Names - @subsection Source File Names - - @noindent - In a project that contains source files, their names may be specified by the - attributes @code{Source_Files} (a string list) or @code{Source_List_File} - (a string). Source file names never include any directory information. - - If the attribute @code{Source_Files} is given an explicit value, then each - element of the list is a source file name. - - @smallexample - for Source_Files use ("main.adb"); - for Source_Files use ("main.adb", "pack1.ads", "pack2.adb"); - @end smallexample - - @noindent - If the attribute @code{Source_Files} is not given an explicit value, - but the attribute @code{Source_List_File} is given a string value, - then the source file names are contained in the text file whose path name - (absolute or relative to the directory of the project file) is the - value of the attribute @code{Source_List_File}. - - Each line in the file that is not empty or is not a comment - contains a source file name. A comment line starts with two hyphens. - - @smallexample - for Source_List_File use "source_list.txt"; - @end smallexample - - @noindent - By default, if neither the attribute @code{Source_Files} nor the attribute - @code{Source_List_File} is given an explicit value, then each file in the - source directories that conforms to the project's naming scheme - (see @ref{Naming Schemes}) is an immediate source of the project. - - A warning is issued if both attributes @code{Source_Files} and - @code{Source_List_File} are given explicit values. In this case, the attribute - @code{Source_Files} prevails. - - Each source file name must be the name of one and only one existing source file - in one of the source directories. - - A @code{Source_Files} attribute defined with an empty list as its value - indicates that there are no source files in the project. - - Except for projects that are clearly specified as containing no Ada source - files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list, - or @code{Languages} specified without @code{"Ada"} in the list) - @smallexample - for Source_Dirs use (); - for Source_Files use (); - for Languages use ("C", "C++"); - @end smallexample - - @noindent - a project must contain at least one immediate source. - - Projects with no source files are useful as template packages - (see @ref{Packages in Project Files}) for other projects; in particular to - define a package @code{Naming} (see @ref{Naming Schemes}). - - - @c **************************** - @c * Importing Projects * - @c **************************** - - @node Importing Projects - @section Importing Projects - - @noindent - An immediate source of a project P may depend on source files that - are neither immediate sources of P nor in the predefined library. - To get this effect, P must @emph{import} the projects that contain the needed - source files. - - @smallexample - @group - with "project1", "utilities.gpr"; - with "/namings/apex.gpr"; - project Main is - ... - @end group - @end smallexample - - @noindent - As can be seen in this example, the syntax for importing projects is similar - to the syntax for importing compilation units in Ada. However, project files - use literal strings instead of names, and the @code{with} clause identifies - project files rather than packages. - - Each literal string is the file name or path name (absolute or relative) of a - project file. If a string is simply a file name, with no path, then its - location is determined by the @emph{project path}: - - @itemize @bullet - @item - If the environment variable @env{ADA_PROJECT_PATH} exists, then the project - path includes all the directories in this environment variable, plus the - directory of the project file. - - @item - If the environment variable @env{ADA_PROJECT_PATH} does not exist, - then the project path contains only one directory, namely the one where - the project file is located. - @end itemize - - @noindent - If a relative pathname is used as in - - @smallexample - with "tests/proj"; - @end smallexample - - @noindent - then the path is relative to the directory where the importing project file is - located. Any symbolic link will be fully resolved in the directory - of the importing project file before the imported project file is looked up. - - When the @code{with}'ed project file name does not have an extension, - the default is @file{.gpr}. If a file with this extension is not found, then - the file name as specified in the @code{with} clause (no extension) will be - used. In the above example, if a file @code{project1.gpr} is found, then it - will be used; otherwise, if a file @code{project1} exists then it will be used; - if neither file exists, this is an error. - - A warning is issued if the name of the project file does not match the - name of the project; this check is case insensitive. - - Any source file that is an immediate source of the imported project can be - used by the immediate sources of the importing project, and recursively. Thus - if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate - sources of @code{A} may depend on the immediate sources of @code{C}, even if - @code{A} does not import @code{C} explicitly. However, this is not recommended, - because if and when @code{B} ceases to import @code{C}, some sources in - @code{A} will no longer compile. - - A side effect of this capability is that cyclic dependences are not permitted: - if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not - allowed to import @code{A}. - - - @c ********************* - @c * Project Extension * - @c ********************* - - @node Project Extension - @section Project Extension - - @noindent - During development of a large system, it is sometimes necessary to use - modified versions of some of the source files without changing the original - sources. This can be achieved through a facility known as - @emph{project extension}. - - @smallexample - project Modified_Utilities extends "/baseline/utilities.gpr" is ... - @end smallexample - - @noindent - The project file for the project being extended (the @emph{parent}) is - identified by the literal string that follows the reserved word @code{extends}, - which itself follows the name of the extending project (the @emph{child}). - - By default, a child project inherits all the sources of its parent. - However, inherited sources can be overridden: a unit with the same name as one - in the parent will hide the original unit. - Inherited sources are considered to be sources (but not immediate sources) - of the child project; see @ref{Project File Syntax}. - - An inherited source file retains any switches specified in the parent project. - - For example if the project @code{Utilities} contains the specification and the - body of an Ada package @code{Util_IO}, then the project - @code{Modified_Utilities} can contain a new body for package @code{Util_IO}. - The original body of @code{Util_IO} will not be considered in program builds. - However, the package specification will still be found in the project - @code{Utilities}. - - A child project can have only one parent but it may import any number of other - projects. - - A project is not allowed to import directly or indirectly at the same time a - child project and any of its ancestors. - - - @c **************************************** - @c * External References in Project Files * - @c **************************************** - - @node External References in Project Files - @section External References in Project Files - - @noindent - A project file may contain references to external variables; such references - are called @emph{external references}. - - An external variable is either defined as part of the environment (an - environment variable in Unix, for example) or else specified on the command - line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the - command line value is used. - - An external reference is denoted by the built-in function - @code{external}, which returns a string value. This function has two forms: - @itemize @bullet - @item @code{external (external_variable_name)} - @item @code{external (external_variable_name, default_value)} - @end itemize - - @noindent - Each parameter must be a string literal. For example: - - @smallexample - external ("USER") - external ("OS", "Linux") - @end smallexample - - @noindent - In the form with one parameter, the function returns the value of - the external variable given as parameter. If this name is not present in the - environment, then the returned value is an empty string. - - In the form with two string parameters, the second parameter is - the value returned when the variable given as the first parameter is not - present in the environment. In the example above, if @code{"OS"} is not - the name of an environment variable and is not passed on the command line, - then the returned value will be @code{"Linux"}. - - An external reference may be part of a string expression or of a string - list expression, to define variables or attributes. - - @smallexample - @group - type Mode_Type is ("Debug", "Release"); - Mode : Mode_Type := external ("MODE"); - case Mode is - when "Debug" => - ... - @end group - @end smallexample - - - @c ***************************** - @c * Packages in Project Files * - @c ***************************** - - @node Packages in Project Files - @section Packages in Project Files - - @noindent - The @emph{package} is the project file feature that defines the settings for - project-aware tools. - For each such tool you can declare a corresponding package; the names for these - packages are preset (see @ref{Packages}) but are not case sensitive. - A package may contain variable declarations, attribute declarations, and case - constructions. - - @smallexample - @group - project Proj is - package Builder is -- used by gnatmake - for Default_Switches ("Ada") use ("-v", "-g"); - end Builder; - end Proj; - @end group - @end smallexample - - @noindent - A package declaration starts with the reserved word @code{package}, - followed by the package name (case insensitive), followed by the reserved word - @code{is}. It ends with the reserved word @code{end}, followed by the package - name, finally followed by a semi-colon. - - Most of the packages have an attribute @code{Default_Switches}. - This attribute is an associative array, and its value is a string list. - The index of the associative array is the name of a programming language (case - insensitive). This attribute indicates the switch or switches to be used - with the corresponding tool. - - Some packages also have another attribute, @code{Switches}, an associative - array whose value is a string list. The index is the name of a source file. - This attribute indicates the switch or switches to be used by the corresponding - tool when dealing with this specific file. - - Further information on these switch-related attributes is found in - @ref{Switches and Project Files}. - - A package may be declared as a @emph{renaming} of another package; e.g., from - the project file for an imported project. - - @smallexample - @group - with "/global/apex.gpr"; - project Example is - package Naming renames Apex.Naming; - ... - end Example; - @end group - @end smallexample - - @noindent - Packages that are renamed in other project files often come from project files - that have no sources: they are just used as templates. Any modification in the - template will be reflected automatically in all the project files that rename - a package from the template. - - In addition to the tool-oriented packages, you can also declare a package - named @code{Naming} to establish specialized source file naming conventions - (see @ref{Naming Schemes}). - - - @c ************************************ - @c * Variables from Imported Projects * - @c ************************************ - - @node Variables from Imported Projects - @section Variables from Imported Projects - - @noindent - An attribute or variable defined in an imported or parent project can - be used in expressions in the importing / extending project. - Such an attribute or variable is prefixed with the name of the project - and (if relevant) the name of package where it is defined. - - @smallexample - @group - with "imported"; - project Main extends "base" is - Var1 := Imported.Var; - Var2 := Base.Var & ".new"; - @end group - - @group - package Builder is - for Default_Switches ("Ada") use Imported.Builder.Ada_Switches & - "-gnatg" & "-v"; - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") use Base.Compiler.Ada_Switches; - end Compiler; - end Main; - @end group - @end smallexample - - @noindent - In this example: - - @itemize @bullet - @item - @code{Var1} is a copy of the variable @code{Var} defined in the project file - @file{"imported.gpr"} - @item - the value of @code{Var2} is a copy of the value of variable @code{Var} - defined in the project file @file{base.gpr}, concatenated with @code{".new"} - @item - attribute @code{Default_Switches ("Ada")} in package @code{Builder} - is a string list that includes in its value a copy of variable - @code{Ada_Switches} defined in the @code{Builder} package in project file - @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"}; - @item - attribute @code{Default_Switches ("Ada")} in package @code{Compiler} - is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler} - package in project file @file{base.gpr}, the project being extended. - @end itemize - - - @c ****************** - @c * Naming Schemes * - @c ****************** - - @node Naming Schemes - @section Naming Schemes - - @noindent - Sometimes an Ada software system is ported from a foreign compilation - environment to GNAT, with file names that do not use the default GNAT - conventions. Instead of changing all the file names (which for a variety of - reasons might not be possible), you can define the relevant file naming scheme - in the @code{Naming} package in your project file. For example, the following - package models the Apex file naming rules: - - @smallexample - @group - package Naming is - for Casing use "lowercase"; - for Dot_Replacement use "."; - for Specification_Suffix ("Ada") use ".1.ada"; - for Implementation_Suffix ("Ada") use ".2.ada"; - end Naming; - @end group - @end smallexample - - @noindent - You can define the following attributes in package @code{Naming}: - - @table @code - - @item @var{Casing} - This must be a string with one of the three values @code{"lowercase"}, - @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive. - - @noindent - If @var{Casing} is not specified, then the default is @code{"lowercase"}. - - @item @var{Dot_Replacement} - This must be a string whose value satisfies the following conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start or end with an alphanumeric character - @item It cannot be a single underscore - @item It cannot start with an underscore followed by an alphanumeric - @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."} - @end itemize - - @noindent - If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. - - @item @var{Specification_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @end itemize - @noindent - If @code{Specification_Suffix ("Ada")} is not specified, then the default is - @code{".ads"}. - - @item @var{Implementation_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @item It cannot be a suffix of @code{Specification_Suffix} - @end itemize - @noindent - If @code{Implementation_Suffix ("Ada")} is not specified, then the default is - @code{".adb"}. - - @item @var{Separate_Suffix} - This must be a string whose value satisfies the same conditions as - @code{Implementation_Suffix}. - - @noindent - If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same - value as @code{Implementation_Suffix ("Ada")}. - - @item @var{Specification} - @noindent - You can use the @code{Specification} attribute, an associative array, to define - the source file name for an individual Ada compilation unit's spec. The array - index must be a string literal that identifies the Ada unit (case insensitive). - The value of this attribute must be a string that identifies the file that - contains this unit's spec (case sensitive or insensitive depending on the - operating system). - - @smallexample - for Specification ("MyPack.MyChild") use "mypack.mychild.spec"; - @end smallexample - - @item @var{Implementation} - - You can use the @code{Implementation} attribute, an associative array, to - define the source file name for an individual Ada compilation unit's body - (possibly a subunit). The array index must be a string literal that identifies - the Ada unit (case insensitive). The value of this attribute must be a string - that identifies the file that contains this unit's body or subunit (case - sensitive or insensitive depending on the operating system). - - @smallexample - for Implementation ("MyPack.MyChild") use "mypack.mychild.body"; - @end smallexample - @end table - - - @c ******************** - @c * Library Projects * - @c ******************** - - @node Library Projects - @section Library Projects - - @noindent - @emph{Library projects} are projects whose object code is placed in a library. - (Note that this facility is not yet supported on all platforms) - - To create a library project, you need to define in its project file - two project-level attributes: @code{Library_Name} and @code{Library_Dir}. - Additionally, you may define the library-related attributes - @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}. - - The @code{Library_Name} attribute has a string value that must start with a - letter and include only letters and digits. - - The @code{Library_Dir} attribute has a string value that designates the path - (absolute or relative) of the directory where the library will reside. - It must designate an existing directory, and this directory needs to be - different from the project's object directory. It also needs to be writable. - - If both @code{Library_Name} and @code{Library_Dir} are specified and - are legal, then the project file defines a library project. The optional - library-related attributes are checked only for such project files. - - The @code{Library_Kind} attribute has a string value that must be one of the - following (case insensitive): @code{"static"}, @code{"dynamic"} or - @code{"relocatable"}. If this attribute is not specified, the library is a - static library. Otherwise, the library may be dynamic or relocatable. - Depending on the operating system, there may or may not be a distinction - between dynamic and relocatable libraries. For example, on Unix there is no - such distinction. - - The @code{Library_Version} attribute has a string value whose interpretation - is platform dependent. On Unix, it is used only for dynamic/relocatable - libraries as the internal name of the library (the @code{"soname"}). If the - library file name (built from the @code{Library_Name}) is different from the - @code{Library_Version}, then the library file will be a symbolic link to the - actual file whose name will be @code{Library_Version}. - - Example (on Unix): - - @smallexample - @group - project Plib is - - Version := "1"; - - for Library_Dir use "lib_dir"; - for Library_Name use "dummy"; - for Library_Kind use "relocatable"; - for Library_Version use "libdummy.so." & Version; - - end Plib; - @end group - @end smallexample - - @noindent - Directory @file{lib_dir} will contain the internal library file whose name - will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to - @file{libdummy.so.1}. - - When @command{gnatmake} detects that a project file (not the main project file) - is a library project file, it will check all immediate sources of the project - and rebuild the library if any of the sources have been recompiled. - All @file{ALI} files will also be copied from the object directory to the - library directory. To build executables, @command{gnatmake} will use the - library rather than the individual object files. - - - @c ************************************* - @c * Switches Related to Project Files * - @c ************************************* - @node Switches Related to Project Files - @section Switches Related to Project Files - - @noindent - The following switches are used by GNAT tools that support project files: - - @table @code - - @item @option{-P@var{project}} - Indicates the name of a project file. This project file will be parsed with - the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external - references indicated by @option{-X} switches, if any. - - @noindent - There must be only one @option{-P} switch on the command line. - - @noindent - Since the Project Manager parses the project file only after all the switches - on the command line are checked, the order of the switches @option{-P}, - @option{-Vp@emph{x}} or @option{-X} is not significant. - - @item @option{-X@var{name=value}} - Indicates that external variable @var{name} has the value @var{value}. - The Project Manager will use this value for occurrences of - @code{external(name)} when parsing the project file. - - @noindent - If @var{name} or @var{value} includes a space, then @var{name=value} should be - put between quotes. - @smallexample - -XOS=NT - -X"user=John Doe" - @end smallexample - - @noindent - Several @option{-X} switches can be used simultaneously. - If several @option{-X} switches specify the same @var{name}, only the last one - is used. - - @noindent - An external variable specified with a @option{-X} switch takes precedence - over the value of the same name in the environment. - - @item @option{-vP@emph{x}} - Indicates the verbosity of the parsing of GNAT project files. - @option{-vP0} means Default (no output for syntactically correct project - files); - @option{-vP1} means Medium; - @option{-vP2} means High. - @noindent - The default is Default. - @noindent - If several @option{-vP@emph{x}} switches are present, only the last one is - used. - - @end table - - - @c ********************************** - @c * Tools Supporting Project Files * - @c ********************************** - - @node Tools Supporting Project Files - @section Tools Supporting Project Files - - @menu - * gnatmake and Project Files:: - * The GNAT Driver and Project Files:: - @ifclear vms - * Glide and Project Files:: - @end ifclear - @end menu - - @node gnatmake and Project Files - @subsection gnatmake and Project Files - - @noindent - This section covers two topics related to @command{gnatmake} and project files: - defining switches for @command{gnatmake} and for the tools that it invokes; - and the use of the @code{Main} attribute. - - @menu - * Switches and Project Files:: - * Project Files and Main Subprograms:: - @end menu - - @node Switches and Project Files - @subsubsection Switches and Project Files - - @noindent - For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and - @code{Linker}, you can specify a @code{Default_Switches} attribute, a - @code{Switches} attribute, or both; as their names imply, these switch-related - attributes affect which switches are used for which files when - @command{gnatmake} is invoked. As will be explained below, these - package-contributed switches precede the switches passed on the - @command{gnatmake} command line. - - The @code{Default_Switches} attribute is an associative array indexed by - language name (case insensitive) and returning a string list. For example: - - @smallexample - @group - package Compiler is - for Default_Switches ("Ada") use ("-gnaty", "-v"); - end Compiler; - @end group - @end smallexample - - @noindent - The @code{Switches} attribute is also an associative array, indexed by a file - name (which may or may not be case sensitive, depending on the operating - system) and returning a string list. For example: - - @smallexample - @group - package Builder is - for Switches ("main1.adb") use ("-O2"); - for Switches ("main2.adb") use ("-g"); - end Builder; - @end group - @end smallexample - - @noindent - For the @code{Builder} package, the file names should designate source files - for main subprograms. For the @code{Binder} and @code{Linker} packages, the - file names should designate @file{ALI} or source files for main subprograms. - In each case just the file name (without explicit extension) is acceptable. - - For each tool used in a program build (@command{gnatmake}, the compiler, the - binder, and the linker), its corresponding package @dfn{contributes} a set of - switches for each file on which the tool is invoked, based on the - switch-related attributes defined in the package. In particular, the switches - that each of these packages contributes for a given file @var{f} comprise: - - @itemize @bullet - @item - the value of attribute @code{Switches (@var{f})}, if it is specified in the - package for the given file, - @item - otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in - the package. - @end itemize - - @noindent - If neither of these attributes is defined in the package, then the package does - not contribute any switches for the given file. - - When @command{gnatmake} is invoked on a file, the switches comprise two sets, - in the following order: those contributed for the file by the @code{Builder} - package; and the switches passed on the command line. - - When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file, - the switches passed to the tool comprise three sets, in the following order: - - @enumerate - @item - the applicable switches contributed for the file by the @code{Builder} package - in the project file supplied on the command line; - - @item - those contributed for the file by the package (in the relevant project file -- - see below) corresponding to the tool; and - - @item - the applicable switches passed on the command line. - @end enumerate - - @noindent - The term @emph{applicable switches} reflects the fact that @command{gnatmake} - switches may or may not be passed to individual tools, depending on the - individual switch. - - @command{gnatmake} may invoke the compiler on source files from different - projects. The Project Manager will use the appropriate project file to - determine the @code{Compiler} package for each source file being compiled. - Likewise for the @code{Binder} and @code{Linker} packages. - - As an example, consider the following package in a project file: - - @smallexample - @group - project Proj1 is - package Compiler is - for Default_Switches ("Ada") use ("-g"); - for Switches ("a.adb") use ("-O1"); - for Switches ("b.adb") use ("-O2", "-gnaty"); - end Compiler; - end Proj1; - @end group - @end smallexample - - @noindent - If @command{gnatmake} is invoked with this project file, and it needs to - compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then - @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb} - with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with - @option{-g}. - - Another example illustrates the ordering of the switches contributed by - different packages: - - @smallexample - @group - project Proj2 is - package Builder is - for Switches ("main.adb") use ("-g", "-O1", "-f"); - end Builder; - @end group - - @group - package Compiler is - for Switches ("main.adb") use ("-O2"); - end Compiler; - end Proj2; - @end group - @end smallexample - - @noindent - If you issue the command: - - @smallexample - gnatmake -PProj2 -O0 main - @end smallexample - - @noindent - then the compiler will be invoked on @file{main.adb} with the following sequence of switches - - @smallexample - -g -O1 -O2 -O0 - @end smallexample - - with the last @option{-O} switch having precedence over the earlier ones; - several other switches (such as @option{-c}) are added implicitly. - - The switches @option{-g} and @option{-O1} are contributed by package - @code{Builder}, @option{-O2} is contributed by the package @code{Compiler} - and @option{-O0} comes from the command line. - - The @option{-g} switch will also be passed in the invocation of - @command{gnatlink.} - - A final example illustrates switch contributions from packages in different - project files: - - @smallexample - @group - project Proj3 is - for Source_Files use ("pack.ads", "pack.adb"); - package Compiler is - for Default_Switches ("Ada") use ("-gnata"); - end Compiler; - end Proj3; - @end group - - @group - with "Proj3"; - project Proj4 is - for Source_Files use ("foo_main.adb", "bar_main.adb"); - package Builder is - for Switches ("foo_main.adb") use ("-s", "-g"); - end Builder; - end Proj4; - @end group - - @group - -- Ada source file: - with Pack; - procedure Foo_Main is - ... - end Foo_Main; - @end group - @end smallexample - - If the command is - @smallexample - gnatmake -PProj4 foo_main.adb -cargs -gnato - @end smallexample - - @noindent - then the switches passed to the compiler for @file{foo_main.adb} are - @option{-g} (contributed by the package @code{Proj4.Builder}) and - @option{-gnato} (passed on the command line). - When the imported package @code{Pack} is compiled, the switches used are - @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from - package @code{Proj3.Compiler}, and @option{-gnato} from the command line. - - - @node Project Files and Main Subprograms - @subsubsection Project Files and Main Subprograms - - @noindent - When using a project file, you can invoke @command{gnatmake} - with several main subprograms, by specifying their source files on the command - line. Each of these needs to be an immediate source file of the project. - - @smallexample - gnatmake -Pprj main1 main2 main3 - @end smallexample - - @noindent - When using a project file, you can also invoke @command{gnatmake} without - explicitly specifying any main, and the effect depends on whether you have - defined the @code{Main} attribute. This attribute has a string list value, - where each element in the list is the name of a source file (the file - extension is optional) containing a main subprogram. - - If the @code{Main} attribute is defined in a project file as a non-empty - string list and the switch @option{-u} is not used on the command line, then - invoking @command{gnatmake} with this project file but without any main on the - command line is equivalent to invoking @command{gnatmake} with all the file - names in the @code{Main} attribute on the command line. - - Example: - @smallexample - @group - project Prj is - for Main use ("main1", "main2", "main3"); - end Prj; - @end group - @end smallexample - - @noindent - With this project file, @code{"gnatmake -Pprj"} is equivalent to - @code{"gnatmake -Pprj main1 main2 main3"}. - - When the project attribute @code{Main} is not specified, or is specified - as an empty string list, or when the switch @option{-u} is used on the command - line, then invoking @command{gnatmake} with no main on the command line will - result in all immediate sources of the project file being checked, and - potentially recompiled. Depending on the presence of the switch @option{-u}, - sources from other project files on which the immediate sources of the main - project file depend are also checked and potentially recompiled. In other - words, the @option{-u} switch is applied to all of the immediate sources of themain project file. - - - @node The GNAT Driver and Project Files - @subsection The GNAT Driver and Project Files - - @noindent - A number of GNAT tools, other than @command{gnatmake} are project-aware: - @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls} - and @command{gnatxref}. However, none of these tools can be invoked directly - with a project file switch (@code{-P}). They need to be invoke through the - @command{gnat} driver. - - The @command{gnat} driver is a front-end that accepts a number of commands and - call the corresponding tool. It has been designed initially for VMS to convert - VMS style qualifiers to Unix style switches, but it is now available to all - the GNAT supported platforms. - - On non VMS platforms, the @command{gnat} driver accepts the following commands - (case insensitive): - - @itemize @bullet - @item - BIND to invoke @command{gnatbind} - @item - CHOP to invoke @command{gnatchop} - @item - COMP or COMPILE to invoke the compiler - @item - ELIM to invoke @command{gnatelim} - @item - FIND to invoke @command{gnatfind} - @item - KR or KRUNCH to invoke @command{gnatkr} - @item - LINK to invoke @command{gnatlink} - @item - LS or LIST to invoke @command{gnatls} - @item - MAKE to invoke @command{gnatmake} - @item - NAME to invoke @command{gnatname} - @item - PREP or PREPROCESS to invoke @command{gnatprep} - @item - PSTA or STANDARD to invoke @command{gnatpsta} - @item - STUB to invoke @command{gnatstub} - @item - XREF to invoke @command{gnatxref} - @end itemize - - @noindent - Note that the compiler is invoked using the command @command{gnatmake -f -u}. - - @noindent - Following the command, you may put switches and arguments for the invoked - tool. - - @smallexample - gnat bind -C main.ali - gnat ls -a main - gnat chop foo.txt - @end smallexample - - @noindent - In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project - file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in - addition to the switches of the invoking tool. - - @noindent - For each of these command, there is possibly a package in the main project that - corresponds to the invoked tool. - - @itemize @bullet - @item - package @code{Binder} for command BIND (invoking @code{gnatbind}) - - @item - package @code{Finder} for command FIND (invoking @code{gnatfind}) - - @item - package @code{Gnatls} for command LS or LIST (invoking @code{gnatls}) - - @item - package @code{Linker} for command LINK (invoking @code{gnatlink}) - - @item - package @code{Cross_Reference} for command XREF (invoking @code{gnatlink}) - - @end itemize - - @noindent - Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable - with a string list value. It contains switches for the invocation of - @code{gnatls}. - - @smallexample - @group - project Proj1 is - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - end Proj1; - @end group - @end smallexample - - @noindent - All other packages contains a switch @code{Default_Switches}, an associative - array, indexed by the programming language (case insensitive) and having a - string list value. @code{Default_Switches ("Ada")} contains the switches for - the invocation of the tool corresponding to the package. - - @smallexample - @group - project Proj is - - for Source_Dirs use ("./**"); - - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - @end group - @group - - package Binder is - for Default_Switches ("Ada") use ("-C", "-e"); - end Binder; - @end group - @group - - package Linker is - for Default_Switches ("Ada") use ("-C"); - end Linker; - @end group - @group - - package Finder is - for Default_Switches ("Ada") use ("-a", "-f"); - end Finder; - @end group - @group - - package Cross_Reference is - for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u"); - end Cross_Reference; - end Proj; - @end group - @end smallexample - - @noindent - With the above project file, commands such as - - @smallexample - gnat ls -Pproj main - gnat xref -Pproj main - gnat bind -Pproj main.ali - @end smallexample - - @noindent - will set up the environment properly and invoke the tool with the switches - found in the package corresponding to the tool. - - - @ifclear vms - @node Glide and Project Files - @subsection Glide and Project Files - - @noindent - Glide will automatically recognize the @file{.gpr} extension for - project files, and will - convert them to its own internal format automatically. However, it - doesn't provide a syntax-oriented editor for modifying these - files. - The project file will be loaded as text when you select the menu item - @code{Ada} @result{} @code{Project} @result{} @code{Edit}. - You can edit this text and save the @file{gpr} file; - when you next select this project file in Glide it - will be automatically reloaded. - - @ifset vxworks - Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value - is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the - cross-prefix. From this information the correct location for the - GNAT runtime, and thus also the correct cross-references, can be - determined. - @end ifset - @end ifclear - - - @node An Extended Example - @section An Extended Example - - @noindent - Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources - in the respective directories. We would like to build them with a single - @command{gnatmake} command, and we would like to place their object files into - @file{.build} subdirectories of the source directories. Furthermore, we would - like to have to have two separate subdirectories in @file{.build} -- - @file{release} and @file{debug} -- which will contain the object files compiled with - different set of compilation flags. - - In other words, we have the following structure: - - @smallexample - @group - main - |- prog1 - | |- .build - | | debug - | | release - |- prog2 - |- .build - | debug - | release - @end group - @end smallexample - - @noindent - Here are the project files that we need to create in a directory @file{main} - to maintain this structure: - - @enumerate - - @item We create a @code{Common} project with a package @code{Compiler} that - specifies the compilation switches: - - @smallexample - File "common.gpr": - @group - @b{project} Common @b{is} - - @b{for} Source_Dirs @b{use} (); -- No source files - @end group - - @group - @b{type} Build_Type @b{is} ("release", "debug"); - Build : Build_Type := External ("BUILD", "debug"); - @end group - @group - @b{package} Compiler @b{is} - @b{case} Build @b{is} - @b{when} "release" => - @b{for} Default_Switches ("Ada") @b{use} ("-O2"); - @b{when} "debug" => - @b{for} Default_Switches ("Ada") @b{use} ("-g"); - @b{end case}; - @b{end} Compiler; - - @b{end} Common; - @end group - @end smallexample - - @item We create separate projects for the two programs: - - @smallexample - @group - File "prog1.gpr": - - @b{with} "common"; - @b{project} Prog1 @b{is} - - @b{for} Source_Dirs @b{use} ("prog1"); - @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Prog1; - @end group - @end smallexample - - @smallexample - @group - File "prog2.gpr": - - @b{with} "common"; - @b{project} Prog2 @b{is} - - @b{for} Source_Dirs @b{use} ("prog2"); - @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @end group - @b{end} Prog2; - @end smallexample - - @item We create a wrapping project @var{Main}: - - @smallexample - @group - File "main.gpr": - - @b{with} "common"; - @b{with} "prog1"; - @b{with} "prog2"; - @b{project} Main @b{is} - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Main; - @end group - @end smallexample - - @item Finally we need to create a dummy procedure that @code{with}s (either - explicitly or implicitly) all the sources of our two programs. - - @end enumerate - - @noindent - Now we can build the programs using the command - - @smallexample - gnatmake -Pmain dummy - @end smallexample - - @noindent - for the Debug mode, or - - @smallexample - gnatmake -Pmain -XBUILD=release - @end smallexample - - @noindent - for the Release mode. - - - @c ******************************** - @c * Project File Complete Syntax * - @c ******************************** - - @node Project File Complete Syntax - @section Project File Complete Syntax - - @smallexample - project ::= - context_clause project_declaration - - context_clause ::= - @{with_clause@} - - with_clause ::= - @b{with} literal_string @{ , literal_string @} ; - - project_declaration ::= - @b{project} simple_name [ @b{extends} literal_string ] @b{is} - @{declarative_item@} - @b{end} simple_name; - - declarative_item ::= - package_declaration | - typed_string_declaration | - other_declarative_item - - package_declaration ::= - @b{package} simple_name package_completion - - package_completion ::= - package_body | package_renaming - - package body ::= - @b{is} - @{other_declarative_item@} - @b{end} simple_name ; - - package_renaming ::== - @b{renames} simple_name.simple_name ; - - typed_string_declaration ::= - @b{type} _simple_name @b{is} - ( literal_string @{, literal_string@} ); - - other_declarative_item ::= - attribute_declaration | - typed_variable_declaration | - variable_declaration | - case_construction - - attribute_declaration ::= - @b{for} attribute @b{use} expression ; - - attribute ::= - simple_name | - simple_name ( literal_string ) - - typed_variable_declaration ::= - simple_name : name := string_expression ; - - variable_declaration ::= - simple_name := expression; - - expression ::= - term @{& term@} - - term ::= - literal_string | - string_list | - name | - external_value | - attribute_reference - - literal_string ::= - (same as Ada) - - string_list ::= - ( expression @{ , expression @} ) - - external_value ::= - @b{external} ( literal_string [, literal_string] ) - - attribute_reference ::= - attribute_parent ' simple_name [ ( literal_string ) ] - - attribute_parent ::= - @b{project} | - simple_name | - simple_name . simple_name - - case_construction ::= - @b{case} name @b{is} - @{case_item@} - @b{end case} ; - - case_item ::= - @b{when} discrete_choice_list => @{case_construction | attribute_declaration@} - - discrete_choice_list ::= - literal_string @{| literal_string@} - - name ::= - simple_name @{. simple_name@} - - simple_name ::= - identifier (same as Ada) - - @end smallexample - - - @node Elaboration Order Handling in GNAT - @chapter Elaboration Order Handling in GNAT - @cindex Order of elaboration - @cindex Elaboration control - - @menu - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - @end menu - - @noindent - This chapter describes the handling of elaboration code in Ada 95 and - in GNAT, and discusses how the order of elaboration of program units can - be controlled in GNAT, either automatically or with explicit programming - features. - - @node Elaboration Code in Ada 95 - @section Elaboration Code in Ada 95 - - @noindent - Ada 95 provides rather general mechanisms for executing code at elaboration - time, that is to say before the main program starts executing. Such code arises - in three contexts: - - @table @asis - @item Initializers for variables. - Variables declared at the library level, in package specs or bodies, can - require initialization that is performed at elaboration time, as in: - @smallexample - @cartouche - Sqrt_Half : Float := Sqrt (0.5); - @end cartouche - @end smallexample - - @item Package initialization code - Code in a @code{BEGIN-END} section at the outer level of a package body is - executed as part of the package body elaboration code. - - @item Library level task allocators - Tasks that are declared using task allocators at the library level - start executing immediately and hence can execute at elaboration time. - @end table - - @noindent - Subprogram calls are possible in any of these contexts, which means that - any arbitrary part of the program may be executed as part of the elaboration - code. It is even possible to write a program which does all its work at - elaboration time, with a null main program, although stylistically this - would usually be considered an inappropriate way to structure - a program. - - An important concern arises in the context of elaboration code: - we have to be sure that it is executed in an appropriate order. What we - have is a series of elaboration code sections, potentially one section - for each unit in the program. It is important that these execute - in the correct order. Correctness here means that, taking the above - example of the declaration of @code{Sqrt_Half}, - if some other piece of - elaboration code references @code{Sqrt_Half}, - then it must run after the - section of elaboration code that contains the declaration of - @code{Sqrt_Half}. - - There would never be any order of elaboration problem if we made a rule - that whenever you @code{with} a unit, you must elaborate both the spec and body - of that unit before elaborating the unit doing the @code{with}'ing: - - @smallexample - @group - @cartouche - @b{with} Unit_1; - @b{package} Unit_2 @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - would require that both the body and spec of @code{Unit_1} be elaborated - before the spec of @code{Unit_2}. However, a rule like that would be far too - restrictive. In particular, it would make it impossible to have routines - in separate packages that were mutually recursive. - - You might think that a clever enough compiler could look at the actual - elaboration code and determine an appropriate correct order of elaboration, - but in the general case, this is not possible. Consider the following - example. - - In the body of @code{Unit_1}, we have a procedure @code{Func_1} - that references - the variable @code{Sqrt_1}, which is declared in the elaboration code - of the body of @code{Unit_1}: - - @smallexample - @cartouche - Sqrt_1 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_1} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_1 = 1 @b{then} - Q := Unit_2.Func_2; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - @code{Unit_2} is exactly parallel, - it has a procedure @code{Func_2} that references - the variable @code{Sqrt_2}, which is declared in the elaboration code of - the body @code{Unit_2}: - - @smallexample - @cartouche - Sqrt_2 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_2} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_2 = 2 @b{then} - Q := Unit_1.Func_1; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the question is, which of the following orders of elaboration is - acceptable: - - @smallexample - @group - Spec of Unit_1 - Spec of Unit_2 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - or - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_2 - Body of Unit_1 - @end group - @end smallexample - - @noindent - If you carefully analyze the flow here, you will see that you cannot tell - at compile time the answer to this question. - If @code{expression_1} is not equal to 1, - and @code{expression_2} is not equal to 2, - then either order is acceptable, because neither of the function calls is - executed. If both tests evaluate to true, then neither order is acceptable - and in fact there is no correct order. - - If one of the two expressions is true, and the other is false, then one - of the above orders is correct, and the other is incorrect. For example, - if @code{expression_1} = 1 and @code{expression_2} /= 2, - then the call to @code{Func_2} - will occur, but not the call to @code{Func_1.} - This means that it is essential - to elaborate the body of @code{Unit_1} before - the body of @code{Unit_2}, so the first - order of elaboration is correct and the second is wrong. - - By making @code{expression_1} and @code{expression_2} - depend on input data, or perhaps - the time of day, we can make it impossible for the compiler or binder - to figure out which of these expressions will be true, and hence it - is impossible to guarantee a safe order of elaboration at run time. - - @node Checking the Elaboration Order in Ada 95 - @section Checking the Elaboration Order in Ada 95 - - @noindent - In some languages that involve the same kind of elaboration problems, - e.g. Java and C++, the programmer is expected to worry about these - ordering problems himself, and it is common to - write a program in which an incorrect elaboration order gives - surprising results, because it references variables before they - are initialized. - Ada 95 is designed to be a safe language, and a programmer-beware approach is - clearly not sufficient. Consequently, the language provides three lines - of defense: - - @table @asis - @item Standard rules - Some standard rules restrict the possible choice of elaboration - order. In particular, if you @code{with} a unit, then its spec is always - elaborated before the unit doing the @code{with}. Similarly, a parent - spec is always elaborated before the child spec, and finally - a spec is always elaborated before its corresponding body. - - @item Dynamic elaboration checks - @cindex Elaboration checks - @cindex Checks, elaboration - Dynamic checks are made at run time, so that if some entity is accessed - before it is elaborated (typically by means of a subprogram call) - then the exception (@code{Program_Error}) is raised. - - @item Elaboration control - Facilities are provided for the programmer to specify the desired order - of elaboration. - @end table - - Let's look at these facilities in more detail. First, the rules for - dynamic checking. One possible rule would be simply to say that the - exception is raised if you access a variable which has not yet been - elaborated. The trouble with this approach is that it could require - expensive checks on every variable reference. Instead Ada 95 has two - rules which are a little more restrictive, but easier to check, and - easier to state: - - @table @asis - @item Restrictions on calls - A subprogram can only be called at elaboration time if its body - has been elaborated. The rules for elaboration given above guarantee - that the spec of the subprogram has been elaborated before the - call, but not the body. If this rule is violated, then the - exception @code{Program_Error} is raised. - - @item Restrictions on instantiations - A generic unit can only be instantiated if the body of the generic - unit has been elaborated. Again, the rules for elaboration given above - guarantee that the spec of the generic unit has been elaborated - before the instantiation, but not the body. If this rule is - violated, then the exception @code{Program_Error} is raised. - @end table - - @noindent - The idea is that if the body has been elaborated, then any variables - it references must have been elaborated; by checking for the body being - elaborated we guarantee that none of its references causes any - trouble. As we noted above, this is a little too restrictive, because a - subprogram that has no non-local references in its body may in fact be safe - to call. However, it really would be unsafe to rely on this, because - it would mean that the caller was aware of details of the implementation - in the body. This goes against the basic tenets of Ada. - - A plausible implementation can be described as follows. - A Boolean variable is associated with each subprogram - and each generic unit. This variable is initialized to False, and is set to - True at the point body is elaborated. Every call or instantiation checks the - variable, and raises @code{Program_Error} if the variable is False. - - Note that one might think that it would be good enough to have one Boolean - variable for each package, but that would not deal with cases of trying - to call a body in the same package as the call - that has not been elaborated yet. - Of course a compiler may be able to do enough analysis to optimize away - some of the Boolean variables as unnecessary, and @code{GNAT} indeed - does such optimizations, but still the easiest conceptual model is to - think of there being one variable per subprogram. - - @node Controlling the Elaboration Order in Ada 95 - @section Controlling the Elaboration Order in Ada 95 - - @noindent - In the previous section we discussed the rules in Ada 95 which ensure - that @code{Program_Error} is raised if an incorrect elaboration order is - chosen. This prevents erroneous executions, but we need mechanisms to - specify a correct execution and avoid the exception altogether. - To achieve this, Ada 95 provides a number of features for controlling - the order of elaboration. We discuss these features in this section. - - First, there are several ways of indicating to the compiler that a given - unit has no elaboration problems: - - @table @asis - @item packages that do not require a body - In Ada 95, a library package that does not require a body does not permit - a body. This means that if we have a such a package, as in: - - @smallexample - @group - @cartouche - @b{package} Definitions @b{is} - @b{generic} - @b{type} m @b{is new} integer; - @b{package} Subp @b{is} - @b{type} a @b{is array} (1 .. 10) @b{of} m; - @b{type} b @b{is array} (1 .. 20) @b{of} m; - @b{end} Subp; - @b{end} Definitions; - @end cartouche - @end group - @end smallexample - - @noindent - A package that @code{with}'s @code{Definitions} may safely instantiate - @code{Definitions.Subp} because the compiler can determine that there - definitely is no package body to worry about in this case - - @item pragma Pure - @cindex pragma Pure - @findex Pure - Places sufficient restrictions on a unit to guarantee that - no call to any subprogram in the unit can result in an - elaboration problem. This means that the compiler does not need - to worry about the point of elaboration of such units, and in - particular, does not need to check any calls to any subprograms - in this unit. - - @item pragma Preelaborate - @findex Preelaborate - @cindex pragma Preelaborate - This pragma places slightly less stringent restrictions on a unit than - does pragma Pure, - but these restrictions are still sufficient to ensure that there - are no elaboration problems with any calls to the unit. - - @item pragma Elaborate_Body - @findex Elaborate_Body - @cindex pragma Elaborate_Body - This pragma requires that the body of a unit be elaborated immediately - after its spec. Suppose a unit @code{A} has such a pragma, - and unit @code{B} does - a @code{with} of unit @code{A}. Recall that the standard rules require - the spec of unit @code{A} - to be elaborated before the @code{with}'ing unit; given the pragma in - @code{A}, we also know that the body of @code{A} - will be elaborated before @code{B}, so - that calls to @code{A} are safe and do not need a check. - @end table - - @noindent - Note that, - unlike pragma @code{Pure} and pragma @code{Preelaborate}, - the use of - @code{Elaborate_Body} does not guarantee that the program is - free of elaboration problems, because it may not be possible - to satisfy the requested elaboration order. - Let's go back to the example with @code{Unit_1} and @code{Unit_2}. - If a programmer - marks @code{Unit_1} as @code{Elaborate_Body}, - and not @code{Unit_2,} then the order of - elaboration will be: - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - Now that means that the call to @code{Func_1} in @code{Unit_2} - need not be checked, - it must be safe. But the call to @code{Func_2} in - @code{Unit_1} may still fail if - @code{Expression_1} is equal to 1, - and the programmer must still take - responsibility for this not being the case. - - If all units carry a pragma @code{Elaborate_Body}, then all problems are - eliminated, except for calls entirely within a body, which are - in any case fully under programmer control. However, using the pragma - everywhere is not always possible. - In particular, for our @code{Unit_1}/@code{Unit_2} example, if - we marked both of them as having pragma @code{Elaborate_Body}, then - clearly there would be no possible elaboration order. - - The above pragmas allow a server to guarantee safe use by clients, and - clearly this is the preferable approach. Consequently a good rule in - Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible, - and if this is not possible, - mark them as @code{Elaborate_Body} if possible. - As we have seen, there are situations where neither of these - three pragmas can be used. - So we also provide methods for clients to control the - order of elaboration of the servers on which they depend: - - @table @asis - @item pragma Elaborate (unit) - @findex Elaborate - @cindex pragma Elaborate - This pragma is placed in the context clause, after a @code{with} clause, - and it requires that the body of the named unit be elaborated before - the unit in which the pragma occurs. The idea is to use this pragma - if the current unit calls at elaboration time, directly or indirectly, - some subprogram in the named unit. - - @item pragma Elaborate_All (unit) - @findex Elaborate_All - @cindex pragma Elaborate_All - This is a stronger version of the Elaborate pragma. Consider the - following example: - - @smallexample - Unit A @code{with}'s unit B and calls B.Func in elab code - Unit B @code{with}'s unit C, and B.Func calls C.Func - @end smallexample - - @noindent - Now if we put a pragma @code{Elaborate (B)} - in unit @code{A}, this ensures that the - body of @code{B} is elaborated before the call, but not the - body of @code{C}, so - the call to @code{C.Func} could still cause @code{Program_Error} to - be raised. - - The effect of a pragma @code{Elaborate_All} is stronger, it requires - not only that the body of the named unit be elaborated before the - unit doing the @code{with}, but also the bodies of all units that the - named unit uses, following @code{with} links transitively. For example, - if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, - then it requires - not only that the body of @code{B} be elaborated before @code{A}, - but also the - body of @code{C}, because @code{B} @code{with}'s @code{C}. - @end table - - @noindent - We are now in a position to give a usage rule in Ada 95 for avoiding - elaboration problems, at least if dynamic dispatching and access to - subprogram values are not used. We will handle these cases separately - later. - - The rule is simple. If a unit has elaboration code that can directly or - indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate - a generic unit in a @code{with}'ed unit, - then if the @code{with}'ed unit does not have - pragma @code{Pure} or @code{Preelaborate}, then the client should have - a pragma @code{Elaborate_All} - for the @code{with}'ed unit. By following this rule a client is - assured that calls can be made without risk of an exception. - If this rule is not followed, then a program may be in one of four - states: - - @table @asis - @item No order exists - No order of elaboration exists which follows the rules, taking into - account any @code{Elaborate}, @code{Elaborate_All}, - or @code{Elaborate_Body} pragmas. In - this case, an Ada 95 compiler must diagnose the situation at bind - time, and refuse to build an executable program. - - @item One or more orders exist, all incorrect - One or more acceptable elaboration orders exists, and all of them - generate an elaboration order problem. In this case, the binder - can build an executable program, but @code{Program_Error} will be raised - when the program is run. - - @item Several orders exist, some right, some incorrect - One or more acceptable elaboration orders exists, and some of them - work, and some do not. The programmer has not controlled - the order of elaboration, so the binder may or may not pick one of - the correct orders, and the program may or may not raise an - exception when it is run. This is the worst case, because it means - that the program may fail when moved to another compiler, or even - another version of the same compiler. - - @item One or more orders exists, all correct - One ore more acceptable elaboration orders exist, and all of them - work. In this case the program runs successfully. This state of - affairs can be guaranteed by following the rule we gave above, but - may be true even if the rule is not followed. - @end table - - @noindent - Note that one additional advantage of following our Elaborate_All rule - is that the program continues to stay in the ideal (all orders OK) state - even if maintenance - changes some bodies of some subprograms. Conversely, if a program that does - not follow this rule happens to be safe at some point, this state of affairs - may deteriorate silently as a result of maintenance changes. - - You may have noticed that the above discussion did not mention - the use of @code{Elaborate_Body}. This was a deliberate omission. If you - @code{with} an @code{Elaborate_Body} unit, it still may be the case that - code in the body makes calls to some other unit, so it is still necessary - to use @code{Elaborate_All} on such units. - - @node Controlling Elaboration in GNAT - Internal Calls - @section Controlling Elaboration in GNAT - Internal Calls - - @noindent - In the case of internal calls, i.e. calls within a single package, the - programmer has full control over the order of elaboration, and it is up - to the programmer to elaborate declarations in an appropriate order. For - example writing: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - Q : Float := One; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - @end cartouche - @end group - @end smallexample - - @noindent - will obviously raise @code{Program_Error} at run time, because function - One will be called before its body is elaborated. In this case GNAT will - generate a warning that the call will raise @code{Program_Error}: - - @smallexample - @group - @cartouche - 1. procedure y is - 2. function One return Float; - 3. - 4. Q : Float := One; - | - >>> warning: cannot call "One" before body is elaborated - >>> warning: Program_Error will be raised at run time - - 5. - 6. function One return Float is - 7. begin - 8. return 1.0; - 9. end One; - 10. - 11. begin - 12. null; - 13. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that in this particular case, it is likely that the call is safe, because - the function @code{One} does not access any global variables. - Nevertheless in Ada 95, we do not want the validity of the check to depend on - the contents of the body (think about the separate compilation case), so this - is still wrong, as we discussed in the previous sections. - - The error is easily corrected by rearranging the declarations so that the - body of One appears before the declaration containing the call - (note that in Ada 95, - declarations can appear in any order, so there is no restriction that - would prevent this reordering, and if we write: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - - Q : Float := One; - @end cartouche - @end group - @end smallexample - - @noindent - then all is well, no warning is generated, and no - @code{Program_Error} exception - will be raised. - Things are more complicated when a chain of subprograms is executed: - - @smallexample - @group - @cartouche - @b{function} A @b{return} Integer; - @b{function} B @b{return} Integer; - @b{function} C @b{return} Integer; - - @b{function} B @b{return} Integer @b{is begin return} A; @b{end}; - @b{function} C @b{return} Integer @b{is begin return} B; @b{end}; - - X : Integer := C; - - @b{function} A @b{return} Integer @b{is begin return} 1; @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the call to @code{C} - at elaboration time in the declaration of @code{X} is correct, because - the body of @code{C} is already elaborated, - and the call to @code{B} within the body of - @code{C} is correct, but the call - to @code{A} within the body of @code{B} is incorrect, because the body - of @code{A} has not been elaborated, so @code{Program_Error} - will be raised on the call to @code{A}. - In this case GNAT will generate a - warning that @code{Program_Error} may be - raised at the point of the call. Let's look at the warning: - - @smallexample - @group - @cartouche - 1. procedure x is - 2. function A return Integer; - 3. function B return Integer; - 4. function C return Integer; - 5. - 6. function B return Integer is begin return A; end; - | - >>> warning: call to "A" before body is elaborated may - raise Program_Error - >>> warning: "B" called at line 7 - >>> warning: "C" called at line 9 - - 7. function C return Integer is begin return B; end; - 8. - 9. X : Integer := C; - 10. - 11. function A return Integer is begin return 1; end; - 12. - 13. begin - 14. null; - 15. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that the message here says "may raise", instead of the direct case, - where the message says "will be raised". That's because whether - @code{A} is - actually called depends in general on run-time flow of control. - For example, if the body of @code{B} said - - @smallexample - @group - @cartouche - @b{function} B @b{return} Integer @b{is} - @b{begin} - @b{if} some-condition-depending-on-input-data @b{then} - @b{return} A; - @b{else} - @b{return} 1; - @b{end if}; - @b{end} B; - @end cartouche - @end group - @end smallexample - - @noindent - then we could not know until run time whether the incorrect call to A would - actually occur, so @code{Program_Error} might - or might not be raised. It is possible for a compiler to - do a better job of analyzing bodies, to - determine whether or not @code{Program_Error} - might be raised, but it certainly - couldn't do a perfect job (that would require solving the halting problem - and is provably impossible), and because this is a warning anyway, it does - not seem worth the effort to do the analysis. Cases in which it - would be relevant are rare. - - In practice, warnings of either of the forms given - above will usually correspond to - real errors, and should be examined carefully and eliminated. - In the rare case where a warning is bogus, it can be suppressed by any of - the following methods: - - @itemize @bullet - @item - Compile with the @option{-gnatws} switch set - - @item - Suppress @code{Elaboration_Checks} for the called subprogram - - @item - Use pragma @code{Warnings_Off} to turn warnings off for the call - @end itemize - - @noindent - For the internal elaboration check case, - GNAT by default generates the - necessary run-time checks to ensure - that @code{Program_Error} is raised if any - call fails an elaboration check. Of course this can only happen if a - warning has been issued as described above. The use of pragma - @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress - some of these checks, meaning that it may be possible (but is not - guaranteed) for a program to be able to call a subprogram whose body - is not yet elaborated, without raising a @code{Program_Error} exception. - - @node Controlling Elaboration in GNAT - External Calls - @section Controlling Elaboration in GNAT - External Calls - - @noindent - The previous section discussed the case in which the execution of a - particular thread of elaboration code occurred entirely within a - single unit. This is the easy case to handle, because a programmer - has direct and total control over the order of elaboration, and - furthermore, checks need only be generated in cases which are rare - and which the compiler can easily detect. - The situation is more complex when separate compilation is taken into account. - Consider the following: - - @smallexample - @cartouche - @group - @b{package} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float; - @b{end} Math; - - @b{package body} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float @b{is} - @b{begin} - ... - @b{end} Sqrt; - @b{end} Math; - @end group - @group - @b{with} Math; - @b{package} Stuff @b{is} - X : Float := Math.Sqrt (0.5); - @b{end} Stuff; - - @b{with} Stuff; - @b{procedure} Main @b{is} - @b{begin} - ... - @b{end} Main; - @end group - @end cartouche - @end smallexample - - @noindent - where @code{Main} is the main program. When this program is executed, the - elaboration code must first be executed, and one of the jobs of the - binder is to determine the order in which the units of a program are - to be elaborated. In this case we have four units: the spec and body - of @code{Math}, - the spec of @code{Stuff} and the body of @code{Main}). - In what order should the four separate sections of elaboration code - be executed? - - There are some restrictions in the order of elaboration that the binder - can choose. In particular, if unit U has a @code{with} - for a package @code{X}, then you - are assured that the spec of @code{X} - is elaborated before U , but you are - not assured that the body of @code{X} - is elaborated before U. - This means that in the above case, the binder is allowed to choose the - order: - - @smallexample - spec of Math - spec of Stuff - body of Math - body of Main - @end smallexample - - @noindent - but that's not good, because now the call to @code{Math.Sqrt} - that happens during - the elaboration of the @code{Stuff} - spec happens before the body of @code{Math.Sqrt} is - elaborated, and hence causes @code{Program_Error} exception to be raised. - At first glance, one might say that the binder is misbehaving, because - obviously you want to elaborate the body of something you @code{with} - first, but - that is not a general rule that can be followed in all cases. Consider - - @smallexample - @group - @cartouche - @b{package} X @b{is} ... - - @b{package} Y @b{is} ... - - @b{with} X; - @b{package body} Y @b{is} ... - - @b{with} Y; - @b{package body} X @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - This is a common arrangement, and, apart from the order of elaboration - problems that might arise in connection with elaboration code, this works fine. - A rule that says that you must first elaborate the body of anything you - @code{with} cannot work in this case: - the body of @code{X} @code{with}'s @code{Y}, - which means you would have to - elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, - which means - you have to elaborate the body of @code{X} first, but ... and we have a - loop that cannot be broken. - - It is true that the binder can in many cases guess an order of elaboration - that is unlikely to cause a @code{Program_Error} - exception to be raised, and it tries to do so (in the - above example of @code{Math/Stuff/Spec}, the GNAT binder will - by default - elaborate the body of @code{Math} right after its spec, so all will be well). - - However, a program that blindly relies on the binder to be helpful can - get into trouble, as we discussed in the previous sections, so - GNAT - provides a number of facilities for assisting the programmer in - developing programs that are robust with respect to elaboration order. - - @node Default Behavior in GNAT - Ensuring Safety - @section Default Behavior in GNAT - Ensuring Safety - - @noindent - The default behavior in GNAT ensures elaboration safety. In its - default mode GNAT implements the - rule we previously described as the right approach. Let's restate it: - - @itemize - @item - @emph{If a unit has elaboration code that can directly or indirectly make a - call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit - in a @code{with}'ed unit, then if the @code{with}'ed unit - does not have pragma @code{Pure} or - @code{Preelaborate}, then the client should have an - @code{Elaborate_All} for the @code{with}'ed unit.} - @end itemize - - @noindent - By following this rule a client - is assured that calls and instantiations can be made without risk of an exception. - - In this mode GNAT traces all calls that are potentially made from - elaboration code, and puts in any missing implicit @code{Elaborate_All} - pragmas. - The advantage of this approach is that no elaboration problems - are possible if the binder can find an elaboration order that is - consistent with these implicit @code{Elaborate_All} pragmas. The - disadvantage of this approach is that no such order may exist. - - If the binder does not generate any diagnostics, then it means that it - has found an elaboration order that is guaranteed to be safe. However, - the binder may still be relying on implicitly generated - @code{Elaborate_All} pragmas so portability to other compilers than - GNAT is not guaranteed. - - If it is important to guarantee portability, then the compilations should - use the - @option{-gnatwl} - (warn on elaboration problems) switch. This will cause warning messages - to be generated indicating the missing @code{Elaborate_All} pragmas. - Consider the following source program: - - @smallexample - @group - @cartouche - @b{with} k; - @b{package} j @b{is} - m : integer := k.r; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - where it is clear that there - should be a pragma @code{Elaborate_All} - for unit @code{k}. An implicit pragma will be generated, and it is - likely that the binder will be able to honor it. However, - it is safer to include the pragma explicitly in the source. If this - unit is compiled with the - @option{-gnatwl} - switch, then the compiler outputs a warning: - - @smallexample - @group - @cartouche - 1. with k; - 2. package j is - 3. m : integer := k.r; - | - >>> warning: call to "r" may raise Program_Error - >>> warning: missing pragma Elaborate_All for "k" - - 4. end; - @end cartouche - @end group - @end smallexample - - @noindent - and these warnings can be used as a guide for supplying manually - the missing pragmas. - - This default mode is more restrictive than the Ada Reference - Manual, and it is possible to construct programs which will compile - using the dynamic model described there, but will run into a - circularity using the safer static model we have described. - - Of course any Ada compiler must be able to operate in a mode - consistent with the requirements of the Ada Reference Manual, - and in particular must have the capability of implementing the - standard dynamic model of elaboration with run-time checks. - - In GNAT, this standard mode can be achieved either by the use of - the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake}) - command, or by the use of the configuration pragma: - - @smallexample - pragma Elaboration_Checks (RM); - @end smallexample - - @noindent - Either approach will cause the unit affected to be compiled using the - standard dynamic run-time elaboration checks described in the Ada - Reference Manual. The static model is generally preferable, since it - is clearly safer to rely on compile and link time checks rather than - run-time checks. However, in the case of legacy code, it may be - difficult to meet the requirements of the static model. This - issue is further discussed in - @ref{What to Do If the Default Elaboration Behavior Fails}. - - Note that the static model provides a strict subset of the allowed - behavior and programs of the Ada Reference Manual, so if you do - adhere to the static model and no circularities exist, - then you are assured that your program will - work using the dynamic model. - - @node Elaboration Issues for Library Tasks - @section Elaboration Issues for Library Tasks - @cindex Library tasks, elaboration issues - @cindex Elaboration of library tasks - - @noindent - In this section we examine special elaboration issues that arise for - programs that declare library level tasks. - - Generally the model of execution of an Ada program is that all units are - elaborated, and then execution of the program starts. However, the - declaration of library tasks definitely does not fit this model. The - reason for this is that library tasks start as soon as they are declared - (more precisely, as soon as the statement part of the enclosing package - body is reached), that is to say before elaboration - of the program is complete. This means that if such a task calls a - subprogram, or an entry in another task, the callee may or may not be - elaborated yet, and in the standard - Reference Manual model of dynamic elaboration checks, you can even - get timing dependent Program_Error exceptions, since there can be - a race between the elaboration code and the task code. - - The static model of elaboration in GNAT seeks to avoid all such - dynamic behavior, by being conservative, and the conservative - approach in this particular case is to assume that all the code - in a task body is potentially executed at elaboration time if - a task is declared at the library level. - - This can definitely result in unexpected circularities. Consider - the following example - - @smallexample - package Decls is - task Lib_Task is - entry Start; - end Lib_Task; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - procedure Main is - begin - Decls.Lib_Task.Start; - end; - @end smallexample - - @noindent - If the above example is compiled in the default static elaboration - mode, then a circularity occurs. The circularity comes from the call - @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since - this call occurs in elaboration code, we need an implicit pragma - @code{Elaborate_All} for @code{Utils}. This means that not only must - the spec and body of @code{Utils} be elaborated before the body - of @code{Decls}, but also the spec and body of any unit that is - @code{with'ed} by the body of @code{Utils} must also be elaborated before - the body of @code{Decls}. This is the transitive implication of - pragma @code{Elaborate_All} and it makes sense, because in general - the body of @code{Put_Val} might have a call to something in a - @code{with'ed} unit. - - In this case, the body of Utils (actually its spec) @code{with's} - @code{Decls}. Unfortunately this means that the body of @code{Decls} - must be elaborated before itself, in case there is a call from the - body of @code{Utils}. - - Here is the exact chain of events we are worrying about: - - @enumerate - @item - In the body of @code{Decls} a call is made from within the body of a library - task to a subprogram in the package @code{Utils}. Since this call may - occur at elaboration time (given that the task is activated at elaboration - time), we have to assume the worst, i.e. that the - call does happen at elaboration time. - - @item - This means that the body and spec of @code{Util} must be elaborated before - the body of @code{Decls} so that this call does not cause an access before - elaboration. - - @item - Within the body of @code{Util}, specifically within the body of - @code{Util.Put_Val} there may be calls to any unit @code{with}'ed - by this package. - - @item - One such @code{with}'ed package is package @code{Decls}, so there - might be a call to a subprogram in @code{Decls} in @code{Put_Val}. - In fact there is such a call in this example, but we would have to - assume that there was such a call even if it were not there, since - we are not supposed to write the body of @code{Decls} knowing what - is in the body of @code{Utils}; certainly in the case of the - static elaboration model, the compiler does not know what is in - other bodies and must assume the worst. - - @item - This means that the spec and body of @code{Decls} must also be - elaborated before we elaborate the unit containing the call, but - that unit is @code{Decls}! This means that the body of @code{Decls} - must be elaborated before itself, and that's a circularity. - @end enumerate - - @noindent - Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in - the body of @code{Decls} you will get a true Ada Reference Manual - circularity that makes the program illegal. - - In practice, we have found that problems with the static model of - elaboration in existing code often arise from library tasks, so - we must address this particular situation. - - Note that if we compile and run the program above, using the dynamic model of - elaboration (that is to say use the @option{-gnatE} switch), - then it compiles, binds, - links, and runs, printing the expected result of 2. Therefore in some sense - the circularity here is only apparent, and we need to capture - the properties of this program that distinguish it from other library-level - tasks that have real elaboration problems. - - We have four possible answers to this question: - - @itemize @bullet - - @item - Use the dynamic model of elaboration. - - If we use the @option{-gnatE} switch, then as noted above, the program works. - Why is this? If we examine the task body, it is apparent that the task cannot - proceed past the - @code{accept} statement until after elaboration has been completed, because - the corresponding entry call comes from the main program, not earlier. - This is why the dynamic model works here. But that's really giving - up on a precise analysis, and we prefer to take this approach only if we cannot - solve the - problem in any other manner. So let us examine two ways to reorganize - the program to avoid the potential elaboration problem. - - @item - Split library tasks into separate packages. - - Write separate packages, so that library tasks are isolated from - other declarations as much as possible. Let us look at a variation on - the above program. - - @smallexample - package Decls1 is - task Lib_Task is - entry Start; - end Lib_Task; - end Decls1; - - with Utils; - package body Decls1 is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - end Decls1; - - package Decls2 is - type My_Int is new Integer; - function Ident (M : My_Int) return My_Int; - end Decls2; - - with Utils; - package body Decls2 is - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls2; - - with Decls2; - package Utils is - procedure Put_Val (Arg : Decls2.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls2.My_Int) is - begin - Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls1; - procedure Main is - begin - Decls1.Lib_Task.Start; - end; - @end smallexample - - @noindent - All we have done is to split @code{Decls} into two packages, one - containing the library task, and one containing everything else. Now - there is no cycle, and the program compiles, binds, links and executes - using the default static model of elaboration. - - @item - Declare separate task types. - - A significant part of the problem arises because of the use of the - single task declaration form. This means that the elaboration of - the task type, and the elaboration of the task itself (i.e. the - creation of the task) happen at the same time. A good rule - of style in Ada 95 is to always create explicit task types. By - following the additional step of placing task objects in separate - packages from the task type declaration, many elaboration problems - are avoided. Here is another modified example of the example program: - - @smallexample - package Decls is - task type Lib_Task_Type is - entry Start; - end Lib_Task_Type; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task_Type is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task_Type; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - package Declst is - Lib_Task : Decls.Lib_Task_Type; - end Declst; - - with Declst; - procedure Main is - begin - Declst.Lib_Task.Start; - end; - @end smallexample - - @noindent - What we have done here is to replace the @code{task} declaration in - package @code{Decls} with a @code{task type} declaration. Then we - introduce a separate package @code{Declst} to contain the actual - task object. This separates the elaboration issues for - the @code{task type} - declaration, which causes no trouble, from the elaboration issues - of the task object, which is also unproblematic, since it is now independent - of the elaboration of @code{Utils}. - This separation of concerns also corresponds to - a generally sound engineering principle of separating declarations - from instances. This version of the program also compiles, binds, links, - and executes, generating the expected output. - - @item - Use No_Entry_Calls_In_Elaboration_Code restriction. - @cindex No_Entry_Calls_In_Elaboration_Code - - The previous two approaches described how a program can be restructured - to avoid the special problems caused by library task bodies. in practice, - however, such restructuring may be difficult to apply to existing legacy code, - so we must consider solutions that do not require massive rewriting. - - Let us consider more carefully why our original sample program works - under the dynamic model of elaboration. The reason is that the code - in the task body blocks immediately on the @code{accept} - statement. Now of course there is nothing to prohibit elaboration - code from making entry calls (for example from another library level task), - so we cannot tell in isolation that - the task will not execute the accept statement during elaboration. - - However, in practice it is very unusual to see elaboration code - make any entry calls, and the pattern of tasks starting - at elaboration time and then immediately blocking on @code{accept} or - @code{select} statements is very common. What this means is that - the compiler is being too pessimistic when it analyzes the - whole package body as though it might be executed at elaboration - time. - - If we know that the elaboration code contains no entry calls, (a very safe - assumption most of the time, that could almost be made the default - behavior), then we can compile all units of the program under control - of the following configuration pragma: - - @smallexample - pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); - @end smallexample - - @noindent - This pragma can be placed in the @file{gnat.adc} file in the usual - manner. If we take our original unmodified program and compile it - in the presence of a @file{gnat.adc} containing the above pragma, - then once again, we can compile, bind, link, and execute, obtaining - the expected result. In the presence of this pragma, the compiler does - not trace calls in a task body, that appear after the first @code{accept} - or @code{select} statement, and therefore does not report a potential - circularity in the original program. - - The compiler will check to the extent it can that the above - restriction is not violated, but it is not always possible to do a - complete check at compile time, so it is important to use this - pragma only if the stated restriction is in fact met, that is to say - no task receives an entry call before elaboration of all units is completed. - - @end itemize - - @node Mixing Elaboration Models - @section Mixing Elaboration Models - @noindent - So far, we have assumed that the entire program is either compiled - using the dynamic model or static model, ensuring consistency. It - is possible to mix the two models, but rules have to be followed - if this mixing is done to ensure that elaboration checks are not - omitted. - - The basic rule is that @emph{a unit compiled with the static model cannot - be @code{with'ed} by a unit compiled with the dynamic model}. The - reason for this is that in the static model, a unit assumes that - its clients guarantee to use (the equivalent of) pragma - @code{Elaborate_All} so that no elaboration checks are required - in inner subprograms, and this assumption is violated if the - client is compiled with dynamic checks. - - The precise rule is as follows. A unit that is compiled with dynamic - checks can only @code{with} a unit that meets at least one of the - following criteria: - - @itemize @bullet - - @item - The @code{with'ed} unit is itself compiled with dynamic elaboration - checks (that is with the @option{-gnatE} switch. - - @item - The @code{with'ed} unit is an internal GNAT implementation unit from - the System, Interfaces, Ada, or GNAT hierarchies. - - @item - The @code{with'ed} unit has pragma Preelaborate or pragma Pure. - - @item - The @code{with'ing} unit (that is the client) has an explicit pragma - @code{Elaborate_All} for the @code{with'ed} unit. - - @end itemize - - @noindent - If this rule is violated, that is if a unit with dynamic elaboration - checks @code{with's} a unit that does not meet one of the above four - criteria, then the binder (@code{gnatbind}) will issue a warning - similar to that in the following example: - - @smallexample - warning: "x.ads" has dynamic elaboration checks and with's - warning: "y.ads" which has static elaboration checks - @end smallexample - - @noindent - These warnings indicate that the rule has been violated, and that as a result - elaboration checks may be missed in the resulting executable file. - This warning may be suppressed using the @code{-ws} binder switch - in the usual manner. - - One useful application of this mixing rule is in the case of a subsystem - which does not itself @code{with} units from the remainder of the - application. In this case, the entire subsystem can be compiled with - dynamic checks to resolve a circularity in the subsystem, while - allowing the main application that uses this subsystem to be compiled - using the more reliable default static model. - - @node What to Do If the Default Elaboration Behavior Fails - @section What to Do If the Default Elaboration Behavior Fails - - @noindent - If the binder cannot find an acceptable order, it outputs detailed - diagnostics. For example: - @smallexample - @group - @iftex - @leftskip=0cm - @end iftex - error: elaboration circularity detected - info: "proc (body)" must be elaborated before "pack (body)" - info: reason: Elaborate_All probably needed in unit "pack (body)" - info: recompile "pack (body)" with -gnatwl - info: for full details - info: "proc (body)" - info: is needed by its spec: - info: "proc (spec)" - info: which is withed by: - info: "pack (body)" - info: "pack (body)" must be elaborated before "proc (body)" - info: reason: pragma Elaborate in unit "proc (body)" - @end group - - @end smallexample - - @noindent - In this case we have a cycle that the binder cannot break. On the one - hand, there is an explicit pragma Elaborate in @code{proc} for - @code{pack}. This means that the body of @code{pack} must be elaborated - before the body of @code{proc}. On the other hand, there is elaboration - code in @code{pack} that calls a subprogram in @code{proc}. This means - that for maximum safety, there should really be a pragma - Elaborate_All in @code{pack} for @code{proc} which would require that - the body of @code{proc} be elaborated before the body of - @code{pack}. Clearly both requirements cannot be satisfied. - Faced with a circularity of this kind, you have three different options. - - @table @asis - @item Fix the program - The most desirable option from the point of view of long-term maintenance - is to rearrange the program so that the elaboration problems are avoided. - One useful technique is to place the elaboration code into separate - child packages. Another is to move some of the initialization code to - explicitly called subprograms, where the program controls the order - of initialization explicitly. Although this is the most desirable option, - it may be impractical and involve too much modification, especially in - the case of complex legacy code. - - @item Perform dynamic checks - If the compilations are done using the - @option{-gnatE} - (dynamic elaboration check) switch, then GNAT behaves in - a quite different manner. Dynamic checks are generated for all calls - that could possibly result in raising an exception. With this switch, - the compiler does not generate implicit @code{Elaborate_All} pragmas. - The behavior then is exactly as specified in the Ada 95 Reference Manual. - The binder will generate an executable program that may or may not - raise @code{Program_Error}, and then it is the programmer's job to ensure - that it does not raise an exception. Note that it is important to - compile all units with the switch, it cannot be used selectively. - - @item Suppress checks - The drawback of dynamic checks is that they generate a - significant overhead at run time, both in space and time. If you - are absolutely sure that your program cannot raise any elaboration - exceptions, and you still want to use the dynamic elaboration model, - then you can use the configuration pragma - @code{Suppress (Elaboration_Checks)} to suppress all such checks. For - example this pragma could be placed in the @file{gnat.adc} file. - - @item Suppress checks selectively - When you know that certain calls in elaboration code cannot possibly - lead to an elaboration error, and the binder nevertheless generates warnings - on those calls and inserts Elaborate_All pragmas that lead to elaboration - circularities, it is possible to remove those warnings locally and obtain - a program that will bind. Clearly this can be unsafe, and it is the - responsibility of the programmer to make sure that the resulting program has - no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can - be used with different granularity to suppress warnings and break - elaboration circularities: - - @itemize @bullet - @item - Place the pragma that names the called subprogram in the declarative part - that contains the call. - - @item - Place the pragma in the declarative part, without naming an entity. This - disables warnings on all calls in the corresponding declarative region. - - @item - Place the pragma in the package spec that declares the called subprogram, - and name the subprogram. This disables warnings on all elaboration calls to - that subprogram. - - @item - Place the pragma in the package spec that declares the called subprogram, - without naming any entity. This disables warnings on all elaboration calls to - all subprograms declared in this spec. - @end itemize - - @noindent - These four cases are listed in order of decreasing safety, and therefore - require increasing programmer care in their application. Consider the - following program: - @smallexample - - package Pack1 is - function F1 return Integer; - X1 : Integer; - end Pack1; - - package Pack2 is - function F2 return Integer; - function Pure (x : integer) return integer; - -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) - -- pragma Suppress (Elaboration_Check); -- (4) - end Pack2; - - with Pack2; - package body Pack1 is - function F1 return Integer is - begin - return 100; - end F1; - Val : integer := Pack2.Pure (11); -- Elab. call (1) - begin - declare - -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) - -- pragma Suppress(Elaboration_Check); -- (2) - begin - X1 := Pack2.F2 + 1; -- Elab. call (2) - end; - end Pack1; - - with Pack1; - package body Pack2 is - function F2 return Integer is - begin - return Pack1.F1; - end F2; - function Pure (x : integer) return integer is - begin - return x ** 3 - 3 * x; - end; - end Pack2; - - with Pack1, Ada.Text_IO; - procedure Proc3 is - begin - Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 - end Proc3; - @end smallexample - In the absence of any pragmas, an attempt to bind this program produces - the following diagnostics: - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - error: elaboration circularity detected - info: "pack1 (body)" must be elaborated before "pack1 (body)" - info: reason: Elaborate_All probably needed in unit "pack1 (body)" - info: recompile "pack1 (body)" with -gnatwl for full details - info: "pack1 (body)" - info: must be elaborated along with its spec: - info: "pack1 (spec)" - info: which is withed by: - info: "pack2 (body)" - info: which must be elaborated along with its spec: - info: "pack2 (spec)" - info: which is withed by: - info: "pack1 (body)" - @end group - @end smallexample - The sources of the circularity are the two calls to @code{Pack2.Pure} and - @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to - F2 is safe, even though F2 calls F1, because the call appears after the - elaboration of the body of F1. Therefore the pragma (1) is safe, and will - remove the warning on the call. It is also possible to use pragma (2) - because there are no other potentially unsafe calls in the block. - - @noindent - The call to @code{Pure} is safe because this function does not depend on the - state of @code{Pack2}. Therefore any call to this function is safe, and it - is correct to place pragma (3) in the corresponding package spec. - - @noindent - Finally, we could place pragma (4) in the spec of @code{Pack2} to disable - warnings on all calls to functions declared therein. Note that this is not - necessarily safe, and requires more detailed examination of the subprogram - bodies involved. In particular, a call to @code{F2} requires that @code{F1} - be already elaborated. - @end table - - @noindent - It is hard to generalize on which of these four approaches should be - taken. Obviously if it is possible to fix the program so that the default - treatment works, this is preferable, but this may not always be practical. - It is certainly simple enough to use - @option{-gnatE} - but the danger in this case is that, even if the GNAT binder - finds a correct elaboration order, it may not always do so, - and certainly a binder from another Ada compiler might not. A - combination of testing and analysis (for which the warnings generated - with the - @option{-gnatwl} - switch can be useful) must be used to ensure that the program is free - of errors. One switch that is useful in this testing is the - @code{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^} - switch for - @code{gnatbind}. - Normally the binder tries to find an order that has the best chance of - of avoiding elaboration problems. With this switch, the binder - plays a devil's advocate role, and tries to choose the order that - has the best chance of failing. If your program works even with this - switch, then it has a better chance of being error free, but this is still - not a guarantee. - - For an example of this approach in action, consider the C-tests (executable - tests) from the ACVC suite. If these are compiled and run with the default - treatment, then all but one of them succeed without generating any error - diagnostics from the binder. However, there is one test that fails, and - this is not surprising, because the whole point of this test is to ensure - that the compiler can handle cases where it is impossible to determine - a correct order statically, and it checks that an exception is indeed - raised at run time. - - This one test must be compiled and run using the - @option{-gnatE} - switch, and then it passes. Alternatively, the entire suite can - be run using this switch. It is never wrong to run with the dynamic - elaboration switch if your code is correct, and we assume that the - C-tests are indeed correct (it is less efficient, but efficiency is - not a factor in running the ACVC tests.) - - @node Elaboration for Access-to-Subprogram Values - @section Elaboration for Access-to-Subprogram Values - @cindex Access-to-subprogram - - @noindent - The introduction of access-to-subprogram types in Ada 95 complicates - the handling of elaboration. The trouble is that it becomes - impossible to tell at compile time which procedure - is being called. This means that it is not possible for the binder - to analyze the elaboration requirements in this case. - - If at the point at which the access value is created - (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}), - the body of the subprogram is - known to have been elaborated, then the access value is safe, and its use - does not require a check. This may be achieved by appropriate arrangement - of the order of declarations if the subprogram is in the current unit, - or, if the subprogram is in another unit, by using pragma - @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body} - on the referenced unit. - - If the referenced body is not known to have been elaborated at the point - the access value is created, then any use of the access value must do a - dynamic check, and this dynamic check will fail and raise a - @code{Program_Error} exception if the body has not been elaborated yet. - GNAT will generate the necessary checks, and in addition, if the - @option{-gnatwl} - switch is set, will generate warnings that such checks are required. - - The use of dynamic dispatching for tagged types similarly generates - a requirement for dynamic checks, and premature calls to any primitive - operation of a tagged type before the body of the operation has been elaborated, - will result in the raising of @code{Program_Error}. - - @node Summary of Procedures for Elaboration Control - @section Summary of Procedures for Elaboration Control - @cindex Elaboration control - - @noindent - First, compile your program with the default options, using none of - the special elaboration control switches. If the binder successfully - binds your program, then you can be confident that, apart from issues - raised by the use of access-to-subprogram types and dynamic dispatching, - the program is free of elaboration errors. If it is important that the - program be portable, then use the - @option{-gnatwl} - switch to generate warnings about missing @code{Elaborate_All} - pragmas, and supply the missing pragmas. - - If the program fails to bind using the default static elaboration - handling, then you can fix the program to eliminate the binder - message, or recompile the entire program with the - @option{-gnatE} switch to generate dynamic elaboration checks, - and, if you are sure there really are no elaboration problems, - use a global pragma @code{Suppress (Elaboration_Checks)}. - - @node Other Elaboration Order Considerations - @section Other Elaboration Order Considerations - @noindent - This section has been entirely concerned with the issue of finding a valid - elaboration order, as defined by the Ada Reference Manual. In a case - where several elaboration orders are valid, the task is to find one - of the possible valid elaboration orders (and the static model in GNAT - will ensure that this is achieved). - - The purpose of the elaboration rules in the Ada Reference Manual is to - make sure that no entity is accessed before it has been elaborated. For - a subprogram, this means that the spec and body must have been elaborated - before the subprogram is called. For an object, this means that the object - must have been elaborated before its value is read or written. A violation - of either of these two requirements is an access before elaboration order, - and this section has been all about avoiding such errors. - - In the case where more than one order of elaboration is possible, in the - sense that access before elaboration errors are avoided, then any one of - the orders is "correct" in the sense that it meets the requirements of - the Ada Reference Manual, and no such error occurs. - - However, it may be the case for a given program, that there are - constraints on the order of elaboration that come not from consideration - of avoiding elaboration errors, but rather from extra-lingual logic - requirements. Consider this example: - - @smallexample - with Init_Constants; - package Constants is - X : Integer := 0; - Y : Integer := 0; - end Constants; - - package Init_Constants is - procedure Calc; - end Init_Constants; - - with Constants; - package body Init_Constants is - procedure Calc is begin null; end; - begin - Constants.X := 3; - Constants.Y := 4; - end Init_Constants; - - with Constants; - package Calc is - Z : Integer := Constants.X + Constants.Y; - end Calc; - - with Calc; - with Text_IO; use Text_IO; - procedure Main is - begin - Put_Line (Calc.Z'Img); - end Main; - @end smallexample - - @noindent - In this example, there is more than one valid order of elaboration. For - example both the following are correct orders: - - @smallexample - Init_Constants spec - Constants spec - Calc spec - Main body - Init_Constants body - - and - - Init_Constants spec - Init_Constants body - Constants spec - Calc spec - Main body - @end smallexample - - @noindent - There is no language rule to prefer one or the other, both are correct - from an order of elaboration point of view. But the programmatic effects - of the two orders are very different. In the first, the elaboration routine - of @code{Calc} initializes @code{Z} to zero, and then the main program - runs with this value of zero. But in the second order, the elaboration - routine of @code{Calc} runs after the body of Init_Constants has set - @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} - runs. - - One could perhaps by applying pretty clever non-artificial intelligence - to the situation guess that it is more likely that the second order of - elaboration is the one desired, but there is no formal linguistic reason - to prefer one over the other. In fact in this particular case, GNAT will - prefer the second order, because of the rule that bodies are elaborated - as soon as possible, but it's just luck that this is what was wanted - (if indeed the second order was preferred). - - If the program cares about the order of elaboration routines in a case like - this, it is important to specify the order required. In this particular - case, that could have been achieved by adding to the spec of Calc: - - @smallexample - pragma Elaborate_All (Constants); - @end smallexample - - @noindent - which requires that the body (if any) and spec of @code{Constants}, - as well as the body and spec of any unit @code{with}'ed by - @code{Constants} be elaborated before @code{Calc} is elaborated. - - Clearly no automatic method can always guess which alternative you require, - and if you are working with legacy code that had constraints of this kind - which were not properly specified by adding @code{Elaborate} or - @code{Elaborate_All} pragmas, then indeed it is possible that two different - compilers can choose different orders. - - The @code{gnatbind} - @code{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking - out problems. This switch causes bodies to be elaborated as late as possible - instead of as early as possible. In the example above, it would have forced - the choice of the first elaboration order. If you get different results - when using this switch, and particularly if one set of results is right, - and one is wrong as far as you are concerned, it shows that you have some - missing @code{Elaborate} pragmas. For the example above, we have the - following output: - - @smallexample - gnatmake -f -q main - main - 7 - gnatmake -f -q main -bargs -p - main - 0 - @end smallexample - - @noindent - It is of course quite unlikely that both these results are correct, so - it is up to you in a case like this to investigate the source of the - difference, by looking at the two elaboration orders that are chosen, - and figuring out which is correct, and then adding the necessary - @code{Elaborate_All} pragmas to ensure the desired order. - - @node The Cross-Referencing Tools gnatxref and gnatfind - @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind} - @findex gnatxref - @findex gnatfind - - @noindent - The compiler generates cross-referencing information (unless - you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files. - This information indicates where in the source each entity is declared and - referenced. Note that entities in package Standard are not included, but - entities in all other predefined units are included in the output. - - Before using any of these two tools, you need to compile successfully your - application, so that GNAT gets a chance to generate the cross-referencing - information. - - The two tools @code{gnatxref} and @code{gnatfind} take advantage of this - information to provide the user with the capability to easily locate the - declaration and references to an entity. These tools are quite similar, - the difference being that @code{gnatfind} is intended for locating - definitions and/or references to a specified entity or entities, whereas - @code{gnatxref} is oriented to generating a full report of all - cross-references. - - To use these tools, you must not compile your application using the - @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The - GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing - information will not be generated. - - @menu - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - @end menu - - @node gnatxref Switches - @section @code{gnatxref} Switches - - @noindent - The command lines for @code{gnatxref} is: - @smallexample - $ gnatxref [switches] sourcefile1 [sourcefile2 ...] - @end smallexample - - @noindent - where - - @table @code - @item sourcefile1, sourcefile2 - identifies the source files for which a report is to be generated. The - 'with'ed units will be processed too. You must provide at least one file. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - @end table - - @noindent - The switches can be : - @table @code - @item ^-a^/ALL_FILES^ - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatxref}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set @code{gnatxref} will output the parent type - reference for each matching derived types. - - @item ^-f^/FULL_PATHNAME^ - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item ^-g^/IGNORE_LOCALS^ - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file to use @xref{Project Files}. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} - and @samp{^-aO^OBJECT_SEARCH^}. - @item ^-u^/UNUSED^ - Output only unused symbols. This may be really useful if you give your - main compilation unit on the command line, as @code{gnatxref} will then - display every unused entity and 'with'ed package. - - @ifclear vms - @item -v - Instead of producing the default output, @code{gnatxref} will generate a - @file{tags} file that can be used by vi. For examples how to use this - feature, see @xref{Examples of gnatxref Usage}. The tags file is output - to the standard output, thus you will have to redirect it to a file. - @end ifclear - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of - @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}. - - @node gnatfind Switches - @section @code{gnatfind} Switches - - @noindent - The command line for @code{gnatfind} is: - - @smallexample - $ gnatfind [switches] pattern[:sourcefile[:line[:column]]] - [file1 file2 ...] - @end smallexample - - @noindent - where - - @table @code - @item pattern - An entity will be output only if it matches the regular expression found - in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}. - - Omitting the pattern is equivalent to specifying @samp{*}, which - will match any entity. Note that if you do not provide a pattern, you - have to provide both a sourcefile and a line. - - Entity names are given in Latin-1, with uppercase/lowercase equivalence - for matching purposes. At the current time there is no support for - 8-bit codes other than Latin-1, or for wide characters in identifiers. - - @item sourcefile - @code{gnatfind} will look for references, bodies or declarations - of symbols referenced in @file{sourcefile}, at line @samp{line} - and column @samp{column}. See @pxref{Examples of gnatfind Usage} - for syntax examples. - - @item line - is a decimal integer identifying the line number containing - the reference to the entity (or entities) to be located. - - @item column - is a decimal integer identifying the exact location on the - line of the first character of the identifier for the - entity reference. Columns are numbered from 1. - - @item file1 file2 ... - The search will be restricted to these files. If none are given, then - the search will be done for every library file in the search path. - These file must appear only after the pattern or sourcefile. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - Not that if you specify at least one file in this part, @code{gnatfind} may - sometimes not be able to find the body of the subprograms... - - @end table - - At least one of 'sourcefile' or 'pattern' has to be present on - the command line. - - The following switches are available: - @table @code - - @item ^-a^/ALL_FILES^ - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatfind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set, then @code{gnatfind} will output the parent type - reference for each matching derived types. - - @item ^-e^/EXPRESSIONS^ - By default, @code{gnatfind} accept the simple regular expression set for - @samp{pattern}. If this switch is set, then the pattern will be - considered as full Unix-style regular expression. - - @item ^-f^/FULL_PATHNAME^ - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item ^-g^/IGNORE_LOCALS^ - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file (@pxref{Project Files}) to use. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and - @samp{^-aO^/OBJECT_SEARCH^}. - - @item ^-r^/REFERENCES^ - By default, @code{gnatfind} will output only the information about the - declaration, body or type completion of the entities. If this switch is - set, the @code{gnatfind} will locate every reference to the entities in - the files specified on the command line (or in every file in the search - path if no file is given on the command line). - - @item ^-s^/PRINT_LINES^ - If this switch is set, then @code{gnatfind} will output the content - of the Ada source file lines were the entity was found. - - @item -t - If this switch is set, then @code{gnatfind} will output the type hierarchy for - the specified type. It act like -d option but recursively from parent - type to parent type. When this switch is set it is not possible to - specify more than one file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of - @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}. - - As stated previously, gnatfind will search in every directory in the - search path. You can force it to look only in the current directory if - you specify @code{*} at the end of the command line. - - - @node Project Files for gnatxref and gnatfind - @section Project Files for @command{gnatxref} and @command{gnatfind} - - @noindent - Project files allow a programmer to specify how to compile its - application, where to find sources,... These files are used primarily by - the Glide Ada mode, but they can also be used by the two tools - @code{gnatxref} and @code{gnatfind}. - - A project file name must end with @file{.adp}. If a single one is - present in the current directory, then @code{gnatxref} and @code{gnatfind} will - extract the information from it. If multiple project files are found, none of - them is read, and you have to use the @samp{-p} switch to specify the one - you want to use. - - The following lines can be included, even though most of them have default - values which can be used in most cases. - The lines can be entered in any order in the file. - Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of - each line. If you have multiple instances, only the last one is taken into - account. - - @table @code - @item src_dir=DIR [default: "^./^[]^"] - specifies a directory where to look for source files. Multiple src_dir lines - can be specified and they will be searched in the order they - are specified. - - @item obj_dir=DIR [default: "^./^[]^"] - specifies a directory where to look for object and library files. Multiple - obj_dir lines can be specified and they will be searched in the order they - are specified - - @item comp_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{comp_opt@}} notation. This is intended to store the default - switches given to @file{gnatmake} and @file{gcc}. - - @item bind_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{bind_opt@}} notation. This is intended to store the default - switches given to @file{gnatbind}. - - @item link_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{link_opt@}} notation. This is intended to store the default - switches given to @file{gnatlink}. - - @item main=EXECUTABLE [default: ""] - specifies the name of the executable for the application. This variable can - be referred to in the following lines by using the @samp{$@{main@}} notation. - - @ifset vms - @item comp_cmd=COMMAND [default: "GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"] - @end ifset - @ifclear vms - @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"] - @end ifclear - specifies the command used to compile a single file in the application. - - @ifset vms - @item make_cmd=COMMAND [default: "GNAT MAKE $@{main@} /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@} /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@} /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"] - @end ifset - @ifclear vms - @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"] - @end ifclear - specifies the command used to recompile the whole application. - - @item run_cmd=COMMAND [default: "$@{main@}"] - specifies the command used to run the application. - - @item debug_cmd=COMMAND [default: "gdb $@{main@}"] - specifies the command used to debug the application - - @end table - - @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir} - and @samp{obj_dir} lines, and ignore the others. - - @node Regular Expressions in gnatfind and gnatxref - @section Regular Expressions in @code{gnatfind} and @code{gnatxref} - - @noindent - As specified in the section about @code{gnatfind}, the pattern can be a - regular expression. Actually, there are to set of regular expressions - which are recognized by the program : - - @table @code - @item globbing patterns - These are the most usual regular expression. They are the same that you - generally used in a Unix shell command line, or in a DOS session. - - Here is a more formal grammar : - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - regexp ::= term - term ::= elmt -- matches elmt - term ::= elmt elmt -- concatenation (elmt then elmt) - term ::= * -- any string of 0 or more characters - term ::= ? -- matches any character - term ::= [char @{char@}] -- matches any character listed - term ::= [char - char] -- matches any character in range - @end group - @end smallexample - - @item full regular expression - The second set of regular expressions is much more powerful. This is the - type of regular expressions recognized by utilities such a @file{grep}. - - The following is the form of a regular expression, expressed in Ada - reference manual style BNF is as follows - - @smallexample - @iftex - @leftskip=.5cm - @end iftex - @group - regexp ::= term @{| term@} -- alternation (term or term ...) - - term ::= item @{item@} -- concatenation (item then item) - - item ::= elmt -- match elmt - item ::= elmt * -- zero or more elmt's - item ::= elmt + -- one or more elmt's - item ::= elmt ? -- matches elmt or nothing - @end group - @group - elmt ::= nschar -- matches given character - elmt ::= [nschar @{nschar@}] -- matches any character listed - elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed - elmt ::= [char - char] -- matches chars in given range - elmt ::= \ char -- matches given character - elmt ::= . -- matches any single character - elmt ::= ( regexp ) -- parens used for grouping - - char ::= any character, including special characters - nschar ::= any character except ()[].*+?^^^ - @end group - @end smallexample - - Following are a few examples : - - @table @samp - @item abcde|fghi - will match any of the two strings 'abcde' and 'fghi'. - - @item abc*d - will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on - - @item [a-z]+ - will match any string which has only lowercase characters in it (and at - least one character - - @end table - @end table - - @node Examples of gnatxref Usage - @section Examples of @code{gnatxref} Usage - - @subsection General Usage - - @noindent - For the following examples, we will consider the following units : - - @smallexample - @group - @cartouche - main.ads: - 1: @b{with} Bar; - 2: @b{package} Main @b{is} - 3: @b{procedure} Foo (B : @b{in} Integer); - 4: C : Integer; - 5: @b{private} - 6: D : Integer; - 7: @b{end} Main; - - main.adb: - 1: @b{package body} Main @b{is} - 2: @b{procedure} Foo (B : @b{in} Integer) @b{is} - 3: @b{begin} - 4: C := B; - 5: D := B; - 6: Bar.Print (B); - 7: Bar.Print (C); - 8: @b{end} Foo; - 9: @b{end} Main; - - bar.ads: - 1: @b{package} Bar @b{is} - 2: @b{procedure} Print (B : Integer); - 3: @b{end} bar; - @end cartouche - @end group - @end smallexample - - @table @code - - @noindent - The first thing to do is to recompile your application (for instance, in - that case just by doing a @samp{gnatmake main}, so that GNAT generates - the cross-referencing information. - You can then issue any of the following commands: - - @item gnatxref main.adb - @code{gnatxref} generates cross-reference information for main.adb - and every unit 'with'ed by main.adb. - - The output would be: - @smallexample - @iftex - @leftskip=0cm - @end iftex - B Type: Integer - Decl: bar.ads 2:22 - B Type: Integer - Decl: main.ads 3:20 - Body: main.adb 2:20 - Ref: main.adb 4:13 5:13 6:19 - Bar Type: Unit - Decl: bar.ads 1:9 - Ref: main.adb 6:8 7:8 - main.ads 1:6 - C Type: Integer - Decl: main.ads 4:5 - Modi: main.adb 4:8 - Ref: main.adb 7:19 - D Type: Integer - Decl: main.ads 6:5 - Modi: main.adb 5:8 - Foo Type: Unit - Decl: main.ads 3:15 - Body: main.adb 2:15 - Main Type: Unit - Decl: main.ads 2:9 - Body: main.adb 1:14 - Print Type: Unit - Decl: bar.ads 2:15 - Ref: main.adb 6:12 7:12 - @end smallexample - - @noindent - that is the entity @code{Main} is declared in main.ads, line 2, column 9, - its body is in main.adb, line 1, column 14 and is not referenced any where. - - The entity @code{Print} is declared in bar.ads, line 2, column 15 and it - it referenced in main.adb, line 6 column 12 and line 7 column 12. - - @item gnatxref package1.adb package2.ads - @code{gnatxref} will generates cross-reference information for - package1.adb, package2.ads and any other package 'with'ed by any - of these. - - @end table - - @ifclear vms - @subsection Using gnatxref with vi - - @code{gnatxref} can generate a tags file output, which can be used - directly from @file{vi}. Note that the standard version of @file{vi} - will not work properly with overloaded symbols. Consider using another - free implementation of @file{vi}, such as @file{vim}. - - @smallexample - $ gnatxref -v gnatfind.adb > tags - @end smallexample - - @noindent - will generate the tags file for @code{gnatfind} itself (if the sources - are in the search path!). - - From @file{vi}, you can then use the command @samp{:tag @i{entity}} - (replacing @i{entity} by whatever you are looking for), and vi will - display a new file with the corresponding declaration of entity. - @end ifclear - - @node Examples of gnatfind Usage - @section Examples of @code{gnatfind} Usage - - @table @code - - @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb - Find declarations for all entities xyz referenced at least once in - main.adb. The references are search in every library file in the search - path. - - The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^} - switch is set) - - The output will look like: - @smallexample - ^directory/^[directory]^main.ads:106:14: xyz <= declaration - ^directory/^[directory]^main.adb:24:10: xyz <= body - ^directory/^[directory]^foo.ads:45:23: xyz <= declaration - @end smallexample - - @noindent - that is to say, one of the entities xyz found in main.adb is declared at - line 12 of main.ads (and its body is in main.adb), and another one is - declared at line 45 of foo.ads - - @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb - This is the same command as the previous one, instead @code{gnatfind} will - display the content of the Ada source file lines. - - The output will look like: - - @smallexample - ^directory/^[directory]^main.ads:106:14: xyz <= declaration - procedure xyz; - ^directory/^[directory]^main.adb:24:10: xyz <= body - procedure xyz is - ^directory/^[directory]^foo.ads:45:23: xyz <= declaration - xyz : Integer; - @end smallexample - - @noindent - This can make it easier to find exactly the location your are looking - for. - - @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb - Find references to all entities containing an x that are - referenced on line 123 of main.ads. - The references will be searched only in main.adb and foo.adb. - - @item gnatfind main.ads:123 - Find declarations and bodies for all entities that are referenced on - line 123 of main.ads. - - This is the same as @code{gnatfind "*":main.adb:123}. - - @item gnatfind ^mydir/^[mydir]^main.adb:123:45 - Find the declaration for the entity referenced at column 45 in - line 123 of file main.adb in directory mydir. Note that it - is usual to omit the identifier name when the column is given, - since the column position identifies a unique reference. - - The column has to be the beginning of the identifier, and should not - point to any character in the middle of the identifier. - - @end table - - @node File Name Krunching Using gnatkr - @chapter File Name Krunching Using @code{gnatkr} - @findex gnatkr - - @noindent - This chapter discusses the method used by the compiler to shorten - the default file names chosen for Ada units so that they do not - exceed the maximum length permitted. It also describes the - @code{gnatkr} utility that can be used to determine the result of - applying this shortening. - @menu - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - @end menu - - @node About gnatkr - @section About @code{gnatkr} - - @noindent - The default file naming rule in GNAT - is that the file name must be derived from - the unit name. The exact default rule is as follows: - @itemize @bullet - @item - Take the unit name and replace all dots by hyphens. - @item - If such a replacement occurs in the - second character position of a name, and the first character is - ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character - ^~ (tilde)^$ (dollar sign)^ - instead of a minus. - @end itemize - The reason for this exception is to avoid clashes - with the standard names for children of System, Ada, Interfaces, - and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^ - respectively. - - The @code{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}} - switch of the compiler activates a "krunching" - circuit that limits file names to nn characters (where nn is a decimal - integer). For example, using OpenVMS, - where the maximum file name length is - 39, the value of nn is usually set to 39, but if you want to generate - a set of files that would be usable if ported to a system with some - different maximum file length, then a different value can be specified. - The default value of 39 for OpenVMS need not be specified. - - The @code{gnatkr} utility can be used to determine the krunched name for - a given file, when krunched to a specified maximum length. - - @node Using gnatkr - @section Using @code{gnatkr} - - @noindent - The @code{gnatkr} command has the form - - @ifclear vms - @smallexample - $ gnatkr @var{name} [@var{length}] - @end smallexample - @end ifclear - - @ifset vms - @smallexample - $ gnatkr @var{name} /COUNT=nn - @end smallexample - @end ifset - - @noindent - @var{name} can be an Ada name with dots or the GNAT name of the unit, - where the dots representing child units or subunit are replaced by - hyphens. The only confusion arises if a name ends in @code{.ads} or - @code{.adb}. @code{gnatkr} takes this to be an extension if there are - no other dots in the name^ and the whole name is in lowercase^^. - - @var{length} represents the length of the krunched name. The default - when no argument is given is ^8^39^ characters. A length of zero stands for - unlimited, in other words do not chop except for system files which are - always ^8^39^. - - @noindent - The output is the krunched name. The output has an extension only if the - original argument was a file name with an extension. - - @node Krunching Method - @section Krunching Method - - @noindent - The initial file name is determined by the name of the unit that the file - contains. The name is formed by taking the full expanded name of the - unit and replacing the separating dots with hyphens and - using ^lowercase^uppercase^ - for all letters, except that a hyphen in the second character position is - replaced by a ^tilde^dollar sign^ if the first character is - ^a, i, g, or s^A, I, G, or S^. - The extension is @code{.ads} for a - specification and @code{.adb} for a body. - Krunching does not affect the extension, but the file name is shortened to - the specified length by following these rules: - - @itemize @bullet - @item - The name is divided into segments separated by hyphens, tildes or - underscores and all hyphens, tildes, and underscores are - eliminated. If this leaves the name short enough, we are done. - - @item - If the name is too long, the longest segment is located (left-most if there are two - of equal length), and shortened by dropping its last character. This is - repeated until the name is short enough. - - As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb} - to fit the name into 8 characters as required by some operating systems. - - @smallexample - our-strings-wide_fixed 22 - our strings wide fixed 19 - our string wide fixed 18 - our strin wide fixed 17 - our stri wide fixed 16 - our stri wide fixe 15 - our str wide fixe 14 - our str wid fixe 13 - our str wid fix 12 - ou str wid fix 11 - ou st wid fix 10 - ou st wi fix 9 - ou st wi fi 8 - Final file name: oustwifi.adb - @end smallexample - - @item - The file names for all predefined units are always krunched to eight - characters. The krunching of these predefined units uses the following - special prefix replacements: - - @table @file - @item ada- - replaced by @file{^a^A^-} - - @item gnat- - replaced by @file{^g^G^-} - - @item interfaces- - replaced by @file{^i^I^-} - - @item system- - replaced by @file{^s^S^-} - @end table - - These system files have a hyphen in the second character position. That - is why normal user files replace such a character with a - ^tilde^dollar sign^, to - avoid confusion with system file names. - - As an example of this special rule, consider - @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows: - - @smallexample - ada-strings-wide_fixed 22 - a- strings wide fixed 18 - a- string wide fixed 17 - a- strin wide fixed 16 - a- stri wide fixed 15 - a- stri wide fixe 14 - a- str wide fixe 13 - a- str wid fixe 12 - a- str wid fix 11 - a- st wid fix 10 - a- st wi fix 9 - a- st wi fi 8 - Final file name: a-stwifi.adb - @end smallexample - @end itemize - - Of course no file shortening algorithm can guarantee uniqueness over all - possible unit names, and if file name krunching is used then it is your - responsibility to ensure that no name clashes occur. The utility - program @code{gnatkr} is supplied for conveniently determining the - krunched name of a file. - - @node Examples of gnatkr Usage - @section Examples of @code{gnatkr} Usage - - @smallexample - @iftex - @leftskip=0cm - @end iftex - @ifclear vms - $ gnatkr very_long_unit_name.ads --> velounna.ads - $ gnatkr grandparent-parent-child.ads --> grparchi.ads - $ gnatkr Grandparent.Parent.Child --> grparchi - @end ifclear - $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads - $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads - @end smallexample - - @node Preprocessing Using gnatprep - @chapter Preprocessing Using @code{gnatprep} - @findex gnatprep - - @noindent - The @code{gnatprep} utility provides - a simple preprocessing capability for Ada programs. - It is designed for use with GNAT, but is not dependent on any special - features of GNAT. - - @menu - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - @end menu - - @node Using gnatprep - @section Using @code{gnatprep} - - @noindent - To call @code{gnatprep} use - - @smallexample - $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile] - @end smallexample - - @noindent - where - @table @code - @item infile - is the full name of the input file, which is an Ada source - file containing preprocessor directives. - - @item outfile - is the full name of the output file, which is an Ada source - in standard Ada form. When used with GNAT, this file name will - normally have an ads or adb suffix. - - @item deffile - is the full name of a text file containing definitions of - symbols to be referenced by the preprocessor. This argument is - optional, and can be replaced by the use of the @code{-D} switch. - - @item switches - is an optional sequence of switches as described in the next section. - @end table - - @node Switches for gnatprep - @section Switches for @code{gnatprep} - - @table @code - - @item ^-b^/BLANK_LINES^ - Causes both preprocessor lines and the lines deleted by - preprocessing to be replaced by blank lines in the output source file, - preserving line numbers in the output file. - - @item ^-c^/COMMENTS^ - Causes both preprocessor lines and the lines deleted - by preprocessing to be retained in the output source as comments marked - with the special string "--! ". This option will result in line numbers - being preserved in the output file. - - @item -Dsymbol=value - Defines a new symbol, associated with value. If no value is given on the - command line, then symbol is considered to be @code{True}. This switch - can be used in place of a definition file. - - @ifset vms - @item /REMOVE (default) - This is the default setting which causes lines deleted by preprocessing - to be entirely removed from the output file. - @end ifset - - @item ^-r^/REFERENCE^ - Causes a @code{Source_Reference} pragma to be generated that - references the original input file, so that error messages will use - the file name of this original file. The use of this switch implies - that preprocessor lines are not to be removed from the file, so its - use will force @code{^-b^/BLANK_LINES^} mode if - @code{^-c^/COMMENTS^} - has not been specified explicitly. - - Note that if the file to be preprocessed contains multiple units, then - it will be necessary to @code{gnatchop} the output file from - @code{gnatprep}. If a @code{Source_Reference} pragma is present - in the preprocessed file, it will be respected by - @code{gnatchop ^-r^/REFERENCE^} - so that the final chopped files will correctly refer to the original - input source file for @code{gnatprep}. - - @item ^-s^/SYMBOLS^ - Causes a sorted list of symbol names and values to be - listed on the standard output file. - - @item ^-u^/UNDEFINED^ - Causes undefined symbols to be treated as having the value FALSE in the context - of a preprocessor test. In the absence of this option, an undefined symbol in - a @code{#if} or @code{#elsif} test will be treated as an error. - - @end table - - @ifclear vms - @noindent - Note: if neither @code{-b} nor @code{-c} is present, - then preprocessor lines and - deleted lines are completely removed from the output, unless -r is - specified, in which case -b is assumed. - @end ifclear - - @node Form of Definitions File - @section Form of Definitions File - - @noindent - The definitions file contains lines of the form - - @smallexample - symbol := value - @end smallexample - - @noindent - where symbol is an identifier, following normal Ada (case-insensitive) - rules for its syntax, and value is one of the following: - - @itemize @bullet - @item - Empty, corresponding to a null substitution - @item - A string literal using normal Ada syntax - @item - Any sequence of characters from the set - (letters, digits, period, underline). - @end itemize - - @noindent - Comment lines may also appear in the definitions file, starting with - the usual @code{--}, - and comments may be added to the definitions lines. - - @node Form of Input Text for gnatprep - @section Form of Input Text for @code{gnatprep} - - @noindent - The input text may contain preprocessor conditional inclusion lines, - as well as general symbol substitution sequences. - - The preprocessor conditional inclusion commands have the form - - @smallexample - @group - @cartouche - #if @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - ... - #else - lines - #end if; - @end cartouche - @end group - @end smallexample - - @noindent - In this example, @i{expression} is defined by the following grammar: - @smallexample - @i{expression} ::= - @i{expression} ::= = "" - @i{expression} ::= = - @i{expression} ::= 'Defined - @i{expression} ::= not @i{expression} - @i{expression} ::= @i{expression} and @i{expression} - @i{expression} ::= @i{expression} or @i{expression} - @i{expression} ::= @i{expression} and then @i{expression} - @i{expression} ::= @i{expression} or else @i{expression} - @i{expression} ::= ( @i{expression} ) - @end smallexample - - @noindent - For the first test (@i{expression} ::= ) the symbol must have - either the value true or false, that is to say the right-hand of the - symbol definition must be one of the (case-insensitive) literals - @code{True} or @code{False}. If the value is true, then the - corresponding lines are included, and if the value is false, they are - excluded. - - The test (@i{expression} ::= @code{'Defined}) is true only if - the symbol has been defined in the definition file or by a @code{-D} - switch on the command line. Otherwise, the test is false. - - The equality tests are case insensitive, as are all the preprocessor lines. - - If the symbol referenced is not defined in the symbol definitions file, - then the effect depends on whether or not switch @code{-u} - is specified. If so, then the symbol is treated as if it had the value - false and the test fails. If this switch is not specified, then - it is an error to reference an undefined symbol. It is also an error to - reference a symbol that is defined with a value other than @code{True} - or @code{False}. - - The use of the @code{not} operator inverts the sense of this logical test, so - that the lines are included only if the symbol is not defined. - The @code{then} keyword is optional as shown - - The @code{#} must be the first non-blank character on a line, but - otherwise the format is free form. Spaces or tabs may appear between - the @code{#} and the keyword. The keywords and the symbols are case - insensitive as in normal Ada code. Comments may be used on a - preprocessor line, but other than that, no other tokens may appear on a - preprocessor line. Any number of @code{elsif} clauses can be present, - including none at all. The @code{else} is optional, as in Ada. - - The @code{#} marking the start of a preprocessor line must be the first - non-blank character on the line, i.e. it must be preceded only by - spaces or horizontal tabs. - - Symbol substitution outside of preprocessor lines is obtained by using - the sequence - - @smallexample - $symbol - @end smallexample - - @noindent - anywhere within a source line, except in a comment or within a - string literal. The identifier - following the @code{$} must match one of the symbols defined in the symbol - definition file, and the result is to substitute the value of the - symbol in place of @code{$symbol} in the output file. - - Note that although the substitution of strings within a string literal - is not possible, it is possible to have a symbol whose defined value is - a string literal. So instead of setting XYZ to @code{hello} and writing: - - @smallexample - Header : String := "$XYZ"; - @end smallexample - - @noindent - you should set XYZ to @code{"hello"} and write: - - @smallexample - Header : String := $XYZ; - @end smallexample - - @noindent - and then the substitution will occur as desired. - - @ifset vms - @node The GNAT Run-Time Library Builder gnatlbr - @chapter The GNAT Run-Time Library Builder @code{gnatlbr} - @findex gnatlbr - @cindex Library builder - - @noindent - @code{gnatlbr} is a tool for rebuilding the GNAT run time with user - supplied configuration pragmas. - - @menu - * Running gnatlbr:: - * Switches for gnatlbr:: - * Examples of gnatlbr Usage:: - @end menu - - @node Running gnatlbr - @section Running @code{gnatlbr} - - @noindent - The @code{gnatlbr} command has the form - - @smallexample - $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file] - @end smallexample - - @node Switches for gnatlbr - @section Switches for @code{gnatlbr} - - @noindent - @code{gnatlbr} recognizes the following switches: - - @table @code - @item /CREATE=directory - @cindex @code{/CREATE=directory} (@code{gnatlbr}) - Create the new run-time library in the specified directory. - - @item /SET=directory - @cindex @code{/SET=directory} (@code{gnatlbr}) - Make the library in the specified directory the current run-time - library. - - @item /DELETE=directory - @cindex @code{/DELETE=directory} (@code{gnatlbr}) - Delete the run-time library in the specified directory. - - @item /CONFIG=file - @cindex @code{/CONFIG=file} (@code{gnatlbr}) - With /CREATE: - Use the configuration pragmas in the specified file when building - the library. - - With /SET: - Use the configuration pragmas in the specified file when compiling. - - @end table - - @node Examples of gnatlbr Usage - @section Example of @code{gnatlbr} Usage - - @smallexample - Contents of VAXFLOAT.ADC: - pragma Float_Representation (VAX_Float); - - $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC - - GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT] - - @end smallexample - @end ifset - - @node The GNAT Library Browser gnatls - @chapter The GNAT Library Browser @code{gnatls} - @findex gnatls - @cindex Library browser - - @noindent - @code{gnatls} is a tool that outputs information about compiled - units. It gives the relationship between objects, unit names and source - files. It can also be used to check the source dependencies of a unit - as well as various characteristics. - - @menu - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - @end menu - - @node Running gnatls - @section Running @code{gnatls} - - @noindent - The @code{gnatls} command has the form - - @smallexample - $ gnatls switches @var{object_or_ali_file} - @end smallexample - - @noindent - The main argument is the list of object or @file{ali} files - (@pxref{The Ada Library Information Files}) - for which information is requested. - - In normal mode, without additional option, @code{gnatls} produces a - four-column listing. Each line represents information for a specific - object. The first column gives the full path of the object, the second - column gives the name of the principal unit in this object, the third - column gives the status of the source and the fourth column gives the - full path of the source representing this unit. - Here is a simple example of use: - - @smallexample - $ gnatls *.o - ^./^[]^demo1.o demo1 DIF demo1.adb - ^./^[]^demo2.o demo2 OK demo2.adb - ^./^[]^hello.o h1 OK hello.adb - ^./^[]^instr-child.o instr.child MOK instr-child.adb - ^./^[]^instr.o instr OK instr.adb - ^./^[]^tef.o tef DIF tef.adb - ^./^[]^text_io_example.o text_io_example OK text_io_example.adb - ^./^[]^tgef.o tgef DIF tgef.adb - @end smallexample - - @noindent - The first line can be interpreted as follows: the main unit which is - contained in - object file @file{demo1.o} is demo1, whose main source is in - @file{demo1.adb}. Furthermore, the version of the source used for the - compilation of demo1 has been modified (DIF). Each source file has a status - qualifier which can be: - - @table @code - @item OK (unchanged) - The version of the source file used for the compilation of the - specified unit corresponds exactly to the actual source file. - - @item MOK (slightly modified) - The version of the source file used for the compilation of the - specified unit differs from the actual source file but not enough to - require recompilation. If you use gnatmake with the qualifier - @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked - MOK will not be recompiled. - - @item DIF (modified) - No version of the source found on the path corresponds to the source - used to build this object. - - @item ??? (file not found) - No source file was found for this unit. - - @item HID (hidden, unchanged version not first on PATH) - The version of the source that corresponds exactly to the source used - for compilation has been found on the path but it is hidden by another - version of the same source that has been modified. - - @end table - - @node Switches for gnatls - @section Switches for @code{gnatls} - - @noindent - @code{gnatls} recognizes the following switches: - - @table @code - @item ^-a^/ALL_UNITS^ - @cindex @code{^-a^/ALL_UNITS^} (@code{gnatls}) - Consider all units, including those of the predefined Ada library. - Especially useful with @code{^-d^/DEPENDENCIES^}. - - @item ^-d^/DEPENDENCIES^ - @cindex @code{^-d^/DEPENDENCIES^} (@code{gnatls}) - List sources from which specified units depend on. - - @item ^-h^/OUTPUT=OPTIONS^ - @cindex @code{^-h^/OUTPUT=OPTIONS^} (@code{gnatls}) - Output the list of options. - - @item ^-o^/OUTPUT=OBJECTS^ - @cindex @code{^-o^/OUTPUT=OBJECTS^} (@code{gnatls}) - Only output information about object files. - - @item ^-s^/OUTPUT=SOURCES^ - @cindex @code{^-s^/OUTPUT=SOURCES^} (@code{gnatls}) - Only output information about source files. - - @item ^-u^/OUTPUT=UNITS^ - @cindex @code{^-u^/OUTPUT=UNITS^} (@code{gnatls}) - Only output information about compilation units. - - @item ^-aO^/OBJECT_SEARCH=^@var{dir} - @itemx ^-aI^/SOURCE_SEARCH=^@var{dir} - @itemx ^-I^/SEARCH=^@var{dir} - @itemx ^-I-^/NOCURRENT_DIRECTORY^ - @itemx -nostdinc - Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags - (see @ref{Switches for gnatmake}). - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatls}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item ^-v^/OUTPUT=VERBOSE^ - @cindex @code{^-s^/OUTPUT=VERBOSE^} (@code{gnatls}) - Verbose mode. Output the complete source and object paths. Do not use - the default column layout but instead use long format giving as much as - information possible on each requested units, including special - characteristics such as: - - @table @code - @item Preelaborable - The unit is preelaborable in the Ada 95 sense. - - @item No_Elab_Code - No elaboration code has been produced by the compiler for this unit. - - @item Pure - The unit is pure in the Ada 95 sense. - - @item Elaborate_Body - The unit contains a pragma Elaborate_Body. - - @item Remote_Types - The unit contains a pragma Remote_Types. - - @item Shared_Passive - The unit contains a pragma Shared_Passive. - - @item Predefined - This unit is part of the predefined environment and cannot be modified - by the user. - - @item Remote_Call_Interface - The unit contains a pragma Remote_Call_Interface. - - @end table - - @end table - - @node Examples of gnatls Usage - @section Example of @code{gnatls} Usage - @ifclear vms - - @noindent - Example of using the verbose switch. Note how the source and - object paths are affected by the -I switch. - - @smallexample - $ gnatls -v -I.. demo1.o - - GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc. - - Source Search Path: - - ../ - /home/comar/local/adainclude/ - - Object Search Path: - - ../ - /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/ - - ./demo1.o - Unit => - Name => demo1 - Kind => subprogram body - Flags => No_Elab_Code - Source => demo1.adb modified - @end smallexample - - @noindent - The following is an example of use of the dependency list. - Note the use of the -s switch - which gives a straight list of source files. This can be useful for - building specialized scripts. - - @smallexample - $ gnatls -d demo2.o - ./demo2.o demo2 OK demo2.adb - OK gen_list.ads - OK gen_list.adb - OK instr.ads - OK instr-child.ads - - $ gnatls -d -s -a demo1.o - demo1.adb - /home/comar/local/adainclude/ada.ads - /home/comar/local/adainclude/a-finali.ads - /home/comar/local/adainclude/a-filico.ads - /home/comar/local/adainclude/a-stream.ads - /home/comar/local/adainclude/a-tags.ads - gen_list.ads - gen_list.adb - /home/comar/local/adainclude/gnat.ads - /home/comar/local/adainclude/g-io.ads - instr.ads - /home/comar/local/adainclude/system.ads - /home/comar/local/adainclude/s-exctab.ads - /home/comar/local/adainclude/s-finimp.ads - /home/comar/local/adainclude/s-finroo.ads - /home/comar/local/adainclude/s-secsta.ads - /home/comar/local/adainclude/s-stalib.ads - /home/comar/local/adainclude/s-stoele.ads - /home/comar/local/adainclude/s-stratt.ads - /home/comar/local/adainclude/s-tasoli.ads - /home/comar/local/adainclude/s-unstyp.ads - /home/comar/local/adainclude/unchconv.ads - @end smallexample - @end ifclear - - @ifset vms - @smallexample - GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB - - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads - demo1.adb - gen_list.ads - gen_list.adb - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads - instr.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads - @end smallexample - @end ifset - - @ifclear vms - @node GNAT and Libraries - @chapter GNAT and Libraries - @cindex Library, building, installing - - @noindent - This chapter addresses some of the issues related to building and using - a library with GNAT. It also shows how the GNAT run-time library can be - recompiled. - - @menu - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - @end menu - - @node Creating an Ada Library - @section Creating an Ada Library - - @noindent - In the GNAT environment, a library has two components: - @itemize @bullet - @item - Source files. - @item - Compiled code and Ali files. See @ref{The Ada Library Information Files}. - @end itemize - - @noindent - In order to use other packages @ref{The GNAT Compilation Model} - requires a certain number of sources to be available to the compiler. - The minimal set of - sources required includes the specs of all the packages that make up the - visible part of the library as well as all the sources upon which they - depend. The bodies of all visible generic units must also be provided. - @noindent - Although it is not strictly mandatory, it is recommended that all sources - needed to recompile the library be provided, so that the user can make - full use of inter-unit inlining and source-level debugging. This can also - make the situation easier for users that need to upgrade their compilation - toolchain and thus need to recompile the library from sources. - - @noindent - The compiled code can be provided in different ways. The simplest way is - to provide directly the set of objects produced by the compiler during - the compilation of the library. It is also possible to group the objects - into an archive using whatever commands are provided by the operating - system. Finally, it is also possible to create a shared library (see - option -shared in the GCC manual). - - @noindent - There are various possibilities for compiling the units that make up the - library: for example with a Makefile @ref{Using the GNU make Utility}, - or with a conventional script. - For simple libraries, it is also possible to create a - dummy main program which depends upon all the packages that comprise the - interface of the library. This dummy main program can then be given to - gnatmake, in order to build all the necessary objects. Here is an example - of such a dummy program and the generic commands used to build an - archive or a shared library. - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - @b{with} My_Lib.Service1; - @b{with} My_Lib.Service2; - @b{with} My_Lib.Service3; - @b{procedure} My_Lib_Dummy @b{is} - @b{begin} - @b{null}; - @b{end}; - - # compiling the library - $ gnatmake -c my_lib_dummy.adb - - # we don't need the dummy object itself - $ rm my_lib_dummy.o my_lib_dummy.ali - - # create an archive with the remaining objects - $ ar rc libmy_lib.a *.o - # some systems may require "ranlib" to be run as well - - # or create a shared library - $ gcc -shared -o libmy_lib.so *.o - # some systems may require the code to have been compiled with -fPIC - @end smallexample - - @noindent - When the objects are grouped in an archive or a shared library, the user - needs to specify the desired library at link time, unless a pragma - linker_options has been used in one of the sources: - @smallexample - @b{pragma} Linker_Options ("-lmy_lib"); - @end smallexample - - @node Installing an Ada Library - @section Installing an Ada Library - - @noindent - In the GNAT model, installing a library consists in copying into a specific - location the files that make up this library. It is possible to install - the sources in a different directory from the other files (ALI, objects, - archives) since the source path and the object path can easily be - specified separately. - - @noindent - For general purpose libraries, it is possible for the system - administrator to put those libraries in the default compiler paths. To - achieve this, he must specify their location in the configuration files - "ada_source_path" and "ada_object_path" that must be located in the GNAT - installation tree at the same place as the gcc spec file. The location of - the gcc spec file can be determined as follows: - @smallexample - $ gcc -v - @end smallexample - - @noindent - The configuration files mentioned above have simple format: each line in them - must contain one unique - directory name. Those names are added to the corresponding path - in their order of appearance in the file. The names can be either absolute - or relative, in the latter case, they are relative to where theses files - are located. - - @noindent - "ada_source_path" and "ada_object_path" might actually not be present in a - GNAT installation, in which case, GNAT will look for its run-time library in - the directories "adainclude" for the sources and "adalib" for the - objects and ALI files. When the files exist, the compiler does not - look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file - must contain the location for the GNAT run-time sources (which can simply - be "adainclude"). In the same way, the "ada_object_path" file must contain - the location for the GNAT run-time objects (which can simply - be "adalib"). - - @noindent - You can also specify a new default path to the runtime library at compilation - time with the switch "--RTS=@var{rts-path}". You can easily choose and change - the runtime you want your program to be compiled with. This switch is - recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref. - - @noindent - It is possible to install a library before or after the standard GNAT - library, by reordering the lines in the configuration files. In general, a - library must be installed before the GNAT library if it redefines any part of it. - - @node Using an Ada Library - @section Using an Ada Library - - @noindent - In order to use a Ada library, you need to make sure that this - library is on both your source and object path - @ref{Search Paths and the Run-Time Library (RTL)} - and @ref{Search Paths for gnatbind}. For - instance, you can use the library "mylib" installed in "/dir/my_lib_src" - and "/dir/my_lib_obj" with the following commands: - - @smallexample - $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \ - -largs -lmy_lib - @end smallexample - - @noindent - This can be simplified down to the following: - @smallexample - $ gnatmake my_appl - @end smallexample - when the following conditions are met: - @itemize @bullet - @item - "/dir/my_lib_src" has been added by the user to the environment - variable "ADA_INCLUDE_PATH", or by the administrator to the file - "ada_source_path" - @item - "/dir/my_lib_obj" has been added by the user to the environment - variable "ADA_OBJECTS_PATH", or by the administrator to the file - "ada_object_path" - @item - a pragma linker_options, as mentioned in @ref{Creating an Ada Library} - as been added to the sources. - @end itemize - @noindent - - @node Creating an Ada Library to be Used in a Non-Ada Context - @section Creating an Ada Library to be Used in a Non-Ada Context - - @noindent - The previous sections detailed how to create and install a library that - was usable from an Ada main program. Using this library in a non-Ada - context is not possible, because the elaboration of the library is - automatically done as part of the main program elaboration. - - GNAT also provides the ability to build libraries that can be used both - in an Ada and non-Ada context. This section describes how to build such - a library, and then how to use it from a C program. The method for - interfacing with the library from other languages such as Fortran for - instance remains the same. - - @subsection Creating the Library - - @itemize @bullet - @item Identify the units representing the interface of the library. - - Here is an example of simple library interface: - - @smallexample - package Interface is - - procedure Do_Something; - - procedure Do_Something_Else; - - end Interface; - @end smallexample - - @item Use @code{pragma Export} or @code{pragma Convention} for the - exported entities. - - Our package @code{Interface} is then updated as follow: - @smallexample - package Interface is - - procedure Do_Something; - pragma Export (C, Do_Something, "do_something"); - - procedure Do_Something_Else; - pragma Export (C, Do_Something_Else, "do_something_else"); - - end Interface; - @end smallexample - - @item Compile all the units composing the library. - - @item Bind the library objects. - - This step is performed by invoking gnatbind with the @code{-L} - switch. @code{gnatbind} will then generate the library elaboration - procedure (named @code{init}) and the run-time finalization - procedure (named @code{final}). - - @smallexample - # generate the binder file in Ada - $ gnatbind -Lmylib interface - - # generate the binder file in C - $ gnatbind -C -Lmylib interface - @end smallexample - - @item Compile the files generated by the binder - - @smallexample - $ gcc -c b~interface.adb - @end smallexample - - @item Create the library; - - The procedure is identical to the procedure explained in - @ref{Creating an Ada Library}, - except that @file{b~interface.o} needs to be added to - the list of objects. - - @smallexample - # create an archive file - $ ar cr libmylib.a b~interface.o - - # create a shared library - $ gcc -shared -o libmylib.so b~interface.o - @end smallexample - - @item Provide a "foreign" view of the library interface; - - The example below shows the content of @code{mylib_interface.h} (note - that there is no rule for the naming of this file, any name can be used) - @smallexample - /* the library elaboration procedure */ - extern void mylibinit (void); - - /* the library finalization procedure */ - extern void mylibfinal (void); - - /* the interface exported by the library */ - extern void do_something (void); - extern void do_something_else (void); - @end smallexample - @end itemize - - @subsection Using the Library - - @noindent - Libraries built as explained above can be used from any program, provided - that the elaboration procedures (named @code{mylibinit} in the previous - example) are called before the library services are used. Any number of - libraries can be used simultaneously, as long as the elaboration - procedure of each library is called. - - Below is an example of C program that uses our @code{mylib} library. - - @smallexample - #include "mylib_interface.h" - - int - main (void) - @{ - /* First, elaborate the library before using it */ - mylibinit (); - - /* Main program, using the library exported entities */ - do_something (); - do_something_else (); - - /* Library finalization at the end of the program */ - mylibfinal (); - return 0; - @} - @end smallexample - - @noindent - Note that this same library can be used from an equivalent Ada main - program. In addition, if the libraries are installed as detailed in - @ref{Installing an Ada Library}, it is not necessary to invoke the - library elaboration and finalization routines. The binder will ensure - that this is done as part of the main program elaboration and - finalization phases. - - @subsection The Finalization Phase - - @noindent - Invoking any library finalization procedure generated by @code{gnatbind} - shuts down the Ada run time permanently. Consequently, the finalization - of all Ada libraries must be performed at the end of the program. No - call to these libraries nor the Ada run time should be made past the - finalization phase. - - @subsection Restrictions in Libraries - - @noindent - The pragmas listed below should be used with caution inside libraries, - as they can create incompatibilities with other Ada libraries: - @itemize @bullet - @item pragma @code{Locking_Policy} - @item pragma @code{Queuing_Policy} - @item pragma @code{Task_Dispatching_Policy} - @item pragma @code{Unreserve_All_Interrupts} - @end itemize - When using a library that contains such pragmas, the user must make sure - that all libraries use the same pragmas with the same values. Otherwise, - a @code{Program_Error} will - be raised during the elaboration of the conflicting - libraries. The usage of these pragmas and its consequences for the user - should therefore be well documented. - - Similarly, the traceback in exception occurrences mechanism should be - enabled or disabled in a consistent manner across all libraries. - Otherwise, a Program_Error will be raised during the elaboration of the - conflicting libraries. - - If the @code{'Version} and @code{'Body_Version} - attributes are used inside a library, then it is necessary to - perform a @code{gnatbind} step that mentions all ali files in all - libraries, so that version identifiers can be properly computed. - In practice these attributes are rarely used, so this is unlikely - to be a consideration. - - @node Rebuilding the GNAT Run-Time Library - @section Rebuilding the GNAT Run-Time Library - - @noindent - It may be useful to recompile the GNAT library in various contexts, the - most important one being the use of partition-wide configuration pragmas - such as Normalize_Scalar. A special Makefile called - @code{Makefile.adalib} is provided to that effect and can be found in - the directory containing the GNAT library. The location of this - directory depends on the way the GNAT environment has been installed and can - be determined by means of the command: - - @smallexample - $ gnatls -v - @end smallexample - - @noindent - The last entry in the object search path usually contains the - gnat library. This Makefile contains its own documentation and in - particular the set of instructions needed to rebuild a new library and - to use it. - - @node Using the GNU make Utility - @chapter Using the GNU @code{make} Utility - @findex make - - @noindent - This chapter offers some examples of makefiles that solve specific - problems. It does not explain how to write a makefile (see the GNU make - documentation), nor does it try to replace the @code{gnatmake} utility - (@pxref{The GNAT Make Program gnatmake}). - - All the examples in this section are specific to the GNU version of - make. Although @code{make} is a standard utility, and the basic language - is the same, these examples use some advanced features found only in - @code{GNU make}. - - @menu - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - @end menu - - @node Using gnatmake in a Makefile - @section Using gnatmake in a Makefile - @findex makefile - @cindex GNU make - - @noindent - Complex project organizations can be handled in a very powerful way by - using GNU make combined with gnatmake. For instance, here is a Makefile - which allows you to build each subsystem of a big project into a separate - shared library. Such a makefile allows you to significantly reduce the link - time of very big applications while maintaining full coherence at - each step of the build process. - - The list of dependencies are handled automatically by - @code{gnatmake}. The Makefile is simply used to call gnatmake in each of - the appropriate directories. - - Note that you should also read the example on how to automatically - create the list of directories (@pxref{Automatically Creating a List of Directories}) - which might help you in case your project has a lot of - subdirectories. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - ## This Makefile is intended to be used with the following directory - ## configuration: - ## - The sources are split into a series of csc (computer software components) - ## Each of these csc is put in its own directory. - ## Their name are referenced by the directory names. - ## They will be compiled into shared library (although this would also work - ## with static libraries - ## - The main program (and possibly other packages that do not belong to any - ## csc is put in the top level directory (where the Makefile is). - ## toplevel_dir __ first_csc (sources) __ lib (will contain the library) - ## \_ second_csc (sources) __ lib (will contain the library) - ## \_ ... - ## Although this Makefile is build for shared library, it is easy to modify - ## to build partial link objects instead (modify the lines with -shared and - ## gnatlink below) - ## - ## With this makefile, you can change any file in the system or add any new - ## file, and everything will be recompiled correctly (only the relevant shared - ## objects will be recompiled, and the main program will be re-linked). - - # The list of computer software component for your project. This might be - # generated automatically. - CSC_LIST=aa bb cc - - # Name of the main program (no extension) - MAIN=main - - # If we need to build objects with -fPIC, uncomment the following line - #NEED_FPIC=-fPIC - - # The following variable should give the directory containing libgnat.so - # You can get this directory through 'gnatls -v'. This is usually the last - # directory in the Object_Path. - GLIB=... - - # The directories for the libraries - # (This macro expands the list of CSC to the list of shared libraries, you - # could simply use the expanded form : - # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so - LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@} - - $@{MAIN@}: objects $@{LIB_DIR@} - gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared - gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@} - - objects:: - # recompile the sources - gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@} - - # Note: In a future version of GNAT, the following commands will be simplified - # by a new tool, gnatmlib - $@{LIB_DIR@}: - mkdir -p $@{dir $@@ @} - cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat - cd $@{dir $@@ @}; cp -f ../*.ali . - - # The dependencies for the modules - # Note that we have to force the expansion of *.o, since in some cases make won't - # be able to do it itself. - aa/lib/libaa.so: $@{wildcard aa/*.o@} - bb/lib/libbb.so: $@{wildcard bb/*.o@} - cc/lib/libcc.so: $@{wildcard cc/*.o@} - - # Make sure all of the shared libraries are in the path before starting the - # program - run:: - LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@} - - clean:: - $@{RM@} -rf $@{CSC_LIST:%=%/lib@} - $@{RM@} $@{CSC_LIST:%=%/*.ali@} - $@{RM@} $@{CSC_LIST:%=%/*.o@} - $@{RM@} *.o *.ali $@{MAIN@} - @end smallexample - - @node Automatically Creating a List of Directories - @section Automatically Creating a List of Directories - - @noindent - In most makefiles, you will have to specify a list of directories, and - store it in a variable. For small projects, it is often easier to - specify each of them by hand, since you then have full control over what - is the proper order for these directories, which ones should be - included... - - However, in larger projects, which might involve hundreds of - subdirectories, it might be more convenient to generate this list - automatically. - - The example below presents two methods. The first one, although less - general, gives you more control over the list. It involves wildcard - characters, that are automatically expanded by @code{make}. Its - shortcoming is that you need to explicitly specify some of the - organization of your project, such as for instance the directory tree - depth, whether some directories are found in a separate tree,... - - The second method is the most general one. It requires an external - program, called @code{find}, which is standard on all Unix systems. All - the directories found under a given root directory will be added to the - list. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # The examples below are based on the following directory hierarchy: - # All the directories can contain any number of files - # ROOT_DIRECTORY -> a -> aa -> aaa - # -> ab - # -> ac - # -> b -> ba -> baa - # -> bb - # -> bc - # This Makefile creates a variable called DIRS, that can be reused any time - # you need this list (see the other examples in this section) - - # The root of your project's directory hierarchy - ROOT_DIRECTORY=. - - #### - # First method: specify explicitly the list of directories - # This allows you to specify any subset of all the directories you need. - #### - - DIRS := a/aa/ a/ab/ b/ba/ - - #### - # Second method: use wildcards - # Note that the argument(s) to wildcard below should end with a '/'. - # Since wildcards also return file names, we have to filter them out - # to avoid duplicate directory names. - # We thus use make's @code{dir} and @code{sort} functions. - # It sets DIRs to the following value (note that the directories aaa and baa - # are not given, unless you change the arguments to wildcard). - # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/ - #### - - DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@} - - #### - # Third method: use an external program - # This command is much faster if run on local disks, avoiding NFS slowdowns. - # This is the most complete command: it sets DIRs to the following value: - # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc - #### - - DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@} - - @end smallexample - - @node Generating the Command Line Switches - @section Generating the Command Line Switches - - @noindent - Once you have created the list of directories as explained in the - previous section (@pxref{Automatically Creating a List of Directories}), - you can easily generate the command line arguments to pass to gnatmake. - - For the sake of completeness, this example assumes that the source path - is not the same as the object path, and that you have two separate lists - of directories. - - @smallexample - # see "Automatically creating a list of directories" to create - # these variables - SOURCE_DIRS= - OBJECT_DIRS= - - GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@} - GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@} - - all: - gnatmake $@{GNATMAKE_SWITCHES@} main_unit - @end smallexample - - @node Overcoming Command Line Length Limits - @section Overcoming Command Line Length Limits - - @noindent - One problem that might be encountered on big projects is that many - operating systems limit the length of the command line. It is thus hard to give - gnatmake the list of source and object directories. - - This example shows how you can set up environment variables, which will - make @code{gnatmake} behave exactly as if the directories had been - specified on the command line, but have a much higher length limit (or - even none on most systems). - - It assumes that you have created a list of directories in your Makefile, - using one of the methods presented in - @ref{Automatically Creating a List of Directories}. - For the sake of completeness, we assume that the object - path (where the ALI files are found) is different from the sources patch. - - Note a small trick in the Makefile below: for efficiency reasons, we - create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are - expanded immediately by @code{make}. This way we overcome the standard - make behavior which is to expand the variables only when they are - actually used. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH. - # This is the same thing as putting the -I arguments on the command line. - # (the equivalent of using -aI on the command line would be to define - # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH). - # You can of course have different values for these variables. - # - # Note also that we need to keep the previous values of these variables, since - # they might have been set before running 'make' to specify where the GNAT - # library is installed. - - # see "Automatically creating a list of directories" to create these - # variables - SOURCE_DIRS= - OBJECT_DIRS= - - empty:= - space:=$@{empty@} $@{empty@} - SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@} - OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@} - ADA_INCLUDE_PATH += $@{SOURCE_LIST@} - ADA_OBJECT_PATH += $@{OBJECT_LIST@} - export ADA_INCLUDE_PATH - export ADA_OBJECT_PATH - - all: - gnatmake main_unit - @end smallexample - - @ifclear vxworks - @node Finding Memory Problems with gnatmem - @chapter Finding Memory Problems with @code{gnatmem} - @findex gnatmem - - @noindent - @code{gnatmem}, is a tool that monitors dynamic allocation and - deallocation activity in a program, and displays information about - incorrect deallocations and possible sources of memory leaks. Gnatmem - provides three type of information: - @itemize @bullet - @item - General information concerning memory management, such as the total - number of allocations and deallocations, the amount of allocated - memory and the high water mark, i.e. the largest amount of allocated - memory in the course of program execution. - - @item - Backtraces for all incorrect deallocations, that is to say deallocations - which do not correspond to a valid allocation. - - @item - Information on each allocation that is potentially the origin of a memory - leak. - @end itemize - - The @code{gnatmem} command has two modes. It can be used with @code{gdb} - or with instrumented allocation and deallocation routines. The later - mode is called the @code{GMEM} mode. Both modes produce the very same - output. - - @menu - * Running gnatmem (GDB Mode):: - * Running gnatmem (GMEM Mode):: - * Switches for gnatmem:: - * Examples of gnatmem Usage:: - * GDB and GMEM Modes:: - * Implementation Note:: - @end menu - - @node Running gnatmem (GDB Mode) - @section Running @code{gnatmem} (GDB Mode) - - @noindent - The @code{gnatmem} command has the form - - @smallexample - $ gnatmem [-q] [n] [-o file] user_program [program_arg]* - or - $ gnatmem [-q] [n] -i file - @end smallexample - - @noindent - Gnatmem must be supplied with the executable to examine, followed by its - run-time inputs. For example, if a program is executed with the command: - @smallexample - $ my_program arg1 arg2 - @end smallexample - then it can be run under @code{gnatmem} control using the command: - @smallexample - $ gnatmem my_program arg1 arg2 - @end smallexample - - The program is transparently executed under the control of the debugger - @ref{The GNAT Debugger GDB}. This does not affect the behavior - of the program, except for sensitive real-time programs. When the program - has completed execution, @code{gnatmem} outputs a report containing general - allocation/deallocation information and potential memory leak. - For better results, the user program should be compiled with - debugging options @ref{Switches for gcc}. - - Here is a simple example of use: - - *************** debut cc - @smallexample - $ gnatmem test_gm - - Global information - ------------------ - Total number of allocations : 45 - Total number of deallocations : 6 - Final Water Mark (non freed mem) : 11.29 Kilobytes - High Water Mark : 11.40 Kilobytes - - . - . - . - Allocation Root # 2 - ------------------- - Number of non freed allocations : 11 - Final Water Mark (non freed mem) : 1.16 Kilobytes - High Water Mark : 1.27 Kilobytes - Backtrace : - test_gm.adb:23 test_gm.alloc - . - . - . - @end smallexample - - The first block of output give general information. In this case, the - Ada construct "@b{new}" was executed 45 times, and only 6 calls to an - unchecked deallocation routine occurred. - - Subsequent paragraphs display information on all allocation roots. - An allocation root is a specific point in the execution of the program - that generates some dynamic allocation, such as a "@b{new}" construct. This - root is represented by an execution backtrace (or subprogram call - stack). By default the backtrace depth for allocations roots is 1, so - that a root corresponds exactly to a source location. The backtrace can - be made deeper, to make the root more specific. - - @node Running gnatmem (GMEM Mode) - @section Running @code{gnatmem} (GMEM Mode) - @cindex @code{GMEM} (@code{gnatmem}) - - @noindent - The @code{gnatmem} command has the form - - @smallexample - $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]* - @end smallexample - - The program must have been linked with the instrumented version of the - allocation and deallocation routines. This is done with linking with the - @file{libgmem.a} library. For better results, the user program should be - compiled with debugging options @ref{Switches for gcc}. For example to - build @file{my_program}: - - @smallexample - $ gnatmake -g my_program -largs -lgmem - @end smallexample - - @noindent - When running @file{my_program} the file @file{gmem.out} is produced. This file - contains information about all allocations and deallocations done by the - program. It is produced by the instrumented allocations and - deallocations routines and will be used by @code{gnatmem}. - - @noindent - Gnatmem must be supplied with the @file{gmem.out} file and the executable to - examine followed by its run-time inputs. For example, if a program is - executed with the command: - @smallexample - $ my_program arg1 arg2 - @end smallexample - then @file{gmem.out} can be analysed by @code{gnatmem} using the command: - @smallexample - $ gnatmem -i gmem.out my_program arg1 arg2 - @end smallexample - - @node Switches for gnatmem - @section Switches for @code{gnatmem} - - @noindent - @code{gnatmem} recognizes the following switches: - - @table @code - - @item @code{-q} - @cindex @code{-q} (@code{gnatmem}) - Quiet. Gives the minimum output needed to identify the origin of the - memory leaks. Omit statistical information. - - @item @code{n} - @cindex @code{n} (@code{gnatmem}) - N is an integer literal (usually between 1 and 10) which controls the - depth of the backtraces defining allocation root. The default value for - N is 1. The deeper the backtrace, the more precise the localization of - the root. Note that the total number of roots can depend on this - parameter. - - @item @code{-o file} - @cindex @code{-o} (@code{gnatmem}) - Direct the gdb output to the specified file. The @code{gdb} script used - to generate this output is also saved in the file @file{gnatmem.tmp}. - - @item @code{-i file} - @cindex @code{-i} (@code{gnatmem}) - Do the @code{gnatmem} processing starting from @file{file} which has - been generated by a previous call to @code{gnatmem} with the -o - switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful - for post mortem processing. - - @end table - - @node Examples of gnatmem Usage - @section Example of @code{gnatmem} Usage - - @noindent - This section is based on the @code{GDB} mode of @code{gnatmem}. The same - results can be achieved using @code{GMEM} mode. See section - @ref{Running gnatmem (GMEM Mode)}. - - @noindent - The first example shows the use of @code{gnatmem} - on a simple leaking program. - Suppose that we have the following Ada program: - - @smallexample - @group - @cartouche - @b{with} Unchecked_Deallocation; - @b{procedure} Test_Gm @b{is} - - @b{type} T @b{is array} (1..1000) @b{of} Integer; - @b{type} Ptr @b{is access} T; - @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr); - A : Ptr; - - @b{procedure} My_Alloc @b{is} - @b{begin} - A := @b{new} T; - @b{end} My_Alloc; - - @b{procedure} My_DeAlloc @b{is} - B : Ptr := A; - @b{begin} - Free (B); - @b{end} My_DeAlloc; - - @b{begin} - My_Alloc; - @b{for} I @b{in} 1 .. 5 @b{loop} - @b{for} J @b{in} I .. 5 @b{loop} - My_Alloc; - @b{end loop}; - My_Dealloc; - @b{end loop}; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - The program needs to be compiled with debugging option: - - @smallexample - $ gnatmake -g test_gm - @end smallexample - - @code{gnatmem} is invoked simply with - @smallexample - $ gnatmem test_gm - @end smallexample - - @noindent - which produces the following output: - - @smallexample - Global information - ------------------ - Total number of allocations : 18 - Total number of deallocations : 5 - Final Water Mark (non freed mem) : 53.00 Kilobytes - High Water Mark : 56.90 Kilobytes - - Allocation Root # 1 - ------------------- - Number of non freed allocations : 11 - Final Water Mark (non freed mem) : 42.97 Kilobytes - High Water Mark : 46.88 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - - Allocation Root # 2 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 10.02 Kilobytes - High Water Mark : 10.02 Kilobytes - Backtrace : - s-secsta.adb:81 system.secondary_stack.ss_init - - Allocation Root # 3 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 12 Bytes - High Water Mark : 12 Bytes - Backtrace : - s-secsta.adb:181 system.secondary_stack.ss_init - @end smallexample - - @noindent - Note that the GNAT run time contains itself a certain number of - allocations that have no corresponding deallocation, - as shown here for root #2 and root - #1. This is a normal behavior when the number of non freed allocations - is one, it locates dynamic data structures that the run time needs for - the complete lifetime of the program. Note also that there is only one - allocation root in the user program with a single line back trace: - test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the - program shows that 'My_Alloc' is called at 2 different points in the - source (line 21 and line 24). If those two allocation roots need to be - distinguished, the backtrace depth parameter can be used: - - @smallexample - $ gnatmem 3 test_gm - @end smallexample - - @noindent - which will give the following output: - - @smallexample - Global information - ------------------ - Total number of allocations : 18 - Total number of deallocations : 5 - Final Water Mark (non freed mem) : 53.00 Kilobytes - High Water Mark : 56.90 Kilobytes - - Allocation Root # 1 - ------------------- - Number of non freed allocations : 10 - Final Water Mark (non freed mem) : 39.06 Kilobytes - High Water Mark : 42.97 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - test_gm.adb:24 test_gm - b_test_gm.c:52 main - - Allocation Root # 2 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 10.02 Kilobytes - High Water Mark : 10.02 Kilobytes - Backtrace : - s-secsta.adb:81 system.secondary_stack.ss_init - s-secsta.adb:283 - b_test_gm.c:33 adainit - - Allocation Root # 3 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 3.91 Kilobytes - High Water Mark : 3.91 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - test_gm.adb:21 test_gm - b_test_gm.c:52 main - - Allocation Root # 4 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 12 Bytes - High Water Mark : 12 Bytes - Backtrace : - s-secsta.adb:181 system.secondary_stack.ss_init - s-secsta.adb:283 - b_test_gm.c:33 adainit - @end smallexample - - @noindent - The allocation root #1 of the first example has been split in 2 roots #1 - and #3 thanks to the more precise associated backtrace. - - @node GDB and GMEM Modes - @section GDB and GMEM Modes - - @noindent - The main advantage of the @code{GMEM} mode is that it is a lot faster than the - @code{GDB} mode where the application must be monitored by a @code{GDB} script. - But the @code{GMEM} mode is available only for DEC Unix, Linux x86, - Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86). - - @noindent - The main advantage of the @code{GDB} mode is that it is available on all - supported platforms. But it can be very slow if the application does a - lot of allocations and deallocations. - - @node Implementation Note - @section Implementation Note - - @menu - * gnatmem Using GDB Mode:: - * gnatmem Using GMEM Mode:: - @end menu - - @node gnatmem Using GDB Mode - @subsection @code{gnatmem} Using @code{GDB} Mode - - @noindent - @code{gnatmem} executes the user program under the control of @code{GDB} using - a script that sets breakpoints and gathers information on each dynamic - allocation and deallocation. The output of the script is then analyzed - by @code{gnatmem} - in order to locate memory leaks and their origin in the - program. Gnatmem works by recording each address returned by the - allocation procedure (@code{__gnat_malloc}) - along with the backtrace at the - allocation point. On each deallocation, the deallocated address is - matched with the corresponding allocation. At the end of the processing, - the unmatched allocations are considered potential leaks. All the - allocations associated with the same backtrace are grouped together and - form an allocation root. The allocation roots are then sorted so that - those with the biggest number of unmatched allocation are printed - first. A delicate aspect of this technique is to distinguish between the - data produced by the user program and the data produced by the gdb - script. Currently, on systems that allow probing the terminal, the gdb - command "tty" is used to force the program output to be redirected to the - current terminal while the @code{gdb} output is directed to a file or to a - pipe in order to be processed subsequently by @code{gnatmem}. - - @node gnatmem Using GMEM Mode - @subsection @code{gnatmem} Using @code{GMEM} Mode - - @noindent - This mode use the same algorithm to detect memory leak as the @code{GDB} - mode of @code{gnatmem}, the only difference is in the way data are - gathered. In @code{GMEM} mode the program is linked with instrumented - version of @code{__gnat_malloc} and @code{__gnat_free} - routines. Information needed to find memory leak are recorded by these - routines in file @file{gmem.out}. This mode also require that the stack - traceback be available, this is only implemented on some platforms - @ref{GDB and GMEM Modes}. - - @end ifclear - @end ifclear - - @node Finding Memory Problems with GNAT Debug Pool - @chapter Finding Memory Problems with GNAT Debug Pool - @findex Debug Pool - @cindex storage, pool, memory corruption - - @noindent - The use of unchecked deallocation and unchecked conversion can easily - lead to incorrect memory references. The problems generated by such - references are usually difficult to tackle because the symptoms can be - very remote from the origin of the problem. In such cases, it is - very helpful to detect the problem as early as possible. This is the - purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. - - @noindent - In order to use the GNAT specific debugging pool, the user must - associate a debug pool object with each of the access types that may be - related to suspected memory problems. See Ada Reference Manual - 13.11. - @smallexample - @b{type} Ptr @b{is} @b{access} Some_Type; - Pool : GNAT.Debug_Pools.Debug_Pool; - @b{for} Ptr'Storage_Pool @b{use} Pool; - @end smallexample - - @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of - pool: the Checked_Pool. Such pools, like standard Ada storage pools, - allow the user to redefine allocation and deallocation strategies. They - also provide a checkpoint for each dereference, through the use of - the primitive operation @code{Dereference} which is implicitly called at - each dereference of an access value. - - Once an access type has been associated with a debug pool, operations on - values of the type may raise four distinct exceptions, - which correspond to four potential kinds of memory corruption: - @itemize @bullet - @item - @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } - @end itemize - - @noindent - For types associated with a Debug_Pool, dynamic allocation is performed using - the standard - GNAT allocation routine. References to all allocated chunks of memory - are kept in an internal dictionary. The deallocation strategy consists - in not releasing the memory to the underlying system but rather to fill - it with a memory pattern easily recognizable during debugging sessions: - The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#. - Upon each dereference, a check is made that the access value denotes a properly - allocated memory location. Here is a complete example of use of - @code{Debug_Pools}, that includes typical instances of memory corruption: - @smallexample - @iftex - @leftskip=0cm - @end iftex - @b{with} Gnat.Io; @b{use} Gnat.Io; - @b{with} Unchecked_Deallocation; - @b{with} Unchecked_Conversion; - @b{with} GNAT.Debug_Pools; - @b{with} System.Storage_Elements; - @b{with} Ada.Exceptions; @b{use} Ada.Exceptions; - @b{procedure} Debug_Pool_Test @b{is} - - @b{type} T @b{is} @b{access} Integer; - @b{type} U @b{is} @b{access} @b{all} T; - - P : GNAT.Debug_Pools.Debug_Pool; - @b{for} T'Storage_Pool @b{use} P; - - @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T); - @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T); - A, B : @b{aliased} T; - - @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line); - - @b{begin} - Info (P); - A := @b{new} Integer; - B := @b{new} Integer; - B := A; - Info (P); - Free (A); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - B := UC(A'Access); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - Info (P); - @b{end} Debug_Pool_Test; - @end smallexample - @noindent - The debug pool mechanism provides the following precise diagnostics on the - execution of this erroneous program: - @smallexample - Debug Pool info: - Total allocated bytes : 0 - Total deallocated bytes : 0 - Current Water Mark: 0 - High Water Mark: 0 - - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 0 - Current Water Mark: 8 - High Water Mark: 8 - - raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 4 - Current Water Mark: 4 - High Water Mark: 8 - - @end smallexample - - @node Creating Sample Bodies Using gnatstub - @chapter Creating Sample Bodies Using @code{gnatstub} - @findex gnatstub - - @noindent - @code{gnatstub} creates body stubs, that is, empty but compilable bodies - for library unit declarations. - - To create a body stub, @code{gnatstub} has to compile the library - unit declaration. Therefore, bodies can be created only for legal - library units. Moreover, if a library unit depends semantically upon - units located outside the current directory, you have to provide - the source search path when calling @code{gnatstub}, see the description - of @code{gnatstub} switches below. - - @menu - * Running gnatstub:: - * Switches for gnatstub:: - @end menu - - @node Running gnatstub - @section Running @code{gnatstub} - - @noindent - @code{gnatstub} has the command-line interface of the form - - @smallexample - $ gnatstub [switches] filename [directory] - @end smallexample - - @noindent - where - @table @code - @item filename - is the name of the source file that contains a library unit declaration - for which a body must be created. This name should follow the GNAT file name - conventions. No crunching is allowed for this file name. The file - name may contain the path information. - - @item directory - indicates the directory to place a body stub (default is the - current directory) - - @item switches - is an optional sequence of switches as described in the next section - @end table - - @node Switches for gnatstub - @section Switches for @code{gnatstub} - - @table @code - - @item ^-f^/FULL^ - If the destination directory already contains a file with a name of the body file - for the argument spec file, replace it with the generated body stub. - - @item ^-hs^/HEADER=SPEC^ - Put the comment header (i.e. all the comments preceding the - compilation unit) from the source of the library unit declaration - into the body stub. - - @item ^-hg^/HEADER=GENERAL^ - Put a sample comment header into the body stub. - - @item -IDIR - @itemx ^-I-^/NOCURRENT_DIRECTORY^ - These switches have the same meaning as in calls to gcc. - They define the source search path in the call to gcc issued - by @code{gnatstub} to compile an argument source file. - - @item ^-i^/INDENTATION=^@var{n} - (@var{n} is a decimal natural number). Set the indentation level in the - generated body sample to n, '^-i0^/INDENTATION=0^' means "no indentation", - the default indentation is 3. - - @item ^-k^/TREE_FILE=SAVE^ - Do not remove the tree file (i.e. the snapshot of the compiler internal - structures used by @code{gnatstub}) after creating the body stub. - - @item ^-l^/LINE_LENGTH=^@var{n} - (@var{n} is a decimal positive number) Set the maximum line length in the - body stub to n, the default is 78. - - @item ^-q^/QUIET^ - Quiet mode: do not generate a confirmation when a body is - successfully created or a message when a body is not required for an - argument unit. - - @item ^-r^/TREE_FILE=REUSE^ - Reuse the tree file (if it exists) instead of creating it: instead of - creating the tree file for the library unit declaration, gnatstub - tries to find it in the current directory and use it for creating - a body. If the tree file is not found, no body is created. @code{^-r^/REUSE^} - also implies @code{^-k^/SAVE^}, whether or not - @code{^-k^/SAVE^} is set explicitly. - - @item ^-t^/TREE_FILE=OVERWRITE^ - Overwrite the existing tree file: if the current directory already - contains the file which, according to the GNAT file name rules should - be considered as a tree file for the argument source file, gnatstub - will refuse to create the tree file needed to create a body sampler, - unless @code{-t} option is set - - @item ^-v^/VERBOSE^ - Verbose mode: generate version information. - - @end table - - @node Reducing the Size of Ada Executables with gnatelim - @chapter Reducing the Size of Ada Executables with @code{gnatelim} - @findex gnatelim - - @menu - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - @end menu - - @node About gnatelim - @section About @code{gnatelim} - - @noindent - When a program shares a set of Ada - packages with other programs, it may happen that this program uses - only a fraction of the subprograms defined in these packages. The code - created for these unused subprograms increases the size of the executable. - - @code{gnatelim} tracks unused subprograms in an Ada program and - outputs a list of GNAT-specific @code{Eliminate} pragmas (see next - section) marking all the subprograms that are declared but never called. - By placing the list of @code{Eliminate} pragmas in the GNAT configuration - file @file{gnat.adc} and recompiling your program, you may decrease the - size of its executable, because the compiler will not generate the code - for 'eliminated' subprograms. - - @code{gnatelim} needs as its input data a set of tree files - (see @ref{Tree Files}) representing all the components of a program to - process and a bind file for a main subprogram (see - @ref{Preparing Tree and Bind Files for gnatelim}). - - @node Eliminate Pragma - @section @code{Eliminate} Pragma - @findex Eliminate - - @noindent - The simplified syntax of the Eliminate pragma used by @code{gnatelim} is: - - @smallexample - @cartouche - @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name); - @end cartouche - @end smallexample - - @noindent - where - @table @code - @item Library_Unit_Name - full expanded Ada name of a library unit - - @item Subprogram_Name - a simple or expanded name of a subprogram declared within this - compilation unit - - @end table - - @noindent - The effect of an @code{Eliminate} pragma placed in the GNAT configuration - file @file{gnat.adc} is: - - @itemize @bullet - - @item - If the subprogram @code{Subprogram_Name} is declared within - the library unit @code{Library_Unit_Name}, the compiler will not generate - code for this subprogram. This applies to all overloaded subprograms denoted - by @code{Subprogram_Name}. - - @item - If a subprogram marked by the pragma @code{Eliminate} is used (called) - in a program, the compiler will produce an error message in the place where - it is called. - @end itemize - - @node Tree Files - @section Tree Files - @cindex Tree file - - @noindent - A tree file stores a snapshot of the compiler internal data - structures at the very end of a successful compilation. It contains all the - syntactic and semantic information for the compiled unit and all the - units upon which it depends semantically. - To use tools that make use of tree files, you - need to first produce the right set of tree files. - - GNAT produces correct tree files when -gnatt -gnatc options are set - in a gcc call. The tree files have an .adt extension. - Therefore, to produce a tree file for the compilation unit contained in a file - named @file{foo.adb}, you must use the command - - @smallexample - $ gcc -c -gnatc -gnatt foo.adb - @end smallexample - - @noindent - and you will get the tree file @file{foo.adt}. - compilation. - - @node Preparing Tree and Bind Files for gnatelim - @section Preparing Tree and Bind Files for @code{gnatelim} - - @noindent - A set of tree files covering the program to be analyzed with - @code{gnatelim} and - the bind file for the main subprogram does not have to - be in the current directory. - '-T' gnatelim option may be used to provide - the search path for tree files, and '-b' - option may be used to point to the bind - file to process (see @ref{Running gnatelim}) - - If you do not have the appropriate set of tree - files and the right bind file, you - may create them in the current directory using the following procedure. - - Let @code{Main_Prog} be the name of a main subprogram, and suppose - this subprogram is in a file named @file{main_prog.adb}. - - To create a bind file for @code{gnatelim}, run @code{gnatbind} for - the main subprogram. @code{gnatelim} can work with both Ada and C - bind files; when both are present, it uses the Ada bind file. - The following commands will build the program and create the bind file: - - @smallexample - $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^ - $ gnatbind main_prog - @end smallexample - - @noindent - To create a minimal set of tree files covering the whole program, call - @code{gnatmake} for this program as follows: - - @smallexample - @ifset vms - $ GNAT MAKE /FORCE_COMPILE /ACTIONS=COMPILE /NOLOAD /TREE_OUTPUT MAIN_PROG - @end ifset - @ifclear vms - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end ifclear - @end smallexample - - @noindent - The @code{^-c^/ACTIONS=COMPILE^} gnatmake option turns off the bind and link - steps, that are useless anyway because the sources are compiled with - @option{-gnatc} option which turns off code generation. - - The @code{^-f^/FORCE_COMPILE^} gnatmake option forces - recompilation of all the needed sources. - - This sequence of actions will create all the data needed by @code{gnatelim} - from scratch and therefore guarantee its consistency. If you would like to - use some existing set of files as @code{gnatelim} output, you must make - sure that the set of files is complete and consistent. You can use the - @code{-m} switch to check if there are missed tree files - - Note, that @code{gnatelim} needs neither object nor ALI files. - - @node Running gnatelim - @section Running @code{gnatelim} - - @noindent - @code{gnatelim} has the following command-line interface: - - @smallexample - $ gnatelim [options] name - @end smallexample - - @noindent - @code{name} should be a full expanded Ada name of a main subprogram - of a program (partition). - - @code{gnatelim} options: - - @table @code - @item ^-q^/QUIET^ - Quiet mode: by default @code{gnatelim} generates to the standard error - stream a trace of the source file names of the compilation units being - processed. This option turns this trace off. - - @item ^-v^/VERBOSE^ - Verbose mode: @code{gnatelim} version information is printed as Ada - comments to the standard output stream. - - @item ^-a^/ALL^ - Also look for subprograms from the GNAT run time that can be eliminated. - - @item ^-m^/MISSED^ - Check if any tree files are missing for an accurate result. - - @item ^-T^/TREE_DIRS=^@var{dir} - When looking for tree files also look in directory @var{dir} - - @item ^-b^/BIND_FILE=^@var{bind_file} - Specifies @var{bind_file} as the bind file to process. If not set, the name - of the bind file is computed from the full expanded Ada name of a main subprogram. - - @item -d@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - mode desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Gnatelim.Options} unit in the compiler - source file @file{gnatelim-options.adb}. - @end table - - @noindent - @code{gnatelim} sends its output to the standard output stream, and all the - tracing and debug information is sent to the standard error stream. - In order to produce a proper GNAT configuration file - @file{gnat.adc}, redirection must be used: - - @smallexample - @ifset vms - $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC - @end ifset - @ifclear vms - $ gnatelim Main_Prog > gnat.adc - @end ifclear - @end smallexample - - @ifclear vms - @noindent - or - - @smallexample - $ gnatelim Main_Prog >> gnat.adc - @end smallexample - @end ifclear - - @noindent - In order to append the @code{gnatelim} output to the existing contents of - @file{gnat.adc}. - - @node Correcting the List of Eliminate Pragmas - @section Correcting the List of Eliminate Pragmas - - @noindent - In some rare cases it may happen that @code{gnatelim} will try to eliminate - subprograms which are actually called in the program. In this case, the - compiler will generate an error message of the form: - - @smallexample - file.adb:106:07: cannot call eliminated subprogram "My_Prog" - @end smallexample - - @noindent - You will need to manually remove the wrong @code{Eliminate} pragmas from - the @file{gnat.adc} file. It is advised that you recompile your program - from scratch after that because you need a consistent @file{gnat.adc} file - during the entire compilation. - - @node Making Your Executables Smaller - @section Making Your Executables Smaller - - @noindent - In order to get a smaller executable for your program you now have to - recompile the program completely with the new @file{gnat.adc} file - created by @code{gnatelim} in your current directory: - - @smallexample - $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^ - @end smallexample - - @noindent - (you will need @code{^-f^/FORCE_COMPILE^} option for gnatmake to - recompile everything - with the set of pragmas @code{Eliminate} you have obtained with - @code{gnatelim}). - - Be aware that the set of @code{Eliminate} pragmas is specific to each - program. It is not recommended to merge sets of @code{Eliminate} - pragmas created for different programs in one @file{gnat.adc} file. - - @node Summary of the gnatelim Usage Cycle - @section Summary of the gnatelim Usage Cycle - - @noindent - Here is a quick summary of the steps to be taken in order to reduce - the size of your executables with @code{gnatelim}. You may use - other GNAT options to control the optimization level, - to produce the debugging information, to set search path, etc. - - @enumerate - @item - Produce a bind file and a set of tree files - - @smallexample - $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^ - $ gnatbind main_prog - @ifset vms - $ GNAT MAKE /FORCE_COMPILE /NO_LINK /NOLOAD /TREE_OUTPUT MAIN_PROG - @end ifset - @ifclear vms - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end ifclear - @end smallexample - - @item - Generate a list of @code{Eliminate} pragmas - @smallexample - @ifset vms - $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC - @end ifset - @ifclear vms - $ gnatelim Main_Prog >[>] gnat.adc - @end ifclear - @end smallexample - - @item - Recompile the application - - @smallexample - $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^ - @end smallexample - - @end enumerate - - @node Other Utility Programs - @chapter Other Utility Programs - - @noindent - This chapter discusses some other utility programs available in the Ada - environment. - - @menu - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - * Installing gnathtml:: - @ifset vms - * LSE:: - * Profiling:: - @end ifset - @end menu - - @node Using Other Utility Programs with GNAT - @section Using Other Utility Programs with GNAT - - @noindent - The object files generated by GNAT are in standard system format and in - particular the debugging information uses this format. This means - programs generated by GNAT can be used with existing utilities that - depend on these formats. - - @ifclear vms - In general, any utility program that works with C will also often work with - Ada programs generated by GNAT. This includes software utilities such as - gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such - as Purify. - @end ifclear - - @node The gnatpsta Utility Program - @section The @code{gnatpsta} Utility Program - - @noindent - Many of the definitions in package Standard are implementation-dependent. - However, the source of this package does not exist as an Ada source - file, so these values cannot be determined by inspecting the source. - They can be determined by examining in detail the coding of - @file{cstand.adb} which creates the image of Standard in the compiler, - but this is awkward and requires a great deal of internal knowledge - about the system. - - The @code{gnatpsta} utility is designed to deal with this situation. - It is an Ada program that dynamically determines the - values of all the relevant parameters in Standard, and prints them - out in the form of an Ada source listing for Standard, displaying all - the values of interest. This output is generated to - @file{stdout}. - - To determine the value of any parameter in package Standard, simply - run @code{gnatpsta} with no qualifiers or arguments, and examine - the output. This is preferable to consulting documentation, because - you know that the values you are getting are the actual ones provided - by the executing system. - - @node The External Symbol Naming Scheme of GNAT - @section The External Symbol Naming Scheme of GNAT - - @noindent - In order to interpret the output from GNAT, when using tools that are - originally intended for use with other languages, it is useful to - understand the conventions used to generate link names from the Ada - entity names. - - All link names are in all lowercase letters. With the exception of library - procedure names, the mechanism used is simply to use the full expanded - Ada name with dots replaced by double underscores. For example, suppose - we have the following package spec: - - @smallexample - @group - @cartouche - @b{package} QRS @b{is} - MN : Integer; - @b{end} QRS; - @end cartouche - @end group - @end smallexample - - @noindent - The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so - the corresponding link name is @code{qrs__mn}. - @findex Export - Of course if a @code{pragma Export} is used this may be overridden: - - @smallexample - @group - @cartouche - @b{package} Exports @b{is} - Var1 : Integer; - @b{pragma} Export (Var1, C, External_Name => "var1_name"); - Var2 : Integer; - @b{pragma} Export (Var2, C, Link_Name => "var2_link_name"); - @b{end} Exports; - @end cartouche - @end group - @end smallexample - - @noindent - In this case, the link name for @var{Var1} is whatever link name the - C compiler would assign for the C function @var{var1_name}. This typically - would be either @var{var1_name} or @var{_var1_name}, depending on operating - system conventions, but other possibilities exist. The link name for - @var{Var2} is @var{var2_link_name}, and this is not operating system - dependent. - - @findex _main - One exception occurs for library level procedures. A potential ambiguity - arises between the required name @code{_main} for the C main program, - and the name we would otherwise assign to an Ada library level procedure - called @code{Main} (which might well not be the main program). - - To avoid this ambiguity, we attach the prefix @code{_ada_} to such - names. So if we have a library level procedure such as - - @smallexample - @group - @cartouche - @b{procedure} Hello (S : String); - @end cartouche - @end group - @end smallexample - - @noindent - the external name of this procedure will be @var{_ada_hello}. - - @node Ada Mode for Glide - @section Ada Mode for @code{Glide} - - @noindent - The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the - user in understanding existing code and facilitates writing new code. It - furthermore provides some utility functions for easier integration of - standard Emacs features when programming in Ada. - - @subsection General Features: - - @itemize @bullet - @item - Full Integrated Development Environment : - - @itemize @bullet - @item - support of 'project files' for the configuration (directories, - compilation options,...) - - @item - compiling and stepping through error messages. - - @item - running and debugging your applications within Glide. - @end itemize - - @item - easy to use for beginners by pull-down menus, - - @item - user configurable by many user-option variables. - @end itemize - - @subsection Ada Mode Features That Help Understanding Code: - - @itemize @bullet - @item - functions for easy and quick stepping through Ada code, - - @item - getting cross reference information for identifiers (e.g. find the - defining place by a keystroke), - - @item - displaying an index menu of types and subprograms and move point to - the chosen one, - - @item - automatic color highlighting of the various entities in Ada code. - @end itemize - - @subsection Glide Support for Writing Ada Code: - - @itemize @bullet - @item - switching between spec and body files with possible - autogeneration of body files, - - @item - automatic formating of subprograms parameter lists. - - @item - automatic smart indentation according to Ada syntax, - - @item - automatic completion of identifiers, - - @item - automatic casing of identifiers, keywords, and attributes, - - @item - insertion of statement templates, - - @item - filling comment paragraphs like filling normal text, - @end itemize - - For more information, please refer to the online Glide documentation - available in the Glide --> Help Menu. - - @node Converting Ada Files to html with gnathtml - @section Converting Ada Files to html with @code{gnathtml} - - @noindent - This @code{Perl} script allows Ada source files to be browsed using - standard Web browsers. For installation procedure, see the section - @xref{Installing gnathtml}. - - Ada reserved keywords are highlighted in a bold font and Ada comments in - a blue font. Unless your program was compiled with the gcc @option{-gnatx} - switch to suppress the generation of cross-referencing information, user - defined variables and types will appear in a different color; you will - be able to click on any identifier and go to its declaration. - - The command line is as follow: - @smallexample - $ perl gnathtml.pl [switches] ada-files - @end smallexample - - You can pass it as many Ada files as you want. @code{gnathtml} will generate - an html file for every ada file, and a global file called @file{index.htm}. - This file is an index of every identifier defined in the files. - - The available switches are the following ones : - - @table @code - @item -83 - @cindex @code{-83} (@code{gnathtml}) - Only the subset on the Ada 83 keywords will be highlighted, not the full - Ada 95 keywords set. - - @item -cc @var{color} - This option allows you to change the color used for comments. The default - value is green. The color argument can be any name accepted by html. - - @item -d - @cindex @code{-d} (@code{gnathtml}) - If the ada files depend on some other files (using for instance the - @code{with} command, the latter will also be converted to html. - Only the files in the user project will be converted to html, not the files - in the run-time library itself. - - @item -D - This command is the same as -d above, but @code{gnathtml} will also look - for files in the run-time library, and generate html files for them. - - @item -f - @cindex @code{-f} (@code{gnathtml}) - By default, gnathtml will generate html links only for global entities - ('with'ed units, global variables and types,...). If you specify the - @code{-f} on the command line, then links will be generated for local - entities too. - - @item -l @var{number} - @cindex @code{-l} (@code{gnathtml}) - If this switch is provided and @var{number} is not 0, then @code{gnathtml} - will number the html files every @var{number} line. - - @item -I @var{dir} - @cindex @code{-I} (@code{gnathtml}) - Specify a directory to search for library files (@file{.ali} files) and - source files. You can provide several -I switches on the command line, - and the directories will be parsed in the order of the command line. - - @item -o @var{dir} - @cindex @code{-o} (@code{gnathtml}) - Specify the output directory for html files. By default, gnathtml will - saved the generated html files in a subdirectory named @file{html/}. - - @item -p @var{file} - @cindex @code{-p} (@code{gnathtml}) - If you are using Emacs and the most recent Emacs Ada mode, which provides - a full Integrated Development Environment for compiling, checking, - running and debugging applications, you may be using @file{.adp} files - to give the directories where Emacs can find sources and object files. - - Using this switch, you can tell gnathtml to use these files. This allows - you to get an html version of your application, even if it is spread - over multiple directories. - - @item -sc @var{color} - @cindex @code{-sc} (@code{gnathtml}) - This option allows you to change the color used for symbol definitions. - The default value is red. The color argument can be any name accepted by html. - - @item -t @var{file} - @cindex @code{-t} (@code{gnathtml}) - This switch provides the name of a file. This file contains a list of - file names to be converted, and the effect is exactly as though they had - appeared explicitly on the command line. This - is the recommended way to work around the command line length limit on some - systems. - - @end table - - @node Installing gnathtml - @section Installing @code{gnathtml} - - @noindent - @code{Perl} needs to be installed on your machine to run this script. - @code{Perl} is freely available for almost every architecture and - Operating System via the Internet. - - On Unix systems, you may want to modify the first line of the script - @code{gnathtml}, to explicitly tell the Operating system where Perl - is. The syntax of this line is : - @smallexample - #!full_path_name_to_perl - @end smallexample - - @noindent - Alternatively, you may run the script using the following command line: - - @smallexample - $ perl gnathtml.pl [switches] files - @end smallexample - - @ifset vms - @node LSE - @section LSE - @findex LSE - - @noindent - The GNAT distribution provides an Ada 95 template for the Digital Language - Sensitive Editor (LSE), a component of DECset. In order to - access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV. - - @node Profiling - @section Profiling - @findex PCA - - @noindent - GNAT supports The Digital Performance Coverage Analyzer (PCA), a component - of DECset. To use it proceed as outlined under "HELP PCA", except for running - the collection phase with the /DEBUG qualifier. - - @smallexample - $ GNAT MAKE /DEBUG - $ DEFINE LIB$DEBUG PCA$COLLECTOR - $ RUN/DEBUG - @end smallexample - @noindent - @end ifset - - @node Running and Debugging Ada Programs - @chapter Running and Debugging Ada Programs - @cindex Debugging - - @noindent - This chapter discusses how to debug Ada programs. An incorrect Ada program - may be handled in three ways by the GNAT compiler: - - @enumerate - @item - The illegality may be a violation of the static semantics of Ada. In - that case GNAT diagnoses the constructs in the program that are illegal. - It is then a straightforward matter for the user to modify those parts of - the program. - - @item - The illegality may be a violation of the dynamic semantics of Ada. In - that case the program compiles and executes, but may generate incorrect - results, or may terminate abnormally with some exception. - - @item - When presented with a program that contains convoluted errors, GNAT - itself may terminate abnormally without providing full diagnostics on - the incorrect user program. - @end enumerate - - @menu - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - @end menu - - @cindex Debugger - @findex gdb - - @node The GNAT Debugger GDB - @section The GNAT Debugger GDB - - @noindent - @code{GDB} is a general purpose, platform-independent debugger that - can be used to debug mixed-language programs compiled with @code{GCC}, - and in particular is capable of debugging Ada programs compiled with - GNAT. The latest versions of @code{GDB} are Ada-aware and can handle - complex Ada data structures. - - The manual @cite{Debugging with GDB} - @ifset vms - , located in the GNU:[DOCS] directory, - @end ifset - contains full details on the usage of @code{GDB}, including a section on - its usage on programs. This manual should be consulted for full - details. The section that follows is a brief introduction to the - philosophy and use of @code{GDB}. - - When GNAT programs are compiled, the compiler optionally writes debugging - information into the generated object file, including information on - line numbers, and on declared types and variables. This information is - separate from the generated code. It makes the object files considerably - larger, but it does not add to the size of the actual executable that - will be loaded into memory, and has no impact on run-time performance. The - generation of debug information is triggered by the use of the - ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out - the compilations. It is important to emphasize that the use of these - options does not change the generated code. - - The debugging information is written in standard system formats that - are used by many tools, including debuggers and profilers. The format - of the information is typically designed to describe C types and - semantics, but GNAT implements a translation scheme which allows full - details about Ada types and variables to be encoded into these - standard C formats. Details of this encoding scheme may be found in - the file exp_dbug.ads in the GNAT source distribution. However, the - details of this encoding are, in general, of no interest to a user, - since @code{GDB} automatically performs the necessary decoding. - - When a program is bound and linked, the debugging information is - collected from the object files, and stored in the executable image of - the program. Again, this process significantly increases the size of - the generated executable file, but it does not increase the size of - the executable program itself. Furthermore, if this program is run in - the normal manner, it runs exactly as if the debug information were - not present, and takes no more actual memory. - - However, if the program is run under control of @code{GDB}, the - debugger is activated. The image of the program is loaded, at which - point it is ready to run. If a run command is given, then the program - will run exactly as it would have if @code{GDB} were not present. This - is a crucial part of the @code{GDB} design philosophy. @code{GDB} is - entirely non-intrusive until a breakpoint is encountered. If no - breakpoint is ever hit, the program will run exactly as it would if no - debugger were present. When a breakpoint is hit, @code{GDB} accesses - the debugging information and can respond to user commands to inspect - variables, and more generally to report on the state of execution. - - @node Running GDB - @section Running GDB - - @ifclear vxworks - @noindent - The debugger can be launched directly and simply from @code{glide} or - through its graphical interface: @code{gvd}. It can also be used - directly in text mode. Here is described the basic use of @code{GDB} - in text mode. All the commands described below can be used in the - @code{gvd} console window eventhough there is usually other more - graphical ways to achieve the same goals. - - @ifclear vms - @noindent - The command to run de graphical interface of the debugger is - @smallexample - $ gvd program - @end smallexample - @end ifclear - - @noindent - The command to run @code{GDB} in text mode is - - @smallexample - $ ^gdb program^$ GDB PROGRAM^ - @end smallexample - - @noindent - where @code{^program^PROGRAM^} is the name of the executable file. This - activates the debugger and results in a prompt for debugger commands. - The simplest command is simply @code{run}, which causes the program to run - exactly as if the debugger were not present. The following section - describes some of the additional commands that can be given to @code{GDB}. - @end ifclear - - @ifset vxworks - Please refer to the debugging section of the chapter specific to your - cross environment at the end of this manual. - @end ifset - - @node Introduction to GDB Commands - @section Introduction to GDB Commands - - @noindent - @code{GDB} contains a large repertoire of commands. The manual - @cite{Debugging with GDB} - @ifset vms - , located in the GNU:[DOCS] directory, - @end ifset - includes extensive documentation on the use - of these commands, together with examples of their use. Furthermore, - the command @var{help} invoked from within @code{GDB} activates a simple help - facility which summarizes the available commands and their options. - In this section we summarize a few of the most commonly - used commands to give an idea of what @code{GDB} is about. You should create - a simple program with debugging information and experiment with the use of - these @code{GDB} commands on the program as you read through the - following section. - - @table @code - @item set args @var{arguments} - The @var{arguments} list above is a list of arguments to be passed to - the program on a subsequent run command, just as though the arguments - had been entered on a normal invocation of the program. The @code{set args} - command is not needed if the program does not require arguments. - - @item run - The @code{run} command causes execution of the program to start from - the beginning. If the program is already running, that is to say if - you are currently positioned at a breakpoint, then a prompt will ask - for confirmation that you want to abandon the current execution and - restart. - - @item breakpoint @var{location} - The breakpoint command sets a breakpoint, that is to say a point at which - execution will halt and @code{GDB} will await further - commands. @var{location} is - either a line number within a file, given in the format @code{file:linenumber}, - or it is the name of a subprogram. If you request that a breakpoint be set on - a subprogram that is overloaded, a prompt will ask you to specify on which of - those subprograms you want to breakpoint. You can also - specify that all of them should be breakpointed. If the program is run - and execution encounters the breakpoint, then the program - stops and @code{GDB} signals that the breakpoint was encountered by - printing the line of code before which the program is halted. - - @item breakpoint exception @var{name} - A special form of the breakpoint command which breakpoints whenever - exception @var{name} is raised. - If @var{name} is omitted, - then a breakpoint will occur when any exception is raised. - - @item print @var{expression} - This will print the value of the given expression. Most simple - Ada expression formats are properly handled by @code{GDB}, so the expression - can contain function calls, variables, operators, and attribute references. - - @item continue - Continues execution following a breakpoint, until the next breakpoint or the - termination of the program. - - @item step - Executes a single line after a breakpoint. If the next statement is a subprogram - call, execution continues into (the first statement of) the - called subprogram. - - @item next - Executes a single line. If this line is a subprogram call, executes and - returns from the call. - - @item list - Lists a few lines around the current source location. In practice, it - is usually more convenient to have a separate edit window open with the - relevant source file displayed. Successive applications of this command - print subsequent lines. The command can be given an argument which is a - line number, in which case it displays a few lines around the specified one. - - @item backtrace - Displays a backtrace of the call chain. This command is typically - used after a breakpoint has occurred, to examine the sequence of calls that - leads to the current breakpoint. The display includes one line for each - activation record (frame) corresponding to an active subprogram. - - @item up - At a breakpoint, @code{GDB} can display the values of variables local - to the current frame. The command @code{up} can be used to - examine the contents of other active frames, by moving the focus up - the stack, that is to say from callee to caller, one frame at a time. - - @item down - Moves the focus of @code{GDB} down from the frame currently being - examined to the frame of its callee (the reverse of the previous command), - - @item frame @var{n} - Inspect the frame with the given number. The value 0 denotes the frame - of the current breakpoint, that is to say the top of the call stack. - - @end table - - The above list is a very short introduction to the commands that - @code{GDB} provides. Important additional capabilities, including conditional - breakpoints, the ability to execute command sequences on a breakpoint, - the ability to debug at the machine instruction level and many other - features are described in detail in @cite{Debugging with GDB}. - Note that most commands can be abbreviated - (for example, c for continue, bt for backtrace). - - @node Using Ada Expressions - @section Using Ada Expressions - @cindex Ada expressions - - @noindent - @code{GDB} supports a fairly large subset of Ada expression syntax, with some - extensions. The philosophy behind the design of this subset is - - @itemize @bullet - @item - That @code{GDB} should provide basic literals and access to operations for - arithmetic, dereferencing, field selection, indexing, and subprogram calls, - leaving more sophisticated computations to subprograms written into the - program (which therefore may be called from @code{GDB}). - - @item - That type safety and strict adherence to Ada language restrictions - are not particularly important to the @code{GDB} user. - - @item - That brevity is important to the @code{GDB} user. - @end itemize - - Thus, for brevity, the debugger acts as if there were - implicit @code{with} and @code{use} clauses in effect for all user-written - packages, thus making it unnecessary to fully qualify most names with - their packages, regardless of context. Where this causes ambiguity, - @code{GDB} asks the user's intent. - - For details on the supported Ada syntax, see @cite{Debugging with GDB}. - - @node Calling User-Defined Subprograms - @section Calling User-Defined Subprograms - - @noindent - An important capability of @code{GDB} is the ability to call user-defined - subprograms while debugging. This is achieved simply by entering - a subprogram call statement in the form: - - @smallexample - call subprogram-name (parameters) - @end smallexample - - @noindent - The keyword @code{call} can be omitted in the normal case where the - @code{subprogram-name} does not coincide with any of the predefined - @code{GDB} commands. - - The effect is to invoke the given subprogram, passing it the - list of parameters that is supplied. The parameters can be expressions and - can include variables from the program being debugged. The - subprogram must be defined - at the library level within your program, and @code{GDB} will call the - subprogram within the environment of your program execution (which - means that the subprogram is free to access or even modify variables - within your program). - - The most important use of this facility is in allowing the inclusion of - debugging routines that are tailored to particular data structures - in your program. Such debugging routines can be written to provide a suitably - high-level description of an abstract type, rather than a low-level dump - of its physical layout. After all, the standard - @code{GDB print} command only knows the physical layout of your - types, not their abstract meaning. Debugging routines can provide information - at the desired semantic level and are thus enormously useful. - - For example, when debugging GNAT itself, it is crucial to have access to - the contents of the tree nodes used to represent the program internally. - But tree nodes are represented simply by an integer value (which in turn - is an index into a table of nodes). - Using the @code{print} command on a tree node would simply print this integer - value, which is not very useful. But the PN routine (defined in file - treepr.adb in the GNAT sources) takes a tree node as input, and displays - a useful high level representation of the tree node, which includes the - syntactic category of the node, its position in the source, the integers - that denote descendant nodes and parent node, as well as varied - semantic information. To study this example in more detail, you might want to - look at the body of the PN procedure in the stated file. - - @node Using the Next Command in a Function - @section Using the Next Command in a Function - - @noindent - When you use the @code{next} command in a function, the current source - location will advance to the next statement as usual. A special case - arises in the case of a @code{return} statement. - - Part of the code for a return statement is the "epilog" of the function. - This is the code that returns to the caller. There is only one copy of - this epilog code, and it is typically associated with the last return - statement in the function if there is more than one return. In some - implementations, this epilog is associated with the first statement - of the function. - - The result is that if you use the @code{next} command from a return - statement that is not the last return statement of the function you - may see a strange apparent jump to the last return statement or to - the start of the function. You should simply ignore this odd jump. - The value returned is always that from the first return statement - that was stepped through. - - @node Ada Exceptions - @section Breaking on Ada Exceptions - @cindex Exceptions - - @noindent - You can set breakpoints that trip when your program raises - selected exceptions. - - @table @code - @item break exception - Set a breakpoint that trips whenever (any task in the) program raises - any exception. - - @item break exception @var{name} - Set a breakpoint that trips whenever (any task in the) program raises - the exception @var{name}. - - @item break exception unhandled - Set a breakpoint that trips whenever (any task in the) program raises an - exception for which there is no handler. - - @item info exceptions - @itemx info exceptions @var{regexp} - The @code{info exceptions} command permits the user to examine all defined - exceptions within Ada programs. With a regular expression, @var{regexp}, as - argument, prints out only those exceptions whose name matches @var{regexp}. - @end table - - @node Ada Tasks - @section Ada Tasks - @cindex Tasks - - @noindent - @code{GDB} allows the following task-related commands: - - @table @code - @item info tasks - This command shows a list of current Ada tasks, as in the following example: - - @smallexample - @iftex - @leftskip=0cm - @end iftex - (gdb) info tasks - ID TID P-ID Thread Pri State Name - 1 8088000 0 807e000 15 Child Activation Wait main_task - 2 80a4000 1 80ae000 15 Accept/Select Wait b - 3 809a800 1 80a4800 15 Child Activation Wait a - * 4 80ae800 3 80b8000 15 Running c - @end smallexample - - @noindent - In this listing, the asterisk before the first task indicates it to be the - currently running task. The first column lists the task ID that is used - to refer to tasks in the following commands. - - @item break @var{linespec} task @var{taskid} - @itemx break @var{linespec} task @var{taskid} if @dots{} - @cindex Breakpoints and tasks - These commands are like the @code{break @dots{} thread @dots{}}. - @var{linespec} specifies source lines. - - Use the qualifier @samp{task @var{taskid}} with a breakpoint command - to specify that you only want @code{GDB} to stop the program when a - particular Ada task reaches this breakpoint. @var{taskid} is one of the - numeric task identifiers assigned by @code{GDB}, shown in the first - column of the @samp{info tasks} display. - - If you do not specify @samp{task @var{taskid}} when you set a - breakpoint, the breakpoint applies to @emph{all} tasks of your - program. - - You can use the @code{task} qualifier on conditional breakpoints as - well; in this case, place @samp{task @var{taskid}} before the - breakpoint condition (before the @code{if}). - - @item task @var{taskno} - @cindex Task switching - - This command allows to switch to the task referred by @var{taskno}. In - particular, This allows to browse the backtrace of the specified - task. It is advised to switch back to the original task before - continuing execution otherwise the scheduling of the program may be - perturbated. - @end table - - @noindent - For more detailed information on the tasking support, see @cite{Debugging with GDB}. - - @node Debugging Generic Units - @section Debugging Generic Units - @cindex Debugging Generic Units - @cindex Generics - - @noindent - GNAT always uses code expansion for generic instantiation. This means that - each time an instantiation occurs, a complete copy of the original code is - made, with appropriate substitutions of formals by actuals. - - It is not possible to refer to the original generic entities in - @code{GDB}, but it is always possible to debug a particular instance of - a generic, by using the appropriate expanded names. For example, if we have - - @smallexample - @group - @cartouche - @b{procedure} g @b{is} - - @b{generic package} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer); - @b{end} k; - - @b{package body} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer) @b{is} - @b{begin} - v1 := v1 + 1; - @b{end} kp; - @b{end} k; - - @b{package} k1 @b{is new} k; - @b{package} k2 @b{is new} k; - - var : integer := 1; - - @b{begin} - k1.kp (var); - k2.kp (var); - k1.kp (var); - k2.kp (var); - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Then to break on a call to procedure kp in the k2 instance, simply - use the command: - - @smallexample - (gdb) break g.k2.kp - @end smallexample - - @noindent - When the breakpoint occurs, you can step through the code of the - instance in the normal manner and examine the values of local variables, as for - other units. - - @node GNAT Abnormal Termination or Failure to Terminate - @section GNAT Abnormal Termination or Failure to Terminate - @cindex GNAT Abnormal Termination or Failure to Terminate - - @noindent - When presented with programs that contain serious errors in syntax - or semantics, - GNAT may on rare occasions experience problems in operation, such - as aborting with a - segmentation fault or illegal memory access, raising an internal - exception, terminating abnormally, or failing to terminate at all. - In such cases, you can activate - various features of GNAT that can help you pinpoint the construct in your - program that is the likely source of the problem. - - The following strategies are presented in increasing order of - difficulty, corresponding to your experience in using GNAT and your - familiarity with compiler internals. - - @enumerate - @item - Run @code{gcc} with the @option{-gnatf}. This first - switch causes all errors on a given line to be reported. In its absence, - only the first error on a line is displayed. - - The @option{-gnatdO} switch causes errors to be displayed as soon as they - are encountered, rather than after compilation is terminated. If GNAT - terminates prematurely or goes into an infinite loop, the last error - message displayed may help to pinpoint the culprit. - - @item - Run @code{gcc} with the @code{^-v (verbose)^/VERBOSE^} switch. In this mode, - @code{gcc} produces ongoing information about the progress of the - compilation and provides the name of each procedure as code is - generated. This switch allows you to find which Ada procedure was being - compiled when it encountered a code generation problem. - - @item - @cindex @option{-gnatdc} switch - Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific - switch that does for the front-end what @code{^-v^VERBOSE^} does for the back end. - The system prints the name of each unit, either a compilation unit or - nested unit, as it is being analyzed. - @item - Finally, you can start - @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the - front-end of GNAT, and can be run independently (normally it is just - called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you - would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The - @code{where} command is the first line of attack; the variable - @code{lineno} (seen by @code{print lineno}), used by the second phase of - @code{gnat1} and by the @code{gcc} backend, indicates the source line at - which the execution stopped, and @code{input_file name} indicates the name of - the source file. - @end enumerate - - @node Naming Conventions for GNAT Source Files - @section Naming Conventions for GNAT Source Files - - @noindent - In order to examine the workings of the GNAT system, the following - brief description of its organization may be helpful: - - @itemize @bullet - @item - Files with prefix @file{^sc^SC^} contain the lexical scanner. - - @item - All files prefixed with @file{^par^PAR^} are components of the parser. The - numbers correspond to chapters of the Ada 95 Reference Manual. For example, - parsing of select statements can be found in @file{par-ch9.adb}. - - @item - All files prefixed with @file{^sem^SEM^} perform semantic analysis. The - numbers correspond to chapters of the Ada standard. For example, all - issues involving context clauses can be found in @file{sem_ch10.adb}. In - addition, some features of the language require sufficient special processing - to justify their own semantic files: sem_aggr for aggregates, sem_disp for - dynamic dispatching, etc. - - @item - All files prefixed with @file{^exp^EXP^} perform normalization and - expansion of the intermediate representation (abstract syntax tree, or AST). - these files use the same numbering scheme as the parser and semantics files. - For example, the construction of record initialization procedures is done in - @file{exp_ch3.adb}. - - @item - The files prefixed with @file{^bind^BIND^} implement the binder, which - verifies the consistency of the compilation, determines an order of - elaboration, and generates the bind file. - - @item - The files @file{atree.ads} and @file{atree.adb} detail the low-level - data structures used by the front-end. - - @item - The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of - the abstract syntax tree as produced by the parser. - - @item - The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of - all entities, computed during semantic analysis. - - @item - Library management issues are dealt with in files with prefix - @file{^lib^LIB^}. - - @item - @findex Ada - @cindex Annex A - Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as - defined in Annex A. - - @item - @findex Interfaces - @cindex Annex B - Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as - defined in Annex B. - - @item - @findex System - Files with prefix @file{^s-^S-^} are children of @code{System}. This includes - both language-defined children and GNAT run-time routines. - - @item - @findex GNAT - Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful - general-purpose packages, fully documented in their specifications. All - the other @file{.c} files are modifications of common @code{gcc} files. - @end itemize - - @node Getting Internal Debugging Information - @section Getting Internal Debugging Information - - @noindent - Most compilers have internal debugging switches and modes. GNAT - does also, except GNAT internal debugging switches and modes are not - secret. A summary and full description of all the compiler and binder - debug flags are in the file @file{debug.adb}. You must obtain the - sources of the compiler to see the full detailed effects of these flags. - - The switches that print the source of the program (reconstructed from - the internal tree) are of general interest for user programs, as are the - options to print - the full internal tree, and the entity table (the symbol table - information). The reconstructed source provides a readable version of the - program after the front-end has completed analysis and expansion, and is useful - when studying the performance of specific constructs. For example, constraint - checks are indicated, complex aggregates are replaced with loops and - assignments, and tasking primitives are replaced with run-time calls. - - @node Stack Traceback - @section Stack Traceback - @cindex traceback - @cindex stack traceback - @cindex stack unwinding - - @noindent - Traceback is a mechanism to display the sequence of subprogram calls that - leads to a specified execution point in a program. Often (but not always) - the execution point is an instruction at which an exception has been raised. - This mechanism is also known as @i{stack unwinding} because it obtains - its information by scanning the run-time stack and recovering the activation - records of all active subprograms. Stack unwinding is one of the most - important tools for program debugging. - - @noindent - The first entry stored in traceback corresponds to the deepest calling level, - that is to say the subprogram currently executing the instruction - from which we want to obtain the traceback. - - @noindent - Note that there is no runtime performance penalty when stack traceback - is enabled and no exception are raised during program execution. - - @menu - * Non-Symbolic Traceback:: - * Symbolic Traceback:: - @end menu - - @node Non-Symbolic Traceback - @subsection Non-Symbolic Traceback - @cindex traceback, non-symbolic - - @noindent - Note: this feature is not supported on all platforms. See - @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported - platforms. - - @menu - * Tracebacks From an Unhandled Exception:: - * Tracebacks From Exception Occurrences (non-symbolic):: - * Tracebacks From Anywhere in a Program (non-symbolic):: - @end menu - - @node Tracebacks From an Unhandled Exception - @subsubsection Tracebacks From an Unhandled Exception - - @noindent - A runtime non-symbolic traceback is a list of addresses of call instructions. - To enable this feature you must use the @code{-E} - @code{gnatbind}'s option. With this option a stack traceback is stored as part - of exception information. It is possible to retrieve this information using the - standard @code{Ada.Exception.Exception_Information} routine. - - @noindent - Let's have a look at a simple example: - - @smallexample - @cartouche - @group - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @noindent - As we see the traceback lists a sequence of addresses for the unhandled - exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to - guess that this exception come from procedure P1. To translate these - addresses into the source lines where the calls appear, the - @code{addr2line} tool, described below, is invaluable. The use of this tool - requires the program to be compiled with debug information. - - @smallexample - $ gnatmake -g stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - - $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 - 0x4011f1 0x77e892a4 - - 00401373 at d:/stb/stb.adb:5 - 0040138B at d:/stb/stb.adb:10 - 0040139C at d:/stb/stb.adb:14 - 00401335 at d:/stb/b~stb.adb:104 - 004011C4 at /build/.../crt1.c:200 - 004011F1 at /build/.../crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - @code{addr2line} has a number of other useful options: - - @table @code - @item --functions - to get the function name corresponding to any location - - @item --demangle=gnat - to use the @b{gnat} decoding mode for the function names. Note that - for binutils version 2.9.x the option is simply @code{--demangle}. - @end table - - @smallexample - $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b - 0x40139c 0x401335 0x4011c4 0x4011f1 - - 00401373 in stb.p1 at d:/stb/stb.adb:5 - 0040138B in stb.p2 at d:/stb/stb.adb:10 - 0040139C in stb at d:/stb/stb.adb:14 - 00401335 in main at d:/stb/b~stb.adb:104 - 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200 - 004011F1 in at /build/.../crt1.c:222 - @end smallexample - - @noindent - From this traceback we can see that the exception was raised in - @file{stb.adb} at line 5, which was reached from a procedure call in - @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file, - which contains the call to the main program. - @pxref{Running gnatbind}. The remaining entries are assorted runtime routines, - and the output will vary from platform to platform. - - @noindent - It is also possible to use @code{GDB} with these traceback addresses to debug - the program. For example, we can break at a given code location, as reported - in the stack traceback: - - @smallexample - $ gdb -nw stb - @ifset wnt - @noindent - Furthermore, this feature is not implemented inside Windows DLL. Only - the non-symbolic traceback is reported in this case. - @end ifset - - (gdb) break *0x401373 - Breakpoint 1 at 0x401373: file stb.adb, line 5. - @end smallexample - - @noindent - It is important to note that the stack traceback addresses - do not change when debug information is included. This is particularly useful - because it makes it possible to release software without debug information (to - minimize object size), get a field report that includes a stack traceback - whenever an internal bug occurs, and then be able to retrieve the sequence - of calls with the same program compiled with debug information. - - @node Tracebacks From Exception Occurrences (non-symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @noindent - Non-symbolic tracebacks are obtained by using the @code{-E} binder argument. - The stack traceback is attached to the exception information string, and can - be retrieved in an exception handler within the Ada program, by means of the - Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with Ada.Exceptions; - - procedure STB is - - use Ada; - use Ada.Exceptions; - - procedure P1 is - K : Positive := 1; - begin - K := K - 1; - exception - when E : others => - Text_IO.Put_Line (Exception_Information (E)); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @noindent - This program will output: - - @smallexample - $ stb - - Exception name: CONSTRAINT_ERROR - Message: stb.adb:12 - Call stack traceback locations: - 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @node Tracebacks From Anywhere in a Program (non-symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is also possible to retrieve a stack traceback from anywhere in a - program. For this you need to - use the @code{GNAT.Traceback} API. This package includes a procedure called - @code{Call_Chain} that computes a complete stack traceback, as well as useful - display procedures described below. It is not necessary to use the - @code{-E gnatbind} option in this case, because the stack traceback mechanism - is invoked explicitly. - - @noindent - In the following example we compute a traceback at a specific location in - the program, and we display it using @code{GNAT.Debug_Utilities.Image} to - convert addresses to strings: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Debug_Utilities; - - procedure STB is - - use Ada; - use GNAT; - use GNAT.Traceback; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - - Text_IO.Put ("In STB.P1 : "); - - for K in 1 .. Len loop - Text_IO.Put (Debug_Utilities.Image (TB (K))); - Text_IO.Put (' '); - end loop; - - Text_IO.New_Line; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb - $ stb - - In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# - 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# - @end smallexample - - @node Symbolic Traceback - @subsection Symbolic Traceback - @cindex traceback, symbolic - - @noindent - A symbolic traceback is a stack traceback in which procedure names are - associated with each code location. - - @noindent - Note that this feature is not supported on all platforms. See - @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete - list of currently supported platforms. - - @noindent - Note that the symbolic traceback requires that the program be compiled - with debug information. If it is not compiled with debug information - only the non-symbolic information will be valid. - - @menu - * Tracebacks From Exception Occurrences (symbolic):: - * Tracebacks From Anywhere in a Program (symbolic):: - @end menu - - @node Tracebacks From Exception Occurrences (symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback.Symbolic; - - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - procedure P3 is - begin - P2; - end P3; - - begin - P3; - exception - when E : others => - Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl - $ stb - - 0040149F in stb.p1 at stb.adb:8 - 004014B7 in stb.p2 at stb.adb:13 - 004014CF in stb.p3 at stb.adb:18 - 004015DD in ada.stb at stb.adb:22 - 00401461 in main at b~stb.adb:168 - 004011C4 in __mingw_CRTStartup at crt1.c:200 - 004011F1 in mainCRTStartup at crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - The exact sequence of linker options may vary from platform to platform. - The above @code{-largs} section is for Windows platforms. By contrast, - under Unix there is no need for the @code{-largs} section. - Differences across platforms are due to details of linker implementation. - - @node Tracebacks From Anywhere in a Program (symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is possible to get a symbolic stack traceback - from anywhere in a program, just as for non-symbolic tracebacks. - The first step is to obtain a non-symbolic - traceback, and then call @code{Symbolic_Traceback} to compute the symbolic - information. Here is an example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Traceback.Symbolic; - - procedure STB is - - use Ada; - use GNAT.Traceback; - use GNAT.Traceback.Symbolic; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @ifset vms - @node Compatibility with DEC Ada - @chapter Compatibility with DEC Ada - @cindex Compatibility - - @noindent - This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT - OpenVMS Alpha. GNAT achieves a high level of compatibility - with DEC Ada, and it should generally be straightforward to port code - from the DEC Ada environment to GNAT. However, there are a few language - and implementation differences of which the user must be aware. These - differences are discussed in this section. In - addition, the operating environment and command structure for the - compiler are different, and these differences are also discussed. - - Note that this discussion addresses specifically the implementation - of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation - of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, GNAT - always follows the Alpha implementation. - - @menu - * Ada 95 Compatibility:: - * Differences in the Definition of Package System:: - * Language-Related Features:: - * The Package STANDARD:: - * The Package SYSTEM:: - * Tasking and Task-Related Features:: - * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems:: - * Pragmas and Pragma-Related Features:: - * Library of Predefined Units:: - * Bindings:: - * Main Program Definition:: - * Implementation-Defined Attributes:: - * Compiler and Run-Time Interfacing:: - * Program Compilation and Library Management:: - * Input-Output:: - * Implementation Limits:: - * Tools:: - @end menu - - @node Ada 95 Compatibility - @section Ada 95 Compatibility - - @noindent - GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83 - compiler. Ada 95 is almost completely upwards compatible - with Ada 83, and therefore Ada 83 programs will compile - and run under GNAT with - no changes or only minor changes. The Ada 95 Reference - Manual (ANSI/ISO/IEC-8652:1995) provides details on specific - incompatibilities. - - GNAT provides the switch /83 on the GNAT COMPILE command, - as well as the pragma ADA_83, to force the compiler to - operate in Ada 83 mode. This mode does not guarantee complete - conformance to Ada 83, but in practice is sufficient to - eliminate most sources of incompatibilities. - In particular, it eliminates the recognition of the - additional Ada 95 keywords, so that their use as identifiers - in Ada83 program is legal, and handles the cases of packages - with optional bodies, and generics that instantiate unconstrained - types without the use of @code{(<>)}. - - @node Differences in the Definition of Package System - @section Differences in the Definition of Package System - - @noindent - Both the Ada 95 and Ada 83 reference manuals permit a compiler to add - implementation-dependent declarations to package System. In normal mode, - GNAT does not take advantage of this permission, and the version of System - provided by GNAT exactly matches that in the Ada 95 Reference Manual. - - However, DEC Ada adds an extensive set of declarations to package System, - as fully documented in the DEC Ada manuals. To minimize changes required - for programs that make use of these extensions, GNAT provides the pragma - Extend_System for extending the definition of package System. By using: - - @smallexample - @group - @cartouche - @b{pragma} Extend_System (Aux_DEC); - @end cartouche - @end group - @end smallexample - - @noindent - The set of definitions in System is extended to include those in package - @code{System.Aux_DEC}. - These definitions are incorporated directly into package - System, as though they had been declared there in the first place. For a - list of the declarations added, see the specification of this package, - which can be found in the file @code{s-auxdec.ads} in the GNAT library. - The pragma Extend_System is a configuration pragma, which means that - it can be placed in the file @file{gnat.adc}, so that it will automatically - apply to all subsequent compilations. See the section on Configuration - Pragmas for further details. - - An alternative approach that avoids the use of the non-standard - Extend_System pragma is to add a context clause to the unit that - references these facilities: - - @smallexample - @group - @cartouche - @b{with} System.Aux_DEC; - @b{use} System.Aux_DEC; - @end cartouche - @end group - @end smallexample - - @noindent - The effect is not quite semantically identical to incorporating the declarations - directly into package @code{System}, - but most programs will not notice a difference - unless they use prefix notation (e.g. @code{System.Integer_8}) - to reference the - entities directly in package @code{System}. - For units containing such references, - the prefixes must either be removed, or the pragma @code{Extend_System} - must be used. - - @node Language-Related Features - @section Language-Related Features - - @noindent - The following sections highlight differences in types, - representations of types, operations, alignment, and - related topics. - - @menu - * Integer Types and Representations:: - * Floating-Point Types and Representations:: - * Pragmas Float_Representation and Long_Float:: - * Fixed-Point Types and Representations:: - * Record and Array Component Alignment:: - * Address Clauses:: - * Other Representation Clauses:: - @end menu - - @node Integer Types and Representations - @subsection Integer Types and Representations - - @noindent - The set of predefined integer types is identical in DEC Ada and GNAT. - Furthermore the representation of these integer types is also identical, - including the capability of size clauses forcing biased representation. - - In addition, - DEC Ada for OpenVMS Alpha systems has defined the - following additional integer types in package System: - - @itemize @bullet - - @item - INTEGER_8 - - @item - INTEGER_16 - - @item - INTEGER_32 - - @item - INTEGER_64 - - @item - LARGEST_INTEGER - @end itemize - - @noindent - When using GNAT, the first four of these types may be obtained from the - standard Ada 95 package @code{Interfaces}. - Alternatively, by use of the pragma - @code{Extend_System}, identical - declarations can be referenced directly in package @code{System}. - On both GNAT and DEC Ada, the maximum integer size is 64 bits. - - @node Floating-Point Types and Representations - @subsection Floating-Point Types and Representations - @cindex Floating-Point types - - @noindent - The set of predefined floating-point types is identical in DEC Ada and GNAT. - Furthermore the representation of these floating-point - types is also identical. One important difference is that the default - representation for DEC Ada is VAX_Float, but the default representation - for GNAT is IEEE. - - Specific types may be declared to be VAX_Float or IEEE, using the pragma - @code{Float_Representation} as described in the DEC Ada documentation. - For example, the declarations: - - @smallexample - @group - @cartouche - @b{type} F_Float @b{is digits} 6; - @b{pragma} Float_Representation (VAX_Float, F_Float); - @end cartouche - @end group - @end smallexample - - @noindent - declare a type F_Float that will be represented in VAX_Float format. - This set of declarations actually appears in System.Aux_DEC, which provides - the full set of additional floating-point declarations provided in - the DEC Ada version of package - System. This and similar declarations may be accessed in a user program by using - pragma @code{Extend_System}. The use of this - pragma, and the related pragma @code{Long_Float} is described in further - detail in the following section. - - @node Pragmas Float_Representation and Long_Float - @subsection Pragmas Float_Representation and Long_Float - - @noindent - DEC Ada provides the pragma @code{Float_Representation}, which - acts as a program library switch to allow control over - the internal representation chosen for the predefined - floating-point types declared in the package @code{Standard}. - The format of this pragma is as follows: - - @smallexample - @group - @cartouche - @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float); - @end cartouche - @end group - @end smallexample - - @noindent - This pragma controls the representation of floating-point - types as follows: - - @itemize @bullet - @item - @code{VAX_Float} specifies that floating-point - types are represented by default with the VAX hardware types - F-floating, D-floating, G-floating. Note that the H-floating - type is available only on DIGITAL Vax systems, and is not available - in either DEC Ada or GNAT for Alpha systems. - - @item - @code{IEEE_Float} specifies that floating-point - types are represented by default with the IEEE single and - double floating-point types. - @end itemize - - @noindent - GNAT provides an identical implementation of the pragma - @code{Float_Representation}, except that it functions as a - configuration pragma, as defined by Ada 95. Note that the - notion of configuration pragma corresponds closely to the - DEC Ada notion of a program library switch. - - When no pragma is used in GNAT, the default is IEEE_Float, which is different - from DEC Ada 83, where the default is VAX_Float. In addition, the - predefined libraries in GNAT are built using IEEE_Float, so it is not - advisable to change the format of numbers passed to standard library - routines, and if necessary explicit type conversions may be needed. - - The use of IEEE_Float is recommended in GNAT since it is more efficient, - and (given that it conforms to an international standard) potentially more - portable. The situation in which VAX_Float may be useful is in interfacing - to existing code and data that expects the use of VAX_Float. There are - two possibilities here. If the requirement for the use of VAX_Float is - localized, then the best approach is to use the predefined VAX_Float - types in package @code{System}, as extended by - @code{Extend_System}. For example, use @code{System.F_Float} - to specify the 32-bit @code{F-Float} format. - - Alternatively, if an entire program depends heavily on the use of - the @code{VAX_Float} and in particular assumes that the types in - package @code{Standard} are in @code{Vax_Float} format, then it - may be desirable to reconfigure GNAT to assume Vax_Float by default. - This is done by using the GNAT LIBRARY command to rebuild the library, and - then using the general form of the @code{Float_Representation} - pragma to ensure that this default format is used throughout. - The form of the GNAT LIBRARY command is: - - @smallexample - GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory} - @end smallexample - - @noindent - where @i{file} contains the new configuration pragmas - and @i{directory} is the directory to be created to contain - the new library. - - @noindent - On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float} - to allow control over the internal representation chosen - for the predefined type @code{Long_Float} and for floating-point - type declarations with digits specified in the range 7 .. 15. - The format of this pragma is as follows: - - @smallexample - @cartouche - @b{pragma} Long_Float (D_FLOAT | G_FLOAT); - @end cartouche - @end smallexample - - @node Fixed-Point Types and Representations - @subsection Fixed-Point Types and Representations - - @noindent - On DEC Ada for OpenVMS Alpha systems, rounding is - away from zero for both positive and negative numbers. - Therefore, +0.5 rounds to 1 and -0.5 rounds to -1. - - On GNAT for OpenVMS Alpha, the results of operations - on fixed-point types are in accordance with the Ada 95 - rules. In particular, results of operations on decimal - fixed-point types are truncated. - - @node Record and Array Component Alignment - @subsection Record and Array Component Alignment - - @noindent - On DEC Ada for OpenVMS Alpha, all non composite components - are aligned on natural boundaries. For example, 1-byte - components are aligned on byte boundaries, 2-byte - components on 2-byte boundaries, 4-byte components on 4-byte - byte boundaries, and so on. The OpenVMS Alpha hardware - runs more efficiently with naturally aligned data. - - ON GNAT for OpenVMS Alpha, alignment rules are compatible - with DEC Ada for OpenVMS Alpha. - - @node Address Clauses - @subsection Address Clauses - - @noindent - In DEC Ada and GNAT, address clauses are supported for - objects and imported subprograms. - The predefined type @code{System.Address} is a private type - in both compilers, with the same representation (it is simply - a machine pointer). Addition, subtraction, and comparison - operations are available in the standard Ada 95 package - @code{System.Storage_Elements}, or in package @code{System} - if it is extended to include @code{System.Aux_DEC} using a - pragma @code{Extend_System} as previously described. - - Note that code that with's both this extended package @code{System} - and the package @code{System.Storage_Elements} should not @code{use} - both packages, or ambiguities will result. In general it is better - not to mix these two sets of facilities. The Ada 95 package was - designed specifically to provide the kind of features that DEC Ada - adds directly to package @code{System}. - - GNAT is compatible with DEC Ada in its handling of address - clauses, except for some limitations in - the form of address clauses for composite objects with - initialization. Such address clauses are easily replaced - by the use of an explicitly-defined constant as described - in the Ada 95 Reference Manual (13.1(22)). For example, the sequence - of declarations: - - @smallexample - @group - @cartouche - X, Y : Integer := Init_Func; - Q : String (X .. Y) := "abc"; - ... - @b{for} Q'Address @b{use} Compute_Address; - @end cartouche - @end group - @end smallexample - - @noindent - will be rejected by GNAT, since the address cannot be computed at the time - that Q is declared. To achieve the intended effect, write instead: - - @smallexample - @group - @cartouche - X, Y : Integer := Init_Func; - Q_Address : @b{constant} Address := Compute_Address; - Q : String (X .. Y) := "abc"; - ... - @b{for} Q'Address @b{use} Q_Address; - @end cartouche - @end group - @end smallexample - - @noindent - which will be accepted by GNAT (and other Ada 95 compilers), and is also - backwards compatible with Ada 83. A fuller description of the restrictions - on address specifications is found in the GNAT Reference Manual. - - @node Other Representation Clauses - @subsection Other Representation Clauses - - @noindent - GNAT supports in a compatible manner all the representation - clauses supported by DEC Ada. In addition, it - supports representation clause forms that are new in Ada 95 - including COMPONENT_SIZE and SIZE clauses for objects. - - @node The Package STANDARD - @section The Package STANDARD - - @noindent - The package STANDARD, as implemented by DEC Ada, is fully - described in the Reference Manual for the Ada Programming - Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada - Language Reference Manual. As implemented by GNAT, the - package STANDARD is described in the Ada 95 Reference - Manual. - - In addition, DEC Ada supports the Latin-1 character set in - the type CHARACTER. GNAT supports the Latin-1 character set - in the type CHARACTER and also Unicode (ISO 10646 BMP) in - the type WIDE_CHARACTER. - - The floating-point types supported by GNAT are those - supported by DEC Ada, but defaults are different, and are controlled by - pragmas. See @pxref{Floating-Point Types and Representations} for details. - - @node The Package SYSTEM - @section The Package SYSTEM - - @noindent - DEC Ada provides a system-specific version of the package - SYSTEM for each platform on which the language ships. - For the complete specification of the package SYSTEM, see - Appendix F of the DEC Ada Language Reference Manual. - - On DEC Ada, the package SYSTEM includes the following conversion functions: - @itemize @bullet - @item TO_ADDRESS(INTEGER) - - @item TO_ADDRESS(UNSIGNED_LONGWORD) - - @item TO_ADDRESS(universal_integer) - - @item TO_INTEGER(ADDRESS) - - @item TO_UNSIGNED_LONGWORD(ADDRESS) - - @item Function IMPORT_VALUE return UNSIGNED_LONGWORD and the - functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE - @end itemize - - @noindent - By default, GNAT supplies a version of SYSTEM that matches - the definition given in the Ada 95 Reference Manual. - This - is a subset of the DIGITAL system definitions, which is as - close as possible to the original definitions. The only difference - is that the definition of SYSTEM_NAME is different: - - @smallexample - @group - @cartouche - @b{type} Name @b{is} (SYSTEM_NAME_GNAT); - System_Name : @b{constant} Name := SYSTEM_NAME_GNAT; - @end cartouche - @end group - @end smallexample - - @noindent - Also, GNAT adds the new Ada 95 declarations for - BIT_ORDER and DEFAULT_BIT_ORDER. - - However, the use of the following pragma causes GNAT - to extend the definition of package SYSTEM so that it - encompasses the full set of DIGITAL-specific extensions, - including the functions listed above: - - @smallexample - @cartouche - @b{pragma} Extend_System (Aux_DEC); - @end cartouche - @end smallexample - - @noindent - The pragma Extend_System is a configuration pragma that - is most conveniently placed in the @file{gnat.adc} file. See the - GNAT Reference Manual for further details. - - DEC Ada does not allow the recompilation of the package - SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_ - NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in - the package SYSTEM. On OpenVMS Alpha systems, the pragma - SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as - its single argument. - - GNAT does permit the recompilation of package SYSTEM using - a special switch (-gnatg) and this switch can be used if - it is necessary to change constants in SYSTEM. GNAT does - not permit the specification of SYSTEM_NAME, STORAGE_UNIT - or MEMORY_SIZE by any other means. - - On GNAT systems, the pragma SYSTEM_NAME takes the - enumeration literal SYSTEM_NAME_GNAT. - - The definitions provided by the use of - - @smallexample - pragma Extend_System (AUX_Dec); - @end smallexample - - @noindent - are virtually identical to those provided by the DEC Ada 83 package - System. One important difference is that the name of the TO_ADDRESS - function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG. - See the GNAT Reference manual for a discussion of why this change was - necessary. - - @noindent - The version of TO_ADDRESS taking a universal integer argument is in fact - an extension to Ada 83 not strictly compatible with the reference manual. - In GNAT, we are constrained to be exactly compatible with the standard, - and this means we cannot provide this capability. In DEC Ada 83, the - point of this definition is to deal with a call like: - - @smallexample - TO_ADDRESS (16#12777#); - @end smallexample - - @noindent - Normally, according to the Ada 83 standard, one would expect this to be - ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms - of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the - definition using universal_integer takes precedence. - - In GNAT, since the version with universal_integer cannot be supplied, it is - not possible to be 100% compatible. Since there are many programs using - numeric constants for the argument to TO_ADDRESS, the decision in GNAT was - to change the name of the function in the UNSIGNED_LONGWORD case, so the - declarations provided in the GNAT version of AUX_Dec are: - - @smallexample - function To_Address (X : Integer) return Address; - pragma Pure_Function (To_Address); - - function To_Address_Long (X : Unsigned_Longword) return Address; - pragma Pure_Function (To_Address_Long); - @end smallexample - - @noindent - This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must - change the name to TO_ADDRESS_LONG. - - @node Tasking and Task-Related Features - @section Tasking and Task-Related Features - - @noindent - The concepts relevant to a comparison of tasking on GNAT - and on DEC Ada for OpenVMS Alpha systems are discussed in - the following sections. - - For detailed information on concepts related to tasking in - DEC Ada, see the DEC Ada Language Reference Manual and the - relevant run-time reference manual. - - @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems - @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems - - @noindent - On OpenVMS Alpha systems, each Ada task (except a passive - task) is implemented as a single stream of execution - that is created and managed by the kernel. On these - systems, DEC Ada tasking support is based on DECthreads, - an implementation of the POSIX standard for threads. - - Although tasks are implemented as threads, all tasks in - an Ada program are part of the same process. As a result, - resources such as open files and virtual memory can be - shared easily among tasks. Having all tasks in one process - allows better integration with the programming environment - (the shell and the debugger, for example). - - Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign - code that calls DECthreads routines can be used together. - The interaction between Ada tasks and DECthreads routines - can have some benefits. For example when on OpenVMS Alpha, - DEC Ada can call C code that is already threaded. - GNAT on OpenVMS Alpha uses the facilities of DECthreads, - and Ada tasks are mapped to threads. - - @menu - * Assigning Task IDs:: - * Task IDs and Delays:: - * Task-Related Pragmas:: - * Scheduling and Task Priority:: - * The Task Stack:: - * External Interrupts:: - @end menu - - @node Assigning Task IDs - @subsection Assigning Task IDs - - @noindent - The DEC Ada Run-Time Library always assigns %TASK 1 to - the environment task that executes the main program. On - OpenVMS Alpha systems, %TASK 0 is often used for tasks - that have been created but are not yet activated. - - On OpenVMS Alpha systems, task IDs are assigned at - activation. On GNAT systems, task IDs are also assigned at - task creation but do not have the same form or values as - task ID values in DEC Ada. There is no null task, and the - environment task does not have a specific task ID value. - - @node Task IDs and Delays - @subsection Task IDs and Delays - - @noindent - On OpenVMS Alpha systems, tasking delays are implemented - using Timer System Services. The Task ID is used for the - identification of the timer request (the REQIDT parameter). - If Timers are used in the application take care not to use - 0 for the identification, because cancelling such a timer - will cancel all timers and may lead to unpredictable results. - - @node Task-Related Pragmas - @subsection Task-Related Pragmas - - @noindent - Ada supplies the pragma TASK_STORAGE, which allows - specification of the size of the guard area for a task - stack. (The guard area forms an area of memory that has no - read or write access and thus helps in the detection of - stack overflow.) On OpenVMS Alpha systems, if the pragma - TASK_STORAGE specifies a value of zero, a minimal guard - area is created. In the absence of a pragma TASK_STORAGE, a default guard - area is created. - - GNAT supplies the following task-related pragmas: - - @itemize @bullet - @item TASK_INFO - - This pragma appears within a task definition and - applies to the task in which it appears. The argument - must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE. - - @item TASK_STORAGE - - GNAT implements pragma TASK_STORAGE in the same way as - DEC Ada. - Both DEC Ada and GNAT supply the pragmas PASSIVE, - SUPPRESS, and VOLATILE. - @end itemize - @node Scheduling and Task Priority - @subsection Scheduling and Task Priority - - @noindent - DEC Ada implements the Ada language requirement that - when two tasks are eligible for execution and they have - different priorities, the lower priority task does not - execute while the higher priority task is waiting. The DEC - Ada Run-Time Library keeps a task running until either the - task is suspended or a higher priority task becomes ready. - - On OpenVMS Alpha systems, the default strategy is round- - robin with preemption. Tasks of equal priority take turns - at the processor. A task is run for a certain period of - time and then placed at the rear of the ready queue for - its priority level. - - DEC Ada provides the implementation-defined pragma TIME_SLICE, - which can be used to enable or disable round-robin - scheduling of tasks with the same priority. - See the relevant DEC Ada run-time reference manual for - information on using the pragmas to control DEC Ada task - scheduling. - - GNAT follows the scheduling rules of Annex D (real-time - Annex) of the Ada 95 Reference Manual. In general, this - scheduling strategy is fully compatible with DEC Ada - although it provides some additional constraints (as - fully documented in Annex D). - GNAT implements time slicing control in a manner compatible with - DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical - to the DEC Ada 83 pragma of the same name. - Note that it is not possible to mix GNAT tasking and - DEC Ada 83 tasking in the same program, since the two run times are - not compatible. - - @node The Task Stack - @subsection The Task Stack - - @noindent - In DEC Ada, a task stack is allocated each time a - non passive task is activated. As soon as the task is - terminated, the storage for the task stack is deallocated. - If you specify a size of zero (bytes) with T'STORAGE_SIZE, - a default stack size is used. Also, regardless of the size - specified, some additional space is allocated for task - management purposes. On OpenVMS Alpha systems, at least - one page is allocated. - - GNAT handles task stacks in a similar manner. According to - the Ada 95 rules, it provides the pragma STORAGE_SIZE as - an alternative method for controlling the task stack size. - The specification of the attribute T'STORAGE_SIZE is also - supported in a manner compatible with DEC Ada. - - @node External Interrupts - @subsection External Interrupts - - @noindent - On DEC Ada, external interrupts can be associated with task entries. - GNAT is compatible with DEC Ada in its handling of external interrupts. - - @node Pragmas and Pragma-Related Features - @section Pragmas and Pragma-Related Features - - @noindent - Both DEC Ada and GNAT supply all language-defined pragmas - as specified by the Ada 83 standard. GNAT also supplies all - language-defined pragmas specified in the Ada 95 Reference Manual. - In addition, GNAT implements the implementation-defined pragmas - from DEC Ada 83. - - @itemize @bullet - @item AST_ENTRY - - @item COMMON_OBJECT - - @item COMPONENT_ALIGNMENT - - @item EXPORT_EXCEPTION - - @item EXPORT_FUNCTION - - @item EXPORT_OBJECT - - @item EXPORT_PROCEDURE - - @item EXPORT_VALUED_PROCEDURE - - @item FLOAT_REPRESENTATION - - @item IDENT - - @item IMPORT_EXCEPTION - - @item IMPORT_FUNCTION - - @item IMPORT_OBJECT - - @item IMPORT_PROCEDURE - - @item IMPORT_VALUED_PROCEDURE - - @item INLINE_GENERIC - - @item INTERFACE_NAME - - @item LONG_FLOAT - - @item MAIN_STORAGE - - @item PASSIVE - - @item PSET_OBJECT - - @item SHARE_GENERIC - - @item SUPPRESS_ALL - - @item TASK_STORAGE - - @item TIME_SLICE - - @item TITLE - @end itemize - - @noindent - These pragmas are all fully implemented, with the exception of @code{Title}, - @code{Passive}, and @code{Share_Generic}, which are - recognized, but which have no - effect in GNAT. The effect of @code{Passive} may be obtained by the - use of protected objects in Ada 95. In GNAT, all generics are inlined. - - Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require - a separate subprogram specification which must appear before the - subprogram body. - - GNAT also supplies a number of implementation-defined pragmas as follows: - @itemize @bullet - @item C_PASS_BY_COPY - - @item EXTEND_SYSTEM - - @item SOURCE_FILE_NAME - - @item UNSUPPRESS - - @item WARNINGS - - @item ABORT_DEFER - - @item ADA_83 - - @item ADA_95 - - @item ANNOTATE - - @item ASSERT - - @item CPP_CLASS - - @item CPP_CONSTRUCTOR - - @item CPP_DESTRUCTOR - - @item CPP_VIRTUAL - - @item CP_VTABLE - - @item DEBUG - - @item LINKER_ALIAS - - @item LINKER_SECTION - - @item MACHINE_ATTRIBUTE - - @item NO_RETURN - - @item PURE_FUNCTION - - @item SOURCE_REFERENCE - - @item TASK_INFO - - @item UNCHECKED_UNION - - @item UNIMPLEMENTED_UNIT - - @item WEAK_EXTERNAL - @end itemize - - @noindent - For full details on these GNAT implementation-defined pragmas, see - the GNAT Reference Manual. - - @menu - * Restrictions on the Pragma INLINE:: - * Restrictions on the Pragma INTERFACE:: - * Restrictions on the Pragma SYSTEM_NAME:: - @end menu - - @node Restrictions on the Pragma INLINE - @subsection Restrictions on the Pragma INLINE - - @noindent - DEC Ada applies the following restrictions to the pragma INLINE: - @itemize @bullet - @item Parameters cannot be a task type. - - @item Function results cannot be task types, unconstrained - array types, or unconstrained types with discriminants. - - @item Bodies cannot declare the following: - @itemize @bullet - @item Subprogram body or stub (imported subprogram is allowed) - - @item Tasks - - @item Generic declarations - - @item Instantiations - - @item Exceptions - - @item Access types (types derived from access types allowed) - - @item Array or record types - - @item Dependent tasks - - @item Direct recursive calls of subprogram or containing - subprogram, directly or via a renaming - - @end itemize - @end itemize - - @noindent - In GNAT, the only restriction on pragma INLINE is that the - body must occur before the call if both are in the same - unit, and the size must be appropriately small. There are - no other specific restrictions which cause subprograms to - be incapable of being inlined. - - @node Restrictions on the Pragma INTERFACE - @subsection Restrictions on the Pragma INTERFACE - - @noindent - The following lists and describes the restrictions on the - pragma INTERFACE on DEC Ada and GNAT: - @itemize @bullet - @item Languages accepted: Ada, Bliss, C, Fortran, Default. - Default is the default on OpenVMS Alpha systems. - - @item Parameter passing: Language specifies default - mechanisms but can be overridden with an EXPORT pragma. - - @itemize @bullet - @item Ada: Use internal Ada rules. - - @item Bliss, C: Parameters must be mode @code{in}; cannot be - record or task type. Result cannot be a string, an - array, or a record. - - @item Fortran: Parameters cannot be a task. Result cannot - be a string, an array, or a record. - @end itemize - @end itemize - - @noindent - GNAT is entirely upwards compatible with DEC Ada, and in addition allows - record parameters for all languages. - - @node Restrictions on the Pragma SYSTEM_NAME - @subsection Restrictions on the Pragma SYSTEM_NAME - - @noindent - For DEC Ada for OpenVMS Alpha, the enumeration literal - for the type NAME is OPENVMS_AXP. In GNAT, the enumeration - literal for the type NAME is SYSTEM_NAME_GNAT. - - @node Library of Predefined Units - @section Library of Predefined Units - - @noindent - A library of predefined units is provided as part of the - DEC Ada and GNAT implementations. DEC Ada does not provide - the package MACHINE_CODE but instead recommends importing - assembler code. - - The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:) - units are taken from the OpenVMS Alpha version, not the OpenVMS VAX - version. During GNAT installation, the DEC Ada Predefined - Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] - (aka DECLIB) directory and patched to remove Ada 95 incompatibilities - and to make them interoperable with GNAT, @pxref{Changes to DECLIB} - for details. - - The GNAT RTL is contained in - the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and - the default search path is set up to find DECLIB units in preference - to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO, - for example). - - However, it is possible to change the default so that the - reverse is true, or even to mix them using child package - notation. The DEC Ada 83 units are available as DEC.xxx where xxx - is the package name, and the Ada units are available in the - standard manner defined for Ada 95, that is to say as Ada.xxx. To - change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH - appropriately. For example, to change the default to use the Ada95 - versions do: - - @smallexample - $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],- - GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB] - $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],- - GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB] - @end smallexample - - @menu - * Changes to DECLIB:: - @end menu - - @node Changes to DECLIB - @subsection Changes to DECLIB - - @noindent - The changes made to the DEC Ada predefined library for GNAT and Ada 95 - compatibility are minor and include the following: - - @itemize @bullet - @item Adjusting the location of pragmas and record representation - clauses to obey Ada 95 rules - - @item Adding the proper notation to generic formal parameters - that take unconstrained types in instantiation - - @item Adding pragma ELABORATE_BODY to package specifications - that have package bodies not otherwise allowed - - @item Occurrences of the identifier "PROTECTED" are renamed to "PROTECTD". - Currently these are found only in the STARLET package spec. - @end itemize - - @noindent - None of the above changes is visible to users. - - @node Bindings - @section Bindings - - @noindent - On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings: - @itemize @bullet - - @item Command Language Interpreter (CLI interface) - - @item DECtalk Run-Time Library (DTK interface) - - @item Librarian utility routines (LBR interface) - - @item General Purpose Run-Time Library (LIB interface) - - @item Math Run-Time Library (MTH interface) - - @item National Character Set Run-Time Library (NCS interface) - - @item Compiled Code Support Run-Time Library (OTS interface) - - @item Parallel Processing Run-Time Library (PPL interface) - - @item Screen Management Run-Time Library (SMG interface) - - @item Sort Run-Time Library (SOR interface) - - @item String Run-Time Library (STR interface) - - @item STARLET System Library - @findex Starlet - - @item X Window System Version 11R4 and 11R5 (X, XLIB interface) - - @item X Windows Toolkit (XT interface) - - @item X/Motif Version 1.1.3 and 1.2 (XM interface) - @end itemize - - @noindent - GNAT provides implementations of these DEC bindings in the DECLIB directory. - - The X/Motif bindings used to build DECLIB are whatever versions are in the - DEC Ada ADA$PREDEFINED directory with extension .ADC. The build script will - automatically add a pragma Linker_Options to packages Xm, Xt, and X_Lib - causing the default X/Motif shareable image libraries to be linked in. This - is done via options files named xm.opt, xt.opt, and x_lib.opt (also located - in the DECLIB directory). - - It may be necessary to edit these options files to update or correct the - library names if, for example, the newer X/Motif bindings from ADA$EXAMPLES - had been (previous to installing GNAT) copied and renamed to superseded the - default ADA$PREDEFINED versions. - - @menu - * Shared Libraries and Options Files:: - * Interfaces to C:: - @end menu - - @node Shared Libraries and Options Files - @subsection Shared Libraries and Options Files - - @noindent - When using the DEC Ada - predefined X and Motif bindings, the linking with their shareable images is - done automatically by GNAT LINK. When using other X and Motif bindings, it - is necessary to add the corresponding shareable images to the command line for - GNAT LINK. When linking with shared libraries, or with .OPT files, it is - also necessary to add them to the command line for GNAT LINK. - - A shared library to be used with GNAT is built in the same way as other - libraries under VMS. The VMS Link command can be used in standard fashion. - - @node Interfaces to C - @subsection Interfaces to C - - @noindent - DEC Ada - provides the following Ada types and operations: - - @itemize @bullet - @item C types package (C_TYPES) - - @item C strings (C_TYPES.NULL_TERMINATED) - - @item Other_types (SHORT_INT) - @end itemize - - @noindent - Interfacing to C with GNAT, one can use the above approach - described for DEC Ada or the facilities of Annex B of - the Ada 95 Reference Manual (packages INTERFACES.C, - INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more - information, see the section "Interfacing to C" in the - GNAT Reference Manual. - - The @option{-gnatF} qualifier forces default and explicit - @code{External_Name} parameters in pragmas Import and Export - to be uppercased for compatibility with the default behavior - of DEC C. The qualifier has no effect on @code{Link_Name} parameters. - - @node Main Program Definition - @section Main Program Definition - - @noindent - The following section discusses differences in the - definition of main programs on DEC Ada and GNAT. - On DEC Ada, main programs are defined to meet the - following conditions: - @itemize @bullet - @item Procedure with no formal parameters (returns 0 upon - normal completion) - - @item Procedure with no formal parameters (returns 42 when - unhandled exceptions are raised) - - @item Function with no formal parameters whose returned value - is of a discrete type - - @item Procedure with one OUT formal of a discrete type for - which a specification of pragma EXPORT_VALUED_PROCEDURE is given. - - @end itemize - - @noindent - When declared with the pragma EXPORT_VALUED_PROCEDURE, - a main function or main procedure returns a discrete - value whose size is less than 64 bits (32 on VAX systems), - the value is zero- or sign-extended as appropriate. - On GNAT, main programs are defined as follows: - @itemize @bullet - @item Must be a non-generic, parameter-less subprogram that - is either a procedure or function returning an Ada - STANDARD.INTEGER (the predefined type) - - @item Cannot be a generic subprogram or an instantiation of a - generic subprogram - @end itemize - - @node Implementation-Defined Attributes - @section Implementation-Defined Attributes - - @noindent - GNAT provides all DEC Ada implementation-defined - attributes. - - @node Compiler and Run-Time Interfacing - @section Compiler and Run-Time Interfacing - - @noindent - DEC Ada provides the following ways to pass options to the linker (ACS LINK): - @itemize @bullet - @item /WAIT and /SUBMIT qualifiers - - @item /COMMAND qualifier - - @item /[NO]MAP qualifier - - @item /OUTPUT=file-spec - - @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers - @end itemize - - @noindent - To pass options to the linker, GNAT provides the following - switches: - - @itemize @bullet - @item /EXECUTABLE=exec-name - - @item /VERBOSE qualifier - - @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers - @end itemize - - @noindent - For more information on these switches, see the section - "Switches for gnatlink" in the corresponding section of this Guide. - In DEC Ada, the command-line switch /OPTIMIZE is available - to control optimization. DEC Ada also supplies the - following pragmas: - @itemize @bullet - @item OPTIMIZE - - @item INLINE - - @item INLINE_GENERIC - - @item SUPPRESS_ALL - - @item PASSIVE - @end itemize - - @noindent - In GNAT, optimization is controlled strictly by command - line parameters, as described in the corresponding section of this guide. - The DIGITAL pragmas for control of optimization are - recognized but ignored. - - Note that in GNAT, the default is optimization off, whereas in DEC Ada 83, - the default is that optimization is turned on. - - @node Program Compilation and Library Management - @section Program Compilation and Library Management - - @noindent - DEC Ada and GNAT provide a comparable set of commands to - build programs. DEC Ada also provides a program library, - which is a concept that does not exist on GNAT. Instead, - GNAT provides directories of sources that are compiled as - needed. - - The following table summarizes - the DEC Ada commands and provides - equivalent GNAT commands. In this table, some GNAT - equivalents reflect the fact that GNAT does not use the - concept of a program library. Instead, it uses a model - in which collections of source and object files are used - in a manner consistent with other languages like C and - Fortran. Therefore, standard system file commands are used - to manipulate these elements. Those GNAT commands are marked with - an asterisk in the table that follows. - Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards. - - @need 1500 - @multitable @columnfractions .31 .30 .39 - - @item @strong{DEC_Ada_Command} - @tab @strong{GNAT_Equivalent} - @tab @strong{Description} - - @item ADA - @tab GNAT COMPILE - @tab Invokes the compiler to compile one or more Ada source files. - - @item ACS ATTACH - @tab No equivalent - @tab Switches control of terminal from current process running the program - library manager. - - @item ACS CHECK - @tab GNAT MAKE /DEPENDENCY_LIST - @tab Forms the execution closure of one - or more compiled units and checks completeness and currency. - - @item ACS COMPILE - @tab GNAT MAKE /ACTIONS=COMPILE - @tab Forms the execution closure of one or - more specified units, checks completeness and currency, - identifies units that have revised source files, compiles same, - and recompiles units that are or will become obsolete. - Also completes incomplete generic instantiations. - - @item ACS COPY FOREIGN - @tab Copy (*) - @tab Copies a foreign object file into the program library as a - library unit body. - - @item ACS COPY UNIT - @tab Copy (*) - @tab Copies a compiled unit from one program library to another. - - @item ACS CREATE LIBRARY - @tab Create /directory (*) - @tab Creates a program library. - - @item ACS CREATE SUBLIBRARY - @tab Create /directory (*) - @tab Creates a program sublibrary. - - @item ACS DELETE LIBRARY - @tab - @tab Deletes a program library and its contents. - - @item ACS DELETE SUBLIBRARY - @tab - @tab Deletes a program sublibrary and its contents. - - @item ACS DELETE UNIT - @tab Delete @i{file} (*) - @tab On OpenVMS systems, deletes one or more compiled units from - the current program library. - - @item ACS DIRECTORY - @tab Directory (*) - @tab On OpenVMS systems, lists units contained in the current - program library. - - @item ACS ENTER FOREIGN - @tab Copy (*) - @tab Allows the import of a foreign body as an Ada library - specification and enters a reference to a pointer. - - @item ACS ENTER UNIT - @tab Copy (*) - @tab Enters a reference (pointer) from the current program library to - a unit compiled into another program library. - - @item ACS EXIT - @tab No equivalent - @tab Exits from the program library manager. - - @item ACS EXPORT - @tab Copy (*) - @tab Creates an object file that contains system-specific object code - for one or more units. With GNAT, object files can simply be copied - into the desired directory. - - @item ACS EXTRACT SOURCE - @tab Copy (*) - @tab Allows access to the copied source file for each Ada compilation unit - - @item ACS HELP - @tab HELP GNAT - @tab Provides online help. - - @item ACS LINK - @tab GNAT LINK - @tab Links an object file containing Ada units into an executable - file. - - @item ACS LOAD - @tab Copy (*) - @tab Loads (partially compiles) Ada units into the program library. - Allows loading a program from a collection of files into a library - without knowing the relationship among units. - - @item ACS MERGE - @tab Copy (*) - @tab Merges into the current program library, one or more units from - another library where they were modified. - - @item ACS RECOMPILE - @tab GNAT MAKE /ACTIONS=COMPILE - @tab Recompiles from external or copied source files any obsolete - unit in the closure. Also, completes any incomplete generic - instantiations. - - @item ACS REENTER - @tab GNAT MAKE - @tab Reenters current references to units compiled after last entered - with the ACS ENTER UNIT command. - - @item ACS SET LIBRARY - @tab Set default (*) - @tab Defines a program library to be the compilation context as well - as the target library for compiler output and commands in general. - - @item ACS SET PRAGMA - @tab Edit gnat.adc (*) - @tab Redefines specified values of the library characteristics - LONG_ FLOAT, MEMORY_SIZE, SYSTEM_NAME, and @code{Float_Representation}. - - @item ACS SET SOURCE - @tab define @* ADA_INCLUDE_PATH @i{path} (*) - @tab Defines the source file search list for the ACS COMPILE command. - - @item ACS SHOW LIBRARY - @tab Directory (*) - @tab Lists information about one or more program libraries. - - @item ACS SHOW PROGRAM - @tab No equivalent - @tab Lists information about the execution closure of one or - more units in the program library. - - @item ACS SHOW SOURCE - @tab Show logical @* ADA_INCLUDE_PATH - @tab Shows the source file search used when compiling units. - - @item ACS SHOW VERSION - @tab Compile with VERBOSE option - @tab Displays the version number of the compiler and program library - manager used. - - @item ACS SPAWN - @tab No equivalent - @tab Creates a subprocess of the current process (same as DCL SPAWN - command). - - @item ACS VERIFY - @tab No equivalent - @tab Performs a series of consistency checks on a program library to - determine whether the library structure and library files are in - valid_form. - - @end multitable - - @noindent - - @node Input-Output - @section Input-Output - - @noindent - On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record - Management Services (RMS) to perform operations on - external files. - - @noindent - DEC Ada and GNAT predefine an identical set of input- - output packages. To make the use of the - generic TEXT_IO operations more convenient, DEC Ada - provides predefined library packages that instantiate the - integer and floating-point operations for the predefined - integer and floating-point types as shown in the following table. - - @table @code - - @item Package_Name - Instantiation - - @item INTEGER_TEXT_IO - INTEGER_IO(INTEGER) - - @item SHORT_INTEGER_TEXT_IO - INTEGER_IO(SHORT_INTEGER) - - @item SHORT_SHORT_INTEGER_TEXT_IO - INTEGER_IO(SHORT_SHORT_ INTEGER) - - @item FLOAT_TEXT_IO - FLOAT_IO(FLOAT) - - @item LONG_FLOAT_TEXT_IO - FLOAT_IO(LONG_FLOAT) - @end table - - @noindent - The DEC Ada predefined packages and their operations - are implemented using OpenVMS Alpha files and input- - output facilities. DEC Ada supports asynchronous input- - output on OpenVMS Alpha. Familiarity with the following is - recommended: - @itemize @bullet - @item RMS file organizations and access methods - - @item OpenVMS file specifications and directories - - @item OpenVMS File Definition Language (FDL) - @end itemize - - @noindent - GNAT provides I/O facilities that are completely - compatible with DEC Ada. The distribution includes the - standard DEC Ada versions of all I/O packages, operating - in a manner compatible with DEC Ada. In particular, the - following packages are by default the DEC Ada (Ada 83) - versions of these packages rather than the renamings - suggested in annex J of the Ada 95 Reference Manual: - @itemize @bullet - @item TEXT_IO - - @item SEQUENTIAL_IO - - @item DIRECT_IO - @end itemize - - @noindent - The use of the standard Ada 95 syntax for child packages (for - example, ADA.TEXT_IO) retrieves the Ada 95 versions of these - packages, as defined in the Ada 95 Reference Manual. - GNAT provides DIGITAL-compatible predefined instantiations - of the TEXT_IO packages, and also - provides the standard predefined instantiations required - by the Ada 95 Reference Manual. - - For further information on how GNAT interfaces to the file - system or how I/O is implemented in programs written in - mixed languages, see the chapter "Implementation of the - Standard I/O" in the GNAT Reference Manual. - This chapter covers the following: - @itemize @bullet - @item Standard I/O packages - - @item FORM strings - - @item DIRECT_IO - - @item SEQUENTIAL_IO - - @item TEXT_IO - - @item Stream pointer positioning - - @item Reading and writing non-regular files - - @item GET_IMMEDIATE - - @item Treating TEXT_IO files as streams - - @item Shared files - - @item Open modes - @end itemize - - @node Implementation Limits - @section Implementation Limits - - @noindent - The following table lists implementation limits for DEC Ada and GNAT systems. - @multitable @columnfractions .60 .20 .20 - @item Compilation Parameter - @tab DEC Ada - @tab GNAT - - @item In a subprogram or entry declaration, maximum number of - formal parameters that are of an unconstrained record type - @tab 32 - @tab No set limit - - @item Maximum identifier length (number of characters) - @tab 255 - @tab 255 - - @item Maximum number of characters in a source line - @tab 255 - @tab 255 - - @item Maximum collection size (number of bytes) - @tab 2**31-1 - @tab 2**31-1 - - @item Maximum number of discriminants for a record type - @tab 245 - @tab No set limit - - @item Maximum number of formal parameters in an entry or - subprogram declaration - @tab 246 - @tab No set limit - - @item Maximum number of dimensions in an array type - @tab 255 - @tab No set limit - - @item Maximum number of library units and subunits in a compilation. - @tab 4095 - @tab No set limit - - @item Maximum number of library units and subunits in an execution. - @tab 16383 - @tab No set limit - - @item Maximum number of objects declared with the pragma COMMON_OBJECT - or PSECT_OBJECT - @tab 32757 - @tab No set limit - - @item Maximum number of enumeration literals in an enumeration type - definition - @tab 65535 - @tab No set limit - - @item Maximum number of lines in a source file - @tab 65534 - @tab No set limit - - @item Maximum number of bits in any object - @tab 2**31-1 - @tab 2**31-1 - - @item Maximum size of the static portion of a stack frame (approximate) - @tab 2**31-1 - @tab 2**31-1 - @end multitable - - @node Tools - @section Tools - - @end ifset - - @node Inline Assembler - @chapter Inline Assembler - - @noindent - If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program. First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT. However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler. The Inline Assembler approach offers a number of advantages, including the following: - - @itemize @bullet - @item No need to use non-Ada tools - @item Consistent interface over different targets - @item Automatic usage of the proper calling conventions - @item Access to Ada constants and variables - @item Definition of intrinsic routines - @item Possibility of inlining a subprogram comprising assembler code - @item Code optimizer can take Inline Assembler code into account - @end itemize - - This chapter presents a series of examples to show you how to use the Inline Assembler. Although it focuses on the Intel x86, the general approach applies also to other processors. It is assumed that you are familiar with Ada and with assembly language programming. - - @menu - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - @end menu - - @c --------------------------------------------------------------------------- - @node Basic Assembler Syntax - @section Basic Assembler Syntax - - @noindent - The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a - language that descends from the AT&T Unix assembler @emph{as} (and which is often - referred to as ``AT&T syntax''). - The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions. - See the gcc @emph{as} and @emph{gas} (an @emph{as} macro - pre-processor) documentation for further information. - - @table @asis - @item Register names - gcc / @emph{as}: Prefix with ``%''; for example @code{%eax} - @* - Intel: No extra punctuation; for example @code{eax} - - @item Immediate operand - gcc / @emph{as}: Prefix with ``$''; for example @code{$4} - @* - Intel: No extra punctuation; for example @code{4} - - @item Address - gcc / @emph{as}: Prefix with ``$''; for example @code{$loc} - @* - Intel: No extra punctuation; for example @code{loc} - - @item Memory contents - gcc / @emph{as}: No extra punctuation; for example @code{loc} - @* - Intel: Square brackets; for example @code{[loc]} - - @item Register contents - gcc / @emph{as}: Parentheses; for example @code{(%eax)} - @* - Intel: Square brackets; for example @code{[eax]} - - @item Hexadecimal numbers - gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} - @* - Intel: Trailing ``h''; for example @code{A0h} - - @item Operand size - gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word - @* - Intel: Implicit, deduced by assembler; for example @code{mov} - - @item Instruction repetition - gcc / @emph{as}: Split into two lines; for example - @* - @code{rep} - @* - @code{stosl} - @* - Intel: Keep on one line; for example @code{rep stosl} - - @item Order of operands - gcc / @emph{as}: Source first; for example @code{movw $4, %eax} - @* - Intel: Destination first; for example @code{mov eax, 4} - @end table - - @c --------------------------------------------------------------------------- - @node A Simple Example of Inline Assembler - @section A Simple Example of Inline Assembler - - @noindent - The following example will generate a single assembly language statement, @code{nop}, which does nothing. Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility. - - @smallexample - @group - with System.Machine_Code; use System.Machine_Code; - procedure Nothing is - begin - Asm ("nop"); - end Nothing; - @end group - @end smallexample - - @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction. - @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions. - - The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}. - - Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}. You can build the executable in the usual way: - @smallexample - gnatmake nothing - @end smallexample - However, the interesting aspect of this example is not its run-time behavior but rather the - generated assembly code. To see this output, invoke the compiler as follows: - @smallexample - gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb} - @end smallexample - where the options are: - - @table @code - @item -c - compile only (no bind or link) - @item -S - generate assembler listing - @item -fomit-frame-pointer - do not set up separate stack frames - @item -gnatp - do not add runtime checks - @end table - - This gives a human-readable assembler version of the code. The resulting - file will have the same name as the Ada source file, but with a @code{.s} extension. - In our example, the file @file{nothing.s} has the following contents: - - @smallexample - @group - .file "nothing.adb" - gcc2_compiled.: - ___gnu_compiled_ada: - .text - .align 4 - .globl __ada_nothing - __ada_nothing: - #APP - nop - #NO_APP - jmp L1 - .align 2,0x90 - L1: - ret - @end group - @end smallexample - - The assembly code you included is clearly indicated by - the compiler, between the @code{#APP} and @code{#NO_APP} - delimiters. The character before the 'APP' and 'NOAPP' - can differ on different targets. For example, Linux uses '#APP' while - on NT you will see '/APP'. - - If you make a mistake in your assembler code (such as using the - wrong size modifier, or using a wrong operand for the instruction) GNAT - will report this error in a temporary file, which will be deleted when - the compilation is finished. Generating an assembler file will help - in such cases, since you can assemble this file separately using the - @emph{as} assembler that comes with gcc. - - Assembling the file using the command - - @smallexample - as @file{nothing.s} - @end smallexample - @noindent - will give you error messages whose lines correspond to the assembler - input file, so you can easily find and correct any mistakes you made. - If there are no errors, @emph{as} will generate an object file @file{nothing.out}. - - @c --------------------------------------------------------------------------- - @node Output Variables in Inline Assembler - @section Output Variables in Inline Assembler - - @noindent - The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements. - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags; - @end group - @end smallexample - - In order to have a nicely aligned assembly listing, we have separated - multiple assembler statements in the Asm template string with linefeed (ASCII.LF) - and horizontal tab (ASCII.HT) characters. The resulting section of the - assembly output file is: - - @smallexample - @group - #APP - pushfl - popl %eax - movl %eax, -40(%ebp) - #NO_APP - @end group - @end smallexample - - It would have been legal to write the Asm invocation as: - - @smallexample - Asm ("pushfl popl %%eax movl %%eax, %0") - @end smallexample - - but in the generated assembler file, this would come out as: - - @smallexample - #APP - pushfl popl %eax movl %eax, -40(%ebp) - #NO_APP - @end smallexample - - which is not so convenient for the human reader. - - We use Ada comments - at the end of each line to explain what the assembler instructions - actually do. This is a useful convention. - - When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign. Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}. In the generated assembly code, one of the percent signs will be stripped off. - - Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}. - An output variable is illustrated in - the third statement in the Asm template string: - @smallexample - movl %%eax, %0 - @end smallexample - The intent is to store the contents of the eax register in a variable that can be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization. The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable. - - Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}: - @smallexample - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end smallexample - - The output is defined by the @code{Asm_Output} attribute of the target type; the general format is - @smallexample - Type'Asm_Output (constraint_string, variable_name) - @end smallexample - - The constraint string directs the compiler how - to store/access the associated variable. In the example - @smallexample - Unsigned_32'Asm_Output ("=m", Flags); - @end smallexample - the @code{"m"} (memory) constraint tells the compiler that the variable - @code{Flags} should be stored in a memory variable, thus preventing - the optimizer from keeping it in a register. In contrast, - @smallexample - Unsigned_32'Asm_Output ("=r", Flags); - @end smallexample - uses the @code{"r"} (register) constraint, telling the compiler to - store the variable in a register. - - If the constraint is preceded by the equal character (@strong{=}), it tells the - compiler that the variable will be used to store data into it. - - In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer - to choose whatever it deems best. - - There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following: - - @table @code - @item = - output constraint - @item g - global (i.e. can be stored anywhere) - @item m - in memory - @item I - a constant - @item a - use eax - @item b - use ebx - @item c - use ecx - @item d - use edx - @item S - use esi - @item D - use edi - @item r - use one of eax, ebx, ecx or edx - @item q - use one of eax, ebx, ecx, edx, esi or edi - @end table - - The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string. - - You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer. Thus in - @smallexample - @group - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end group - @end smallexample - @noindent - @code{%0} will be replaced in the expanded code by the appropriate operand, - whatever - the compiler decided for the @code{Flags} variable. - - In general, you may have any number of output variables: - @itemize @bullet - @item - Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. - @item - Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes - @end itemize - - For example: - @smallexample - @group - Asm ("movl %%eax, %0" & LF & HT & - "movl %%ebx, %1" & LF & HT & - "movl %%ecx, %2", - Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A - Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B - Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C - @end group - @end smallexample - @noindent - where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program. - - As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_2 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax", -- save flags in eax - Outputs => Unsigned_32'Asm_Output ("=a", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_2; - @end group - @end smallexample - - @noindent - The @code{"a"} constraint tells the compiler that the @code{Flags} - variable will come from the eax register. Here is the resulting code: - - @smallexample - @group - #APP - pushfl - popl %eax - #NO_APP - movl %eax,-40(%ebp) - @end group - @end smallexample - - @noindent - The compiler generated the store of eax into Flags after - expanding the assembler code. - - Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_3 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "pop %0", -- save flags in Flags - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_3; - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Input Variables in Inline Assembler - @section Input Variables in Inline Assembler - - @noindent - The example in this section illustrates how to specify the source operands for assembly language statements. The program simply increments its input value by 1: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Incr (Value); - Put_Line ("Value after is" & Value'Img); - end Increment; - @end group - @end smallexample - - The @code{Outputs} parameter to @code{Asm} specifies - that the result will be in the eax register and that it is to be stored in the @code{Result} - variable. - - The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an - @code{Asm_Input} attribute. The - @code{"="} constraint, indicating an output value, is not present. - - You can have multiple input variables, in the same way that you can have more - than one output variable. - - The parameter count (%0, %1) etc, now starts at the first input - statement, and continues with the output statements. - When both parameters use the same variable, the - compiler will treat them as the same %n operand, which is the case here. - - Just as the @code{Outputs} parameter causes the register to be stored into the - target variable after execution of the assembler statements, so does the - @code{Inputs} parameter cause its variable to be loaded into the register before execution - of the - assembler statements. - - Thus the effect of the @code{Asm} invocation is: - @enumerate - @item load the 32-bit value of @code{Value} into eax - @item execute the @code{incl %eax} instruction - @item store the contents of eax into the @code{Result} variable - @end enumerate - - The resulting assembler file (with @code{-O2} optimization) contains: - @smallexample - @group - _increment__incr.1: - subl $4,%esp - movl 8(%esp),%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - movl %ecx,(%esp) - addl $4,%esp - ret - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Inlining Inline Assembler Code - @section Inlining Inline Assembler Code - - @noindent - For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame) - can be significant, compared to the amount of code in the subprogram body. - A solution is to apply Ada's @code{Inline} pragma to the subprogram, - which directs the compiler to expand invocations of the subprogram at the point(s) - of call, instead of setting up a stack frame for out-of-line calls. - Here is the resulting program: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment_2 is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - pragma Inline (Increment); - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Increment (Value); - Put_Line ("Value after is" & Value'Img); - end Increment_2; - @end group - @end smallexample - - Compile the program with both optimization (@code{-O2}) and inlining - enabled (@option{-gnatpn} instead of @option{-gnatp}). - - The @code{Incr} function is still compiled as usual, but at the - point in @code{Increment} where our function used to be called: - - @smallexample - @group - pushl %edi - call _increment__incr.1 - @end group - @end smallexample - - @noindent - the code for the function body directly appears: - - @smallexample - @group - movl %esi,%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - @end group - @end smallexample - - @noindent - thus saving the overhead of stack frame setup and an out-of-line call. - - @c --------------------------------------------------------------------------- - @node Other Asm Functionality - @section Other @code{Asm} Functionality - - @noindent - This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations. - - @menu - * The Clobber Parameter:: - * The Volatile Parameter:: - @end menu - - @c --------------------------------------------------------------------------- - @node The Clobber Parameter - @subsection The @code{Clobber} Parameter - - @noindent - One of the dangers of intermixing assembly language and a compiled language such as Ada is - that the compiler needs to be aware of which registers are being used by the assembly code. - In some cases, such as the earlier examples, the constraint string is sufficient to - indicate register usage (e.g. "a" for the eax register). But more generally, the - compiler needs an explicit identification of the registers that are used by the Inline - Assembly statements. - - Using a register that the compiler doesn't know about - could be a side effect of an instruction (like @code{mull} - storing its result in both eax and edx). - It can also arise from explicit register usage in your - assembly code; for example: - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out)); - @end group - @end smallexample - @noindent - where the compiler (since it does not analyze the @code{Asm} template string) - does not know you are using the ebx register. - - In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, - to identify the registers that will be used by your assembly code: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx"); - @end group - @end smallexample - - The Clobber parameter is a static string expression specifying the - register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign. - Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"} - - The @code{Clobber} parameter has several additional uses: - @enumerate - @item Use the "register" name @code{cc} to indicate that flags might have changed - @item Use the "register" name @code{memory} if you changed a memory location - @end enumerate - - @c --------------------------------------------------------------------------- - @node The Volatile Parameter - @subsection The @code{Volatile} Parameter - @cindex Volatile parameter - - @noindent - Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects. - For example, when - an @code{Asm} invocation with an input variable is inside a loop, the compiler might move - the loading of the input variable outside the loop, regarding it as a - one-time initialization. - - If this effect is not desired, you can disable such optimizations by setting the - @code{Volatile} parameter to @code{True}; for example: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx", - Volatile => True); - @end group - @end smallexample - - By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs} - parameter. - - Although setting @code{Volatile} to @code{True} prevents unwanted optimizations, - it will also disable other optimizations that might be important for efficiency. - In general, you should set @code{Volatile} to @code{True} only if the compiler's - optimizations have created problems. - - @c --------------------------------------------------------------------------- - @node A Complete Example - @section A Complete Example - - @noindent - This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler - capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}. - The package declares a collection of functions that detect the properties of the 32-bit - x86 processor that is running the program. The main procedure invokes these functions - and displays the information. - - The Intel_CPU package could be enhanced by adding functions to - detect the type of x386 co-processor, the processor caching options and - special operations such as the SIMD extensions. - - Although the Intel_CPU package has been written for 32-bit Intel - compatible CPUs, it is OS neutral. It has been tested on DOS, - Windows/NT and Linux. - - @menu - * Check_CPU Procedure:: - * Intel_CPU Package Specification:: - * Intel_CPU Package Body:: - @end menu - - @c --------------------------------------------------------------------------- - @node Check_CPU Procedure - @subsection @code{Check_CPU} Procedure - @cindex Check_CPU procedure - - @smallexample - --------------------------------------------------------------------- - -- -- - -- Uses the Intel_CPU package to identify the CPU the program is -- - -- running on, and some of the features it supports. -- - -- -- - --------------------------------------------------------------------- - - with Intel_CPU; -- Intel CPU detection functions - with Ada.Text_IO; -- Standard text I/O - with Ada.Command_Line; -- To set the exit status - - procedure Check_CPU is - - Type_Found : Boolean := False; - -- Flag to indicate that processor was identified - - Features : Intel_CPU.Processor_Features; - -- The processor features - - Signature : Intel_CPU.Processor_Signature; - -- The processor type signature - - begin - - ----------------------------------- - -- Display the program banner. -- - ----------------------------------- - - Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name & - ": check Intel CPU version and features, v1.0"); - Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever"); - Ada.Text_IO.New_Line; - - ----------------------------------------------------------------------- - -- We can safely start with the assumption that we are on at least -- - -- a x386 processor. If the CPUID instruction is present, then we -- - -- have a later processor type. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Has_CPUID = False then - - -- No CPUID instruction, so we assume this is indeed a x386 - -- processor. We can still check if it has a FP co-processor. - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line - ("x386-type processor with a FP co-processor"); - else - Ada.Text_IO.Put_Line - ("x386-type processor without a FP co-processor"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check for CPUID - - ----------------------------------------------------------------------- - -- If CPUID is supported, check if this is a true Intel processor, -- - -- if it is not, display a warning. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then - Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor"); - Ada.Text_IO.Put_Line ("*** Some information may be incorrect"); - end if; -- check if Intel - - ---------------------------------------------------------------------- - -- With the CPUID instruction present, we can assume at least a -- - -- x486 processor. If the CPUID support level is < 1 then we have -- - -- to leave it at that. -- - ---------------------------------------------------------------------- - - if Intel_CPU.CPUID_Level < 1 then - - -- Ok, this is a x486 processor. we still can get the Vendor ID - Ada.Text_IO.Put_Line ("x486-type processor"); - Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID); - - -- We can also check if there is a FPU present - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line ("Floating-Point support"); - else - Ada.Text_IO.Put_Line ("No Floating-Point support"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check CPUID level - - --------------------------------------------------------------------- - -- With a CPUID level of 1 we can use the processor signature to -- - -- determine it's exact type. -- - --------------------------------------------------------------------- - - Signature := Intel_CPU.Signature; - - ---------------------------------------------------------------------- - -- Ok, now we go into a lot of messy comparisons to get the -- - -- processor type. For clarity, no attememt to try to optimize the -- - -- comparisons has been made. Note that since Intel_CPU does not -- - -- support getting cache info, we cannot distinguish between P5 -- - -- and Celeron types yet. -- - ---------------------------------------------------------------------- - - -- x486SL - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486SL processor"); - end if; - - -- x486DX2 Write-Back - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0111# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor"); - end if; - - -- x486DX4 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 processor"); - end if; - - -- x486DX4 Overdrive - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor"); - end if; - - -- Pentium (60, 66) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium processor (60, 66)"); - end if; - - -- Pentium (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive (60, 66) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)"); - end if; - - -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive processor for x486 processor-based systems - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor for x486 processor-based systems"); - end if; - - -- Pentium processor with MMX technology (166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor with MMX technology (166, 200)"); - end if; - - -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor with MMX " & - "technology for Pentium processor (75, 90, 100, 120, 133)"); - end if; - - -- Pentium Pro processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro processor"); - end if; - - -- Pentium II processor, model 3 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium II processor, model 3"); - end if; - - -- Pentium II processor, model 5 or Celeron processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0101# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium II processor, model 5 or Celeron processor"); - end if; - - -- Pentium Pro OverDrive processor - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor"); - end if; - - -- If no type recognized, we have an unknown. Display what - -- we _do_ know - if Type_Found = False then - Ada.Text_IO.Put_Line ("Unknown processor"); - end if; - - ----------------------------------------- - -- Display processor stepping level. -- - ----------------------------------------- - - Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img); - - --------------------------------- - -- Display vendor ID string. -- - --------------------------------- - - Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID); - - ------------------------------------ - -- Get the processors features. -- - ------------------------------------ - - Features := Intel_CPU.Features; - - ----------------------------- - -- Check for a FPU unit. -- - ----------------------------- - - if Features.FPU = True then - Ada.Text_IO.Put_Line ("Floating-Point unit available"); - else - Ada.Text_IO.Put_Line ("no Floating-Point unit"); - end if; -- check for FPU - - -------------------------------- - -- List processor features. -- - -------------------------------- - - Ada.Text_IO.Put_Line ("Supported features: "); - - -- Virtual Mode Extension - if Features.VME = True then - Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension"); - end if; - - -- Debugging Extension - if Features.DE = True then - Ada.Text_IO.Put_Line (" DE - Debugging Extension"); - end if; - - -- Page Size Extension - if Features.PSE = True then - Ada.Text_IO.Put_Line (" PSE - Page Size Extension"); - end if; - - -- Time Stamp Counter - if Features.TSC = True then - Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter"); - end if; - - -- Model Specific Registers - if Features.MSR = True then - Ada.Text_IO.Put_Line (" MSR - Model Specific Registers"); - end if; - - -- Physical Address Extension - if Features.PAE = True then - Ada.Text_IO.Put_Line (" PAE - Physical Address Extension"); - end if; - - -- Machine Check Extension - if Features.MCE = True then - Ada.Text_IO.Put_Line (" MCE - Machine Check Extension"); - end if; - - -- CMPXCHG8 instruction supported - if Features.CX8 = True then - Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction"); - end if; - - -- on-chip APIC hardware support - if Features.APIC = True then - Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support"); - end if; - - -- Fast System Call - if Features.SEP = True then - Ada.Text_IO.Put_Line (" SEP - Fast System Call"); - end if; - - -- Memory Type Range Registers - if Features.MTRR = True then - Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers"); - end if; - - -- Page Global Enable - if Features.PGE = True then - Ada.Text_IO.Put_Line (" PGE - Page Global Enable"); - end if; - - -- Machine Check Architecture - if Features.MCA = True then - Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture"); - end if; - - -- Conditional Move Instruction Supported - if Features.CMOV = True then - Ada.Text_IO.Put_Line - (" CMOV - Conditional Move Instruction Supported"); - end if; - - -- Page Attribute Table - if Features.PAT = True then - Ada.Text_IO.Put_Line (" PAT - Page Attribute Table"); - end if; - - -- 36-bit Page Size Extension - if Features.PSE_36 = True then - Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension"); - end if; - - -- MMX technology supported - if Features.MMX = True then - Ada.Text_IO.Put_Line (" MMX - MMX technology supported"); - end if; - - -- Fast FP Save and Restore - if Features.FXSR = True then - Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore"); - end if; - - --------------------- - -- Program done. -- - --------------------- - - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - - exception - - when others => - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); - raise; - - end Check_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Specification - @subsection @code{Intel_CPU} Package Specification - @cindex Intel_CPU package specification - - @smallexample - ------------------------------------------------------------------------- - -- -- - -- file: intel_cpu.ads -- - -- -- - -- ********************************************* -- - -- * WARNING: for 32-bit Intel processors only * -- - -- ********************************************* -- - -- -- - -- This package contains a number of subprograms that are useful in -- - -- determining the Intel x86 CPU (and the features it supports) on -- - -- which the program is running. -- - -- -- - -- The package is based upon the information given in the Intel -- - -- Application Note AP-485: "Intel Processor Identification and the -- - -- CPUID Instruction" as of April 1998. This application note can be -- - -- found on www.intel.com. -- - -- -- - -- It currently deals with 32-bit processors only, will not detect -- - -- features added after april 1998, and does not guarantee proper -- - -- results on Intel-compatible processors. -- - -- -- - -- Cache info and x386 fpu type detection are not supported. -- - -- -- - -- This package does not use any privileged instructions, so should -- - -- work on any OS running on a 32-bit Intel processor. -- - -- -- - ------------------------------------------------------------------------- - - with Interfaces; use Interfaces; - -- for using unsigned types - - with System.Machine_Code; use System.Machine_Code; - -- for using inline assembler code - - with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; - -- for inserting control characters - - package Intel_CPU is - - ---------------------- - -- Processor bits -- - ---------------------- - - subtype Num_Bits is Natural range 0 .. 31; - -- the number of processor bits (32) - - -------------------------- - -- Processor register -- - -------------------------- - - -- define a processor register type for easy access to - -- the individual bits - - type Processor_Register is array (Num_Bits) of Boolean; - pragma Pack (Processor_Register); - for Processor_Register'Size use 32; - - ------------------------- - -- Unsigned register -- - ------------------------- - - -- define a processor register type for easy access to - -- the individual bytes - - type Unsigned_Register is - record - L1 : Unsigned_8; - H1 : Unsigned_8; - L2 : Unsigned_8; - H2 : Unsigned_8; - end record; - - for Unsigned_Register use - record - L1 at 0 range 0 .. 7; - H1 at 0 range 8 .. 15; - L2 at 0 range 16 .. 23; - H2 at 0 range 24 .. 31; - end record; - - for Unsigned_Register'Size use 32; - - --------------------------------- - -- Intel processor vendor ID -- - --------------------------------- - - Intel_Processor : constant String (1 .. 12) := "GenuineIntel"; - -- indicates an Intel manufactured processor - - ------------------------------------ - -- Processor signature register -- - ------------------------------------ - - -- a register type to hold the processor signature - - type Processor_Signature is - record - Stepping : Natural range 0 .. 15; - Model : Natural range 0 .. 15; - Family : Natural range 0 .. 15; - Processor_Type : Natural range 0 .. 3; - Reserved : Natural range 0 .. 262143; - end record; - - for Processor_Signature use - record - Stepping at 0 range 0 .. 3; - Model at 0 range 4 .. 7; - Family at 0 range 8 .. 11; - Processor_Type at 0 range 12 .. 13; - Reserved at 0 range 14 .. 31; - end record; - - for Processor_Signature'Size use 32; - - ----------------------------------- - -- Processor features register -- - ----------------------------------- - - -- a processor register to hold the processor feature flags - - type Processor_Features is - record - FPU : Boolean; -- floating point unit on chip - VME : Boolean; -- virtual mode extension - DE : Boolean; -- debugging extension - PSE : Boolean; -- page size extension - TSC : Boolean; -- time stamp counter - MSR : Boolean; -- model specific registers - PAE : Boolean; -- physical address extension - MCE : Boolean; -- machine check extension - CX8 : Boolean; -- cmpxchg8 instruction - APIC : Boolean; -- on-chip apic hardware - Res_1 : Boolean; -- reserved for extensions - SEP : Boolean; -- fast system call - MTRR : Boolean; -- memory type range registers - PGE : Boolean; -- page global enable - MCA : Boolean; -- machine check architecture - CMOV : Boolean; -- conditional move supported - PAT : Boolean; -- page attribute table - PSE_36 : Boolean; -- 36-bit page size extension - Res_2 : Natural range 0 .. 31; -- reserved for extensions - MMX : Boolean; -- MMX technology supported - FXSR : Boolean; -- fast FP save and restore - Res_3 : Natural range 0 .. 127; -- reserved for extensions - end record; - - for Processor_Features use - record - FPU at 0 range 0 .. 0; - VME at 0 range 1 .. 1; - DE at 0 range 2 .. 2; - PSE at 0 range 3 .. 3; - TSC at 0 range 4 .. 4; - MSR at 0 range 5 .. 5; - PAE at 0 range 6 .. 6; - MCE at 0 range 7 .. 7; - CX8 at 0 range 8 .. 8; - APIC at 0 range 9 .. 9; - Res_1 at 0 range 10 .. 10; - SEP at 0 range 11 .. 11; - MTRR at 0 range 12 .. 12; - PGE at 0 range 13 .. 13; - MCA at 0 range 14 .. 14; - CMOV at 0 range 15 .. 15; - PAT at 0 range 16 .. 16; - PSE_36 at 0 range 17 .. 17; - Res_2 at 0 range 18 .. 22; - MMX at 0 range 23 .. 23; - FXSR at 0 range 24 .. 24; - Res_3 at 0 range 25 .. 31; - end record; - - for Processor_Features'Size use 32; - - ------------------- - -- Subprograms -- - ------------------- - - function Has_FPU return Boolean; - -- return True if a FPU is found - -- use only if CPUID is not supported - - function Has_CPUID return Boolean; - -- return True if the processor supports the CPUID instruction - - function CPUID_Level return Natural; - -- return the CPUID support level (0, 1 or 2) - -- can only be called if the CPUID instruction is supported - - function Vendor_ID return String; - -- return the processor vendor identification string - -- can only be called if the CPUID instruction is supported - - function Signature return Processor_Signature; - -- return the processor signature - -- can only be called if the CPUID instruction is supported - - function Features return Processor_Features; - -- return the processors features - -- can only be called if the CPUID instruction is supported - - private - - ------------------------ - -- EFLAGS bit names -- - ------------------------ - - ID_Flag : constant Num_Bits := 21; - -- ID flag bit - - end Intel_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Body - @subsection @code{Intel_CPU} Package Body - @cindex Intel_CPU package body - - @smallexample - package body Intel_CPU is - - --------------------------- - -- Detect FPU presence -- - --------------------------- - - -- There is a FPU present if we can set values to the FPU Status - -- and Control Words. - - function Has_FPU return Boolean is - - Register : Unsigned_16; - -- processor register to store a word - - begin - - -- check if we can change the status word - Asm ( - - -- the assembler code - "finit" & LF & HT & -- reset status word - "movw $0x5A5A, %%ax" & LF & HT & -- set value status word - "fnstsw %0" & LF & HT & -- save status word - "movw %%ax, %0", -- store status word - - -- output stored in Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register), - - -- tell compiler that we used eax - Clobber => "eax"); - - -- if the status word is zero, there is no FPU - if Register = 0 then - return False; -- no status word - end if; -- check status word value - - -- check if we can get the control word - Asm ( - - -- the assembler code - "fnstcw %0", -- save the control word - - -- output into Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register)); - - -- check the relevant bits - if (Register and 16#103F#) /= 16#003F# then - return False; -- no control word - end if; -- check control word value - - -- FPU found - return True; - - end Has_FPU; - - -------------------------------- - -- Detect CPUID instruction -- - -------------------------------- - - -- The processor supports the CPUID instruction if it is possible - -- to change the value of ID flag bit in the EFLAGS register. - - function Has_CPUID return Boolean is - - Original_Flags, Modified_Flags : Processor_Register; - -- EFLAG contents before and after changing the ID flag - - begin - - -- try flipping the ID flag in the EFLAGS register - Asm ( - - -- the assembler code - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %%eax" & LF & HT & -- pop EFLAGS into eax - "movl %%eax, %0" & LF & HT & -- save EFLAGS content - "xor $0x200000, %%eax" & LF & HT & -- flip ID flag - "push %%eax" & LF & HT & -- push EFLAGS on stack - "popfl" & LF & HT & -- load EFLAGS register - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %1", -- save EFLAGS content - - -- output values, may be anything - -- Original_Flags is %0 - -- Modified_Flags is %1 - Outputs => - (Processor_Register'Asm_output ("=g", Original_Flags), - Processor_Register'Asm_output ("=g", Modified_Flags)), - - -- tell compiler eax is destroyed - Clobber => "eax"); - - -- check if CPUID is supported - if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then - return True; -- ID flag was modified - else - return False; -- ID flag unchanged - end if; -- check for CPUID - - end Has_CPUID; - - ------------------------------- - -- Get CPUID support level -- - ------------------------------- - - function CPUID_Level return Natural is - - Level : Unsigned_32; - -- returned support level - - begin - - -- execute CPUID, storing the results in the Level register - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero is stored in eax - -- returning the support level in eax - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- eax is stored in Level - Outputs => Unsigned_32'Asm_output ("=a", Level), - - -- tell compiler ebx, ecx and edx registers are destroyed - Clobber => "ebx, ecx, edx"); - - -- return the support level - return Natural (Level); - - end CPUID_Level; - - -------------------------------- - -- Get CPU Vendor ID String -- - -------------------------------- - - -- The vendor ID string is returned in the ebx, ecx and edx register - -- after executing the CPUID instruction with eax set to zero. - -- In case of a true Intel processor the string returned is - -- "GenuineIntel" - - function Vendor_ID return String is - - Ebx, Ecx, Edx : Unsigned_Register; - -- registers containing the vendor ID string - - Vendor_ID : String (1 .. 12); - -- the vendor ID string - - begin - - -- execute CPUID, storing the results in the processor registers - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero stored in eax - -- vendor ID string returned in ebx, ecx and edx - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- ebx is stored in Ebx - -- ecx is stored in Ecx - -- edx is stored in Edx - Outputs => (Unsigned_Register'Asm_output ("=b", Ebx), - Unsigned_Register'Asm_output ("=c", Ecx), - Unsigned_Register'Asm_output ("=d", Edx))); - - -- now build the vendor ID string - Vendor_ID( 1) := Character'Val (Ebx.L1); - Vendor_ID( 2) := Character'Val (Ebx.H1); - Vendor_ID( 3) := Character'Val (Ebx.L2); - Vendor_ID( 4) := Character'Val (Ebx.H2); - Vendor_ID( 5) := Character'Val (Edx.L1); - Vendor_ID( 6) := Character'Val (Edx.H1); - Vendor_ID( 7) := Character'Val (Edx.L2); - Vendor_ID( 8) := Character'Val (Edx.H2); - Vendor_ID( 9) := Character'Val (Ecx.L1); - Vendor_ID(10) := Character'Val (Ecx.H1); - Vendor_ID(11) := Character'Val (Ecx.L2); - Vendor_ID(12) := Character'Val (Ecx.H2); - - -- return string - return Vendor_ID; - - end Vendor_ID; - - ------------------------------- - -- Get processor signature -- - ------------------------------- - - function Signature return Processor_Signature is - - Result : Processor_Signature; - -- processor signature returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one is stored in eax - -- processor signature returned in eax - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- eax is stored in Result - Outputs => Processor_Signature'Asm_output ("=a", Result), - - -- tell compiler that ebx, ecx and edx are also destroyed - Clobber => "ebx, ecx, edx"); - - -- return processor signature - return Result; - - end Signature; - - ------------------------------ - -- Get processor features -- - ------------------------------ - - function Features return Processor_Features is - - Result : Processor_Features; - -- processor features returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one stored in eax - -- processor features returned in edx - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- edx is stored in Result - Outputs => Processor_Features'Asm_output ("=d", Result), - - -- tell compiler that ebx and ecx are also destroyed - Clobber => "ebx, ecx"); - - -- return processor signature - return Result; - - end Features; - - end Intel_CPU; - @end smallexample - @c END OF INLINE ASSEMBLER CHAPTER - @c =============================== - - @ifset wnt - @node Microsoft Windows Topics - @chapter Microsoft Windows Topics - @cindex Windows NT - @cindex Windows 95 - @cindex Windows 98 - - @noindent - This chapter describes topics that are specific to the Microsoft Windows - platforms (NT, 95 and 98). - - @menu - * Using GNAT on Windows:: - * GNAT Setup Tool:: - * CONSOLE and WINDOWS subsystems:: - * Temporary Files:: - * Mixed-Language Programming on Windows:: - * Windows Calling Conventions:: - * Introduction to Dynamic Link Libraries (DLLs):: - * Using DLLs with GNAT:: - * Building DLLs with GNAT:: - * GNAT and Windows Resources:: - * Debugging a DLL:: - * GNAT and COM/DCOM Objects:: - @end menu - - @node Using GNAT on Windows - @section Using GNAT on Windows - - @noindent - One of the strengths of the GNAT technology is that its tool set - (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the - @code{gdb} debugger, etc.) is used in the same way regardless of the - platform. - - On Windows this tool set is complemented by a number of Microsoft-specific - tools that have been provided to facilitate interoperability with Windows - when this is required. With these tools: - - @itemize @bullet - - @item - You can build applications using the @code{CONSOLE} or @code{WINDOWS} - subsystems. - - @item - You can use any Dynamically Linked Library (DLL) in your Ada code (both - relocatable and non-relocatable DLLs are supported). - - @item - You can build Ada DLLs for use in other applications. These applications - can be written in a language other than Ada (e.g., C, C++, etc). Again both - relocatable and non-relocatable Ada DLLs are supported. - - @item - You can include Windows resources in your Ada application. - - @item - You can use or create COM/DCOM objects. - @end itemize - - @noindent - Immediately below are listed all known general GNAT-for-Windows restrictions. - Other restrictions about specific features like Windows Resources and DLLs - are listed in separate sections below. - - @itemize @bullet - - @item - It is not possible to use @code{GetLastError} and @code{SetLastError} - when tasking, protected records, or exceptions are used. In these - cases, in order to implement Ada semantics, the GNAT run-time system - calls certain Win32 routines that set the last error variable to 0 upon - success. It should be possible to use @code{GetLastError} and - @code{SetLastError} when tasking, protected record, and exception - features are not used, but it is not guaranteed to work. - @end itemize - - @node GNAT Setup Tool - @section GNAT Setup Tool - @cindex GNAT Setup Tool - @cindex Setup Tool - @cindex gnatreg - - @menu - * Command-line arguments:: - * Creating a network installation of GNAT:: - * Registering and unregistering additional libraries:: - @end menu - - @noindent - GNAT installation on Windows is using the Windows registry in order to - locate proper executables and standard libraries. GNAT setup tool, called - @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific - registry entries, allowing to create network GNAT installations, modify the - locations of GNAT components, as well as register and unregister additional - libraries for use with GNAT. - - @node Command-line arguments - @subsection Command-line arguments - - @noindent - @code{gnatreg [switches] [parameter]} - - @noindent - Specifying no arguments causes gnatreg to display current configuration. - - @noindent - The switches understood by gnatreg are: - @table @asis - @item -h - print the help message - @item -a - add a standard library - @item -r - remove a standard library - @item -f - force creation of keys if they don't exist - @item -q - be quiet/terse - @end table - - @node Creating a network installation of GNAT - @subsection Creating a network installation of GNAT - - @noindent - Make sure the system on which GNAT is installed is accessible from the - current machine. - - Use the command - - @code{@ @ @ gnatreg -f \\server\sharename\path} - - in order to setup the registry entries on a current machine. - - For example, if GNAT is installed in @file{\GNAT} directory of a share location - called @file{c-drive} on a machine @file{LOKI}, the command that can be used on - other machines to allow the remote use of GNAT is, - - @code{@ @ @ gnatreg -f \\loki\c-drive\gnat} - - Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable. - - Be aware that every compilation using the network installation results in the - transfer of large amounts of data across the network and may cause serious - performance penalty. - - @node Registering and unregistering additional libraries - @subsection Registering and unregistering additional libraries - - @noindent - To register a standard library use a command: - - @code{@ @ @ gnatreg -a =} - - For example: - - @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada} - - The libraries registered in this manner will be treated like standard libraries - by the compiler (i.e. they don't have to be specified in -I and -l switches to - various GNAT tools). - - To unregister a library, enter - @code{ gnatreg -r } - - e.g., - @code{ gnatreg -r WIN32ADA} - - @node CONSOLE and WINDOWS subsystems - @section CONSOLE and WINDOWS subsystems - @cindex CONSOLE Subsystem - @cindex WINDOWS Subsystem - @cindex -mwindows - - @noindent - Under Windows there is two main subsystems. The @code{CONSOLE} subsystem - (which is the default subsystem) will always create a console when - launching the application. This is not something desirable when the - application has a Windows GUI. To get rid of this console the - application must be using the @code{WINDOWS} subsystem. To do so - the @code{-mwindows} linker option must be specified. - - @smallexample - $ gnatmake winprog -largs -mwindows - @end smallexample - - @node Temporary Files - @section Temporary Files - @cindex Temporary files - - @noindent - It is possible to control where temporary files gets created by setting - the TMP environment variable. The file will be created: - - @itemize - @item Under the directory pointed to by the TMP environment variable if - this directory exists. - - @item Under c:\temp, if the TMP environment variable is not set (or not - pointing to a directory) and if this directory exists. - - @item Under the current working directory otherwise. - @end itemize - - @noindent - This allows you to determine exactly where the temporary - file will be created. This is particularly useful in networked - environments where you may not have write access to some - directories. - - @node Mixed-Language Programming on Windows - @section Mixed-Language Programming on Windows - - @noindent - Developing pure Ada applications on Windows is no different than on - other GNAT-supported platforms. However, when developing or porting an - application that contains a mix of Ada and C/C++, the choice of your - Windows C/C++ development environment conditions your overall - interoperability strategy. - - If you use @code{gcc} to compile the non-Ada part of your application, - there are no Windows-specific restrictions that affect the overall - interoperability with your Ada code. If you plan to use - Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of - the following limitations: - - @itemize @bullet - @item - You cannot link your Ada code with an object or library generated with - Microsoft tools if these use the @code{.tls} section (Thread Local - Storage section) since the GNAT linker does not yet support this section. - - @item - You cannot link your Ada code with an object or library generated with - Microsoft tools if these use I/O routines other than those provided in - the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time - uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O - libraries can cause a conflict with @code{msvcrt.dll} services. For - instance Visual C++ I/O stream routines conflict with those in - @code{msvcrt.dll}. - @end itemize - - @noindent - If you do want to use the Microsoft tools for your non-Ada code and hit one - of the above limitations, you have two choices: - - @enumerate - @item - Encapsulate your non Ada code in a DLL to be linked with your Ada - application. In this case, use the Microsoft or whatever environment to - build the DLL and use GNAT to build your executable - (@pxref{Using DLLs with GNAT}). - - @item - Or you can encapsulate your Ada code in a DLL to be linked with the - other part of your application. In this case, use GNAT to build the DLL - (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever - environment to build your executable. - @end enumerate - - @node Windows Calling Conventions - @section Windows Calling Conventions - @findex Stdcall - @findex APIENTRY - - @menu - * C Calling Convention:: - * Stdcall Calling Convention:: - * DLL Calling Convention:: - @end menu - - @noindent - When a subprogram @code{F} (caller) calls a subprogram @code{G} - (callee), there are several ways to push @code{G}'s parameters on the - stack and there are several possible scenarios to clean up the stack - upon @code{G}'s return. A calling convention is an agreed upon software - protocol whereby the responsibilities between the caller (@code{F}) and - the callee (@code{G}) are clearly defined. Several calling conventions - are available for Windows: - - @itemize @bullet - @item - @code{C} (Microsoft defined) - - @item - @code{Stdcall} (Microsoft defined) - - @item - @code{DLL} (GNAT specific) - @end itemize - - @node C Calling Convention - @subsection @code{C} Calling Convention - - @noindent - This is the default calling convention used when interfacing to C/C++ - routines compiled with either @code{gcc} or Microsoft Visual C++. - - In the @code{C} calling convention subprogram parameters are pushed on the - stack by the caller from right to left. The caller itself is in charge of - cleaning up the stack after the call. In addition, the name of a routine - with @code{C} calling convention is mangled by adding a leading underscore. - - The name to use on the Ada side when importing (or exporting) a routine - with @code{C} calling convention is the name of the routine. For - instance the C function: - - @smallexample - int get_val (long); - @end smallexample - - @noindent - should be imported from Ada as follows: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (C, Get_Val, External_Name => "get_val"); - @end group - @end smallexample - - @noindent - Note that in this particular case the @code{External_Name} parameter could - have been omitted since, when missing, this parameter is taken to be the - name of the Ada entity in lower case. When the @code{Link_Name} parameter - is missing, as in the above example, this parameter is set to be the - @code{External_Name} with a leading underscore. - - When importing a variable defined in C, you should always use the @code{C} - calling convention unless the object containing the variable is part of a - DLL (in which case you should use the @code{DLL} calling convention, - @pxref{DLL Calling Convention}). - - @node Stdcall Calling Convention - @subsection @code{Stdcall} Calling Convention - - @noindent - This convention, which was the calling convention used for Pascal - programs, is used by Microsoft for all the routines in the Win32 API for - efficiency reasons. It must be used to import any routine for which this - convention was specified. - - In the @code{Stdcall} calling convention subprogram parameters are pushed - on the stack by the caller from right to left. The callee (and not the - caller) is in charge of cleaning the stack on routine exit. In addition, - the name of a routine with @code{Stdcall} calling convention is mangled by - adding a leading underscore (as for the @code{C} calling convention) and a - trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in - bytes) of the parameters passed to the routine. - - The name to use on the Ada side when importing a C routine with a - @code{Stdcall} calling convention is the name of the C routine. The leading - underscore and trailing @code{@@}@code{@i{nn}} are added automatically by - the compiler. For instance the Win32 function: - - @smallexample - @b{APIENTRY} int get_val (long); - @end smallexample - - @noindent - should be imported from Ada as follows: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (Stdcall, Get_Val); - -- @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4" - @end group - @end smallexample - - @noindent - As for the @code{C} calling convention, when the @code{External_Name} - parameter is missing, it is taken to be the name of the Ada entity in lower - case. If instead of writing the above import pragma you write: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val"); - @end group - @end smallexample - - @noindent - then the imported routine is @code{_retrieve_val@@4}. However, if instead - of specifying the @code{External_Name} parameter you specify the - @code{Link_Name} as in the following example: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val"); - @end group - @end smallexample - - @noindent - then the imported routine is @code{retrieve_val@@4}, that is, there is no - trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always - added at the end of the @code{Link_Name} by the compiler. - - @noindent - Note, that in some special cases a DLL's entry point name lacks a trailing - @code{@@}@code{@i{nn}} while the exported name generated for a call has it. - The @code{gnatdll} tool, which creates the import library for the DLL, is able - to handle those cases (see the description of the switches in - @pxref{Using gnatdll} section). - - @node DLL Calling Convention - @subsection @code{DLL} Calling Convention - - @noindent - This convention, which is GNAT-specific, must be used when you want to - import in Ada a variables defined in a DLL. For functions and procedures - this convention is equivalent to the @code{Stdcall} convention. As an - example, if a DLL contains a variable defined as: - - @smallexample - int my_var; - @end smallexample - - @noindent - then, to access this variable from Ada you should write: - - @smallexample - @group - My_Var : Interfaces.C.int; - @b{pragma} Import (DLL, My_Var); - @end group - @end smallexample - - The remarks concerning the @code{External_Name} and @code{Link_Name} - parameters given in the previous sections equally apply to the @code{DLL} - calling convention. - - @node Introduction to Dynamic Link Libraries (DLLs) - @section Introduction to Dynamic Link Libraries (DLLs) - @findex DLL - - @noindent - A Dynamically Linked Library (DLL) is a library that can be shared by - several applications running under Windows. A DLL can contain any number of - routines and variables. - - One advantage of DLLs is that you can change and enhance them without - forcing all the applications that depend on them to be relinked or - recompiled. However, you should be aware than all calls to DLL routines are - slower since, as you will understand below, such calls are indirect. - - To illustrate the remainder of this section, suppose that an application - wants to use the services of a DLL @file{API.dll}. To use the services - provided by @file{API.dll} you must statically link against an import - library which contains a jump table with an entry for each routine and - variable exported by the DLL. In the Microsoft world this import library is - called @file{API.lib}. When using GNAT this import library is called either - @file{libAPI.a} or @file{libapi.a} (names are case insensitive). - - After you have statically linked your application with the import library - and you run your application, here is what happens: - - @enumerate - @item - Your application is loaded into memory. - - @item - The DLL @file{API.dll} is mapped into the address space of your - application. This means that: - - @itemize @bullet - @item - The DLL will use the stack of the calling thread. - - @item - The DLL will use the virtual address space of the calling process. - - @item - The DLL will allocate memory from the virtual address space of the calling - process. - - @item - Handles (pointers) can be safely exchanged between routines in the DLL - routines and routines in the application using the DLL. - @end itemize - - @item - The entries in the @file{libAPI.a} or @file{API.lib} jump table which is - part of your application are initialized with the addresses of the routines - and variables in @file{API.dll}. - - @item - If present in @file{API.dll}, routines @code{DllMain} or - @code{DllMainCRTStartup} are invoked. These routines typically contain - the initialization code needed for the well-being of the routines and - variables exported by the DLL. - @end enumerate - - @noindent - There is an additional point which is worth mentioning. In the Windows - world there are two kind of DLLs: relocatable and non-relocatable - DLLs. Non-relocatable DLLs can only be loaded at a very specific address - in the target application address space. If the addresses of two - non-relocatable DLLs overlap and these happen to be used by the same - application, a conflict will occur and the application will run - incorrectly. Hence, when possible, it is always preferable to use and - build relocatable DLLs. Both relocatable and non-relocatable DLLs are - supported by GNAT. - - As a side note, an interesting difference between Microsoft DLLs and - Unix shared libraries, is the fact that on most Unix systems all public - routines are exported by default in a Unix shared library, while under - Windows the exported routines must be listed explicitly in a definition - file (@pxref{The Definition File}). - - @node Using DLLs with GNAT - @section Using DLLs with GNAT - - @menu - * Creating an Ada Spec for the DLL Services:: - * Creating an Import Library:: - @end menu - - @noindent - To use the services of a DLL, say @file{API.dll}, in your Ada application - you must have: - - @enumerate - @item - The Ada spec for the routines and/or variables you want to access in - @file{API.dll}. If not available this Ada spec must be built from the C/C++ - header files provided with the DLL. - - @item - The import library (@file{libAPI.a} or @file{API.lib}). As previously - mentioned an import library is a statically linked library containing the - import table which will be filled at load time to point to the actual - @file{API.dll} routines. Sometimes you don't have an import library for the - DLL you want to use. The following sections will explain how to build one. - - @item - The actual DLL, @file{API.dll}. - @end enumerate - - @noindent - Once you have all the above, to compile an Ada application that uses the - services of @file{API.dll} and whose main subprogram is @code{My_Ada_App}, - you simply issue the command - - @smallexample - $ gnatmake my_ada_app -largs -lAPI - @end smallexample - - @noindent - The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command - tells the GNAT linker to look first for a library named @file{API.lib} - (Microsoft-style name) and if not found for a library named @file{libAPI.a} - (GNAT-style name). Note that if the Ada package spec for @file{API.dll} - contains the following pragma - - @smallexample - @b{pragma} Linker_Options ("-lAPI"); - @end smallexample - - @noindent - you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake} - command. - - If any one of the items above is missing you will have to create it - yourself. The following sections explain how to do so using as an - example a fictitious DLL called @file{API.dll}. - - @node Creating an Ada Spec for the DLL Services - @subsection Creating an Ada Spec for the DLL Services - - @noindent - A DLL typically comes with a C/C++ header file which provides the - definitions of the routines and variables exported by the DLL. The Ada - equivalent of this header file is a package spec that contains definitions - for the imported entities. If the DLL you intend to use does not come with - an Ada spec you have to generate one such spec yourself. For example if - the header file of @file{API.dll} is a file @file{api.h} containing the - following two definitions: - - @smallexample - @group - @cartouche - int some_var; - int get (char *); - @end cartouche - @end group - @end smallexample - - @noindent - then the equivalent Ada spec could be: - - @smallexample - @group - @cartouche - @b{with} Interfaces.C.Strings; - @b{package} API @b{is} - @b{use} Interfaces; - - Some_Var : C.int; - @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int; - - @b{private} - @b{pragma} Import (C, Get); - @b{pragma} Import (DLL, Some_Var); - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - Note that a variable is @strong{always imported with a DLL convention}. A - function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For - subprograms, the @code{DLL} convention is a synonym of @code{Stdcall} - (@pxref{Windows Calling Conventions}). - - @node Creating an Import Library - @subsection Creating an Import Library - @cindex Import library - - @menu - * The Definition File:: - * GNAT-Style Import Library:: - * Microsoft-Style Import Library:: - @end menu - - @noindent - If a Microsoft-style import library @file{API.lib} or a GNAT-style - import library @file{libAPI.a} is available with @file{API.dll} you - can skip this section. Otherwise read on. - - @node The Definition File - @subsubsection The Definition File - @cindex Definition file - @findex .def - - @noindent - As previously mentioned, and unlike Unix systems, the list of symbols - that are exported from a DLL must be provided explicitly in Windows. - The main goal of a definition file is precisely that: list the symbols - exported by a DLL. A definition file (usually a file with a @code{.def} - suffix) has the following structure: - - @smallexample - @group - @cartouche - [LIBRARY @i{name}] - [DESCRIPTION @i{string}] - EXPORTS - @i{symbol1} - @i{symbol2} - ... - @end cartouche - @end group - @end smallexample - - @table @code - @item LIBRARY @i{name} - This section, which is optional, gives the name of the DLL. - - @item DESCRIPTION @i{string} - This section, which is optional, gives a description string that will be - embedded in the import library. - - @item EXPORTS - This section gives the list of exported symbols (procedures, functions or - variables). For instance in the case of @file{API.dll} the @code{EXPORTS} - section of @file{API.def} looks like: - - @smallexample - @group - @cartouche - EXPORTS - some_var - get - @end cartouche - @end group - @end smallexample - @end table - - @noindent - Note that you must specify the correct suffix (@code{@@}@code{@i{nn}}) - (@pxref{Windows Calling Conventions}) for a Stdcall - calling convention function in the exported symbols list. - - @noindent - There can actually be other sections in a definition file, but these - sections are not relevant to the discussion at hand. - - @node GNAT-Style Import Library - @subsubsection GNAT-Style Import Library - - @noindent - To create a static import library from @file{API.dll} with the GNAT tools - you should proceed as follows: - - @enumerate - @item - Create the definition file @file{API.def} (@pxref{The Definition File}). - For that use the @code{dll2def} tool as follows: - - @smallexample - $ dll2def API.dll > API.def - @end smallexample - - @noindent - @code{dll2def} is a very simple tool: it takes as input a DLL and prints - to standard output the list of entry points in the DLL. Note that if - some routines in the DLL have the @code{Stdcall} convention - (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn} - suffix then you'll have to edit @file{api.def} to add it. - - @noindent - Here are some hints to find the right @code{@@}@i{nn} suffix. - - @enumerate - @item - If you have the Microsoft import library (.lib), it is possible to get - the right symbols by using Microsoft @code{dumpbin} tool (see the - corresponding Microsoft documentation for further details). - - @smallexample - $ dumpbin /exports api.lib - @end smallexample - - @item - If you have a message about a missing symbol at link time the compiler - tells you what symbol is expected. You just have to go back to the - definition file and add the right suffix. - @end enumerate - - @item - Build the import library @code{libAPI.a}, using @code{gnatdll} - (@pxref{Using gnatdll}) as follows: - - @smallexample - $ gnatdll -e API.def -d API.dll - @end smallexample - - @noindent - @code{gnatdll} takes as input a definition file @file{API.def} and the - name of the DLL containing the services listed in the definition file - @file{API.dll}. The name of the static import library generated is - computed from the name of the definition file as follows: if the - definition file name is @i{xyz}@code{.def}, the import library name will - be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option - @code{-e} could have been removed because the name of the definition - file (before the "@code{.def}" suffix) is the same as the name of the - DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}). - @end enumerate - - @node Microsoft-Style Import Library - @subsubsection Microsoft-Style Import Library - - @noindent - With GNAT you can either use a GNAT-style or Microsoft-style import - library. A Microsoft import library is needed only if you plan to make an - Ada DLL available to applications developed with Microsoft - tools (@pxref{Mixed-Language Programming on Windows}). - - To create a Microsoft-style import library for @file{API.dll} you - should proceed as follows: - - @enumerate - @item - Create the definition file @file{API.def} from the DLL. For this use either - the @code{dll2def} tool as described above or the Microsoft @code{dumpbin} - tool (see the corresponding Microsoft documentation for further details). - - @item - Build the actual import library using Microsoft's @code{lib} utility: - - @smallexample - $ lib -machine:IX86 -def:API.def -out:API.lib - @end smallexample - - @noindent - If you use the above command the definition file @file{API.def} must - contain a line giving the name of the DLL: - - @smallexample - LIBRARY "API" - @end smallexample - - @noindent - See the Microsoft documentation for further details about the usage of - @code{lib}. - @end enumerate - - @node Building DLLs with GNAT - @section Building DLLs with GNAT - @cindex DLLs, building - - @menu - * Limitations When Using Ada DLLs from Ada:: - * Exporting Ada Entities:: - * Ada DLLs and Elaboration:: - * Ada DLLs and Finalization:: - * Creating a Spec for Ada DLLs:: - * Creating the Definition File:: - * Using gnatdll:: - @end menu - - @noindent - This section explains how to build DLLs containing Ada code. These DLLs - will be referred to as Ada DLLs in the remainder of this section. - - The steps required to build an Ada DLL that is to be used by Ada as well as - non-Ada applications are as follows: - - @enumerate - @item - You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or - @code{Stdcall} calling convention to avoid any Ada name mangling for the - entities exported by the DLL (@pxref{Exporting Ada Entities}). You can - skip this step if you plan to use the Ada DLL only from Ada applications. - - @item - Your Ada code must export an initialization routine which calls the routine - @code{adainit} generated by @code{gnatbind} to perform the elaboration of - the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization - routine exported by the Ada DLL must be invoked by the clients of the DLL - to initialize the DLL. - - @item - When useful, the DLL should also export a finalization routine which calls - routine @code{adafinal} generated by @code{gnatbind} to perform the - finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}). - The finalization routine exported by the Ada DLL must be invoked by the - clients of the DLL when the DLL services are no further needed. - - @item - You must provide a spec for the services exported by the Ada DLL in each - of the programming languages to which you plan to make the DLL available. - - @item - You must provide a definition file listing the exported entities - (@pxref{The Definition File}). - - @item - Finally you must use @code{gnatdll} to produce the DLL and the import - library (@pxref{Using gnatdll}). - @end enumerate - - @node Limitations When Using Ada DLLs from Ada - @subsection Limitations When Using Ada DLLs from Ada - - @noindent - When using Ada DLLs from Ada applications there is a limitation users - should be aware of. Because on Windows the GNAT run time is not in a DLL of - its own, each Ada DLL includes a part of the GNAT run time. Specifically, - each Ada DLL includes the services of the GNAT run time that are necessary - to the Ada code inside the DLL. As a result, when an Ada program uses an - Ada DLL there are two independent GNAT run times: one in the Ada DLL and - one in the main program. - - It is therefore not possible to exchange GNAT run-time objects between the - Ada DLL and the main Ada program. Example of GNAT run-time objects are file - handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects - types, etc. - - It is completely safe to exchange plain elementary, array or record types, - Windows object handles, etc. - - @node Exporting Ada Entities - @subsection Exporting Ada Entities - @cindex Export table - - @noindent - Building a DLL is a way to encapsulate a set of services usable from any - application. As a result, the Ada entities exported by a DLL should be - exported with the @code{C} or @code{Stdcall} calling conventions to avoid - any Ada name mangling. Please note that the @code{Stdcall} convention - should only be used for subprograms, not for variables. As an example here - is an Ada package @code{API}, spec and body, exporting two procedures, a - function, and a variable: - - @smallexample - @group - @cartouche - @b{with} Interfaces.C; @b{use} Interfaces; - @b{package} API @b{is} - Count : C.int := 0; - @b{function} Factorial (Val : C.int) @b{return} C.int; - - @b{procedure} Initialize_API; - @b{procedure} Finalize_API; - -- @i{Initialization & Finalization routines. More in the next section.} - @b{private} - @b{pragma} Export (C, Initialize_API); - @b{pragma} Export (C, Finalize_API); - @b{pragma} Export (C, Count); - @b{pragma} Export (C, Factorial); - @b{end} API; - @end cartouche - @end group - @end smallexample - - @smallexample - @group - @cartouche - @b{package body} API @b{is} - @b{function} Factorial (Val : C.int) @b{return} C.int @b{is} - Fact : C.int := 1; - @b{begin} - Count := Count + 1; - @b{for} K @b{in} 1 .. Val @b{loop} - Fact := Fact * K; - @b{end loop}; - @b{return} Fact; - @b{end} Factorial; - - @b{procedure} Initialize_API @b{is} - @b{procedure} Adainit; - @b{pragma} Import (C, Adainit); - @b{begin} - Adainit; - @b{end} Initialize_API; - - @b{procedure} Finalize_API @b{is} - @b{procedure} Adafinal; - @b{pragma} Import (C, Adafinal); - @b{begin} - Adafinal; - @b{end} Finalize_API; - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - If the Ada DLL you are building will only be used by Ada applications - you do not have to export Ada entities with a @code{C} or @code{Stdcall} - convention. As an example, the previous package could be written as - follows: - - @smallexample - @group - @cartouche - @b{package} API @b{is} - Count : Integer := 0; - @b{function} Factorial (Val : Integer) @b{return} Integer; - - @b{procedure} Initialize_API; - @b{procedure} Finalize_API; - -- @i{Initialization and Finalization routines.} - @b{end} API; - @end cartouche - @end group - @end smallexample - - @smallexample - @group - @cartouche - @b{package body} API @b{is} - @b{function} Factorial (Val : Integer) @b{return} Integer @b{is} - Fact : Integer := 1; - @b{begin} - Count := Count + 1; - @b{for} K @b{in} 1 .. Val @b{loop} - Fact := Fact * K; - @b{end loop}; - @b{return} Fact; - @b{end} Factorial; - - ... - -- @i{The remainder of this package body is unchanged.} - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - Note that if you do not export the Ada entities with a @code{C} or - @code{Stdcall} convention you will have to provide the mangled Ada names - in the definition file of the Ada DLL - (@pxref{Creating the Definition File}). - - @node Ada DLLs and Elaboration - @subsection Ada DLLs and Elaboration - @cindex DLLs and elaboration - - @noindent - The DLL that you are building contains your Ada code as well as all the - routines in the Ada library that are needed by it. The first thing a - user of your DLL must do is elaborate the Ada code - (@pxref{Elaboration Order Handling in GNAT}). - - To achieve this you must export an initialization routine - (@code{Initialize_API} in the previous example), which must be invoked - before using any of the DLL services. This elaboration routine must call - the Ada elaboration routine @code{adainit} generated by the GNAT binder - (@pxref{Binding with Non-Ada Main Programs}). See the body of - @code{Initialize_Api} for an example. Note that the GNAT binder is - automatically invoked during the DLL build process by the @code{gnatdll} - tool (@pxref{Using gnatdll}). - - When a DLL is loaded, Windows systematically invokes a routine called - @code{DllMain}. It would therefore be possible to call @code{adainit} - directly from @code{DllMain} without having to provide an explicit - initialization routine. Unfortunately, it is not possible to call - @code{adainit} from the @code{DllMain} if your program has library level - tasks because access to the @code{DllMain} entry point is serialized by - the system (that is, only a single thread can execute "through" it at a - time), which means that the GNAT run time will deadlock waiting for the - newly created task to complete its initialization. - - @node Ada DLLs and Finalization - @subsection Ada DLLs and Finalization - @cindex DLLs and finalization - - @noindent - When the services of an Ada DLL are no longer needed, the client code should - invoke the DLL finalization routine, if available. The DLL finalization - routine is in charge of releasing all resources acquired by the DLL. In the - case of the Ada code contained in the DLL, this is achieved by calling - routine @code{adafinal} generated by the GNAT binder - (@pxref{Binding with Non-Ada Main Programs}). - See the body of @code{Finalize_Api} for an - example. As already pointed out the GNAT binder is automatically invoked - during the DLL build process by the @code{gnatdll} tool - (@pxref{Using gnatdll}). - - @code{-g} - @cindex @code{-g} (@code{gnatdll}) - @* - Generate debugging information. This information is stored in the object - file and copied from there to the final DLL file by the linker, - where it can be read by the debugger. You must use the - @code{-g} switch if you plan on using the debugger or the symbolic - stack traceback. - - @node Creating a Spec for Ada DLLs - @subsection Creating a Spec for Ada DLLs - - @noindent - To use the services exported by the Ada DLL from another programming - language (e.g. C), you have to translate the specs of the exported Ada - entities in that language. For instance in the case of @code{API.dll}, - the corresponding C header file could look like: - - @smallexample - @group - @cartouche - extern int *__imp__count; - #define count (*__imp__count) - int factorial (int); - @end cartouche - @end group - @end smallexample - - @noindent - It is important to understand that when building an Ada DLL to be used by - other Ada applications, you need two different specs for the packages - contained in the DLL: one for building the DLL and the other for using - the DLL. This is because the @code{DLL} calling convention is needed to - use a variable defined in a DLL, but when building the DLL, the variable - must have either the @code{Ada} or @code{C} calling convention. As an - example consider a DLL comprising the following package @code{API}: - - @smallexample - @group - @cartouche - @b{package} API @b{is} - Count : Integer := 0; - ... - -- @i{Remainder of the package omitted.} - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - After producing a DLL containing package @code{API}, the spec that - must be used to import @code{API.Count} from Ada code outside of the - DLL is: - - @smallexample - @group - @cartouche - @b{package} API @b{is} - Count : Integer; - @b{pragma} Import (DLL, Count); - @b{end} API; - @end cartouche - @end group - @end smallexample - - @node Creating the Definition File - @subsection Creating the Definition File - - @noindent - The definition file is the last file needed to build the DLL. It lists - the exported symbols. As an example, the definition file for a DLL - containing only package @code{API} (where all the entities are exported - with a @code{C} calling convention) is: - - @smallexample - @group - @cartouche - EXPORTS - count - factorial - finalize_api - initialize_api - @end cartouche - @end group - @end smallexample - - @noindent - If the @code{C} calling convention is missing from package @code{API}, - then the definition file contains the mangled Ada names of the above - entities, which in this case are: - - @smallexample - @group - @cartouche - EXPORTS - api__count - api__factorial - api__finalize_api - api__initialize_api - @end cartouche - @end group - @end smallexample - - @node Using gnatdll - @subsection Using @code{gnatdll} - @findex gnatdll - - @menu - * gnatdll Example:: - * gnatdll behind the Scenes:: - * Using dlltool:: - @end menu - - @noindent - @code{gnatdll} is a tool to automate the DLL build process once all the Ada - and non-Ada sources that make up your DLL have been compiled. - @code{gnatdll} is actually in charge of two distinct tasks: build the - static import library for the DLL and the actual DLL. The form of the - @code{gnatdll} command is - - @smallexample - @cartouche - $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}] - @end cartouche - @end smallexample - - @noindent - where @i{list-of-files} is a list of ALI and object files. The object - file list must be the exact list of objects corresponding to the non-Ada - sources whose services are to be included in the DLL. The ALI file list - must be the exact list of ALI files for the corresponding Ada sources - whose services are to be included in the DLL. If @i{list-of-files} is - missing, only the static import library is generated. - - @noindent - You may specify any of the following switches to @code{gnatdll}: - - @table @code - @item -a[@var{address}] - @cindex @code{-a} (@code{gnatdll}) - Build a non-relocatable DLL at @var{address}. If @var{address} is not - specified the default address @var{0x11000000} will be used. By default, - when this switch is missing, @code{gnatdll} builds relocatable DLL. We - advise the reader to build relocatable DLL. - - @item -b @var{address} - @cindex @code{-b} (@code{gnatdll}) - Set the relocatable DLL base address. By default the address is - @var{0x11000000}. - - @item -d @var{dllfile} - @cindex @code{-d} (@code{gnatdll}) - @var{dllfile} is the name of the DLL. This switch must be present for - @code{gnatdll} to do anything. The name of the generated import library is - obtained algorithmically from @var{dllfile} as shown in the following - example: if @var{dllfile} is @code{xyz.dll}, the import library name is - @code{libxyz.a}. The name of the definition file to use (if not specified - by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in - the following example: if @var{dllfile} is @code{xyz.dll}, the definition - file used is @code{xyz.def}. - - @item -e @var{deffile} - @cindex @code{-e} (@code{gnatdll}) - @var{deffile} is the name of the definition file. - - @item -h - @cindex @code{-h} (@code{gnatdll}) - Help mode. Displays @code{gnatdll} switch usage information. - - @item -Idir - Direct @code{gnatdll} to search the @var{dir} directory for source and - object files needed to build the DLL. - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -k - Removes the @code{@@}@i{nn} suffix from the import library's exported - names. You must specified this option if you want to use a - @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix - has been removed. This is the case for most of the Windows NT DLL for - example. This option has no effect when @code{-n} option is specified. - - @item -l @var{file} - @cindex @code{-l} (@code{gnatdll}) - The list of ALI and object files used to build the DLL are listed in - @var{file}, instead of being given in the command line. Each line in - @var{file} contains the name of an ALI or object file. - - @item -n - @cindex @code{-n} (@code{gnatdll}) - No Import. Do not create the import library. - - @item -q - @cindex @code{-q} (@code{gnatdll}) - Quiet mode. Do not display unnecessary messages. - - @item -v - @cindex @code{-v} (@code{gnatdll}) - Verbose mode. Display extra information. - - @item -largs @var{opts} - @cindex @code{-largs} (@code{gnatdll}) - Linker options. Pass @var{opts} to the linker. - @end table - - @node gnatdll Example - @subsubsection @code{gnatdll} Example - - @noindent - As an example the command to build a relocatable DLL from @file{api.adb} - once @file{api.adb} has been compiled and @file{api.def} created is - - @smallexample - $ gnatdll -d api.dll api.ali - @end smallexample - - @noindent - The above command creates two files: @file{libapi.a} (the import - library) and @file{api.dll} (the actual DLL). If you want to create - only the DLL, just type: - - @smallexample - $ gnatdll -d api.dll -n api.ali - @end smallexample - - @noindent - Alternatively if you want to create just the import library, type: - - @smallexample - $ gnatdll -d api.dll - @end smallexample - - @node gnatdll behind the Scenes - @subsubsection @code{gnatdll} behind the Scenes - - @noindent - This section details the steps involved in creating a DLL. @code{gnatdll} - does these steps for you. Unless you are interested in understanding what - goes on behind the scenes, you should skip this section. - - We use the previous example of a DLL containing the Ada package @code{API}, - to illustrate the steps necessary to build a DLL. The starting point is a - set of objects that will make up the DLL and the corresponding ALI - files. In the case of this example this means that @file{api.o} and - @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does - the following: - - @enumerate - @item - @code{gnatdll} builds the base file (@file{api.base}). A base file gives - the information necessary to generate relocation information for the - DLL. - - @smallexample - @group - $ gnatbind -n api - $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base - @end group - @end smallexample - - @noindent - In addition to the base file, the @code{gnatlink} command generates an - output file @file{api.jnk} which can be discarded. The @code{-mdll} switch - asks @code{gnatlink} to generate the routines @code{DllMain} and - @code{DllMainCRTStartup} that are called by the Windows loader when the DLL - is loaded into memory. - - @item - @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the - export table (@file{api.exp}). The export table contains the relocation - information in a form which can be used during the final link to ensure - that the Windows loader is able to place the DLL anywhere in memory. - - @smallexample - @group - $ dlltool --dllname api.dll --def api.def --base-file api.base \ - --output-exp api.exp - @end group - @end smallexample - - @item - @code{gnatdll} builds the base file using the new export table. Note that - @code{gnatbind} must be called once again since the binder generated file - has been deleted during the previous call to @code{gnatlink}. - - @smallexample - @group - $ gnatbind -n api - $ gnatlink api -o api.jnk api.exp -mdll - -Wl,--base-file,api.base - @end group - @end smallexample - - @item - @code{gnatdll} builds the new export table using the new base file and - generates the DLL import library @file{libAPI.a}. - - @smallexample - @group - $ dlltool --dllname api.dll --def api.def --base-file api.base \ - --output-exp api.exp --output-lib libAPI.a - @end group - @end smallexample - - @item - Finally @code{gnatdll} builds the relocatable DLL using the final export - table. - - @smallexample - @group - $ gnatbind -n api - $ gnatlink api api.exp -o api.dll -mdll - @end group - @end smallexample - @end enumerate - - @node Using dlltool - @subsubsection Using @code{dlltool} - - @noindent - @code{dlltool} is the low-level tool used by @code{gnatdll} to build - DLLs and static import libraries. This section summarizes the most - common @code{dlltool} switches. The form of the @code{dlltool} command - is - - @smallexample - $ dlltool [@var{switches}] - @end smallexample - - @noindent - @code{dlltool} switches include: - - @table @code - @item --base-file @var{basefile} - Read the base file @var{basefile} generated by the linker. This switch - is used to create a relocatable DLL. - - @item --def @var{deffile} - Read the definition file. - - @item --dllname @var{name} - Gives the name of the DLL. This switch is used to embed the name of the - DLL in the static import library generated by @code{dlltool} with switch - @code{--output-lib}. - - @item -k - Kill @code{@@}@i{nn} from exported names - (@pxref{Windows Calling Conventions} - for a discussion about @code{Stdcall}-style symbols. - - @item --help - Prints the @code{dlltool} switches with a concise description. - - @item --output-exp @var{exportfile} - Generate an export file @var{exportfile}. The export file contains the - export table (list of symbols in the DLL) and is used to create the DLL. - - @item --output-lib @i{libfile} - Generate a static import library @var{libfile}. - - @item -v - Verbose mode. - - @item --as @i{assembler-name} - Use @i{assembler-name} as the assembler. The default is @code{as}. - @end table - - @node GNAT and Windows Resources - @section GNAT and Windows Resources - @cindex Resources, windows - - @menu - * Building Resources:: - * Compiling Resources:: - * Using Resources:: - * Limitations:: - @end menu - - @noindent - Resources are an easy way to add Windows specific objects to your - application. The objects that can be added as resources include: - - @itemize @bullet - @item - menus - - @item - accelerators - - @item - dialog boxes - - @item - string tables - - @item - bitmaps - - @item - cursors - - @item - icons - - @item - fonts - @end itemize - - @noindent - This section explains how to build, compile and use resources. - - @node Building Resources - @subsection Building Resources - @cindex Resources, building - - @noindent - A resource file is an ASCII file. By convention resource files have an - @file{.rc} extension. - The easiest way to build a resource file is to use Microsoft tools - such as @code{imagedit.exe} to build bitmaps, icons and cursors and - @code{dlgedit.exe} to build dialogs. - It is always possible to build an @file{.rc} file yourself by writing a - resource script. - - It is not our objective to explain how to write a resource file. A - complete description of the resource script language can be found in the - Microsoft documentation. - - @node Compiling Resources - @subsection Compiling Resources - @findex rc - @findex rcl - @findex res2coff - @cindex Resources, compiling - - @noindent - This section describes how to build a GNAT-compatible (COFF) object file - containing the resources. This is done using the Resource Compiler - @code{rcl} as follows: - - @smallexample - $ rcl -i myres.rc -o myres.o - @end smallexample - - @noindent - By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc} - file. You can specify an alternate preprocessor (usually named - @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of - all possible options may be obtained by entering the command @code{rcl} - with no parameters. - - It is also possible to use the Microsoft resource compiler @code{rc.exe} - to produce a @file{.res} file (binary resource file). See the - corresponding Microsoft documentation for further details. In this case - you need to use @code{res2coff} to translate the @file{.res} file to a - GNAT-compatible object file as follows: - - @smallexample - $ res2coff -i myres.res -o myres.o - @end smallexample - - @node Using Resources - @subsection Using Resources - @cindex Resources, using - - @noindent - To include the resource file in your program just add the - GNAT-compatible object file for the resource(s) to the linker - arguments. With @code{gnatmake} this is done by using the @code{-largs} - option: - - @smallexample - $ gnatmake myprog -largs myres.o - @end smallexample - - @node Limitations - @subsection Limitations - @cindex Resources, limitations - - @noindent - In this section we describe the current limitations together with - suggestions for workarounds. - - @itemize @bullet - @item - @code{rcl} does not handle the @code{RCINCLUDE} directive. - @* - Workaround: replace @code{RCINCLUDE} by an @code{#include} directive. - - @item - @code{rcl} does not handle the brackets as block delimiters. - @* - Workaround: replace character '@{' by @code{BEGIN} and '@}' by - @code{END}. Note that Microsoft's @code{rc} handles both forms of block - delimiters. - - @item - @code{rcl} does not handle @code{TypeLib} resources. This type of - resource is used to build COM, DCOM or ActiveX objects. - @* - Workaround: use @code{rc}, the Microsoft resource compiler. - - @item - It is not possible to use @code{strip} to remove the debugging symbols - from a program with resources. - @* - Workaround: use linker option @code{-s} to strip debugging symbols from - the final executable. - @end itemize - - @node Debugging a DLL - @section Debugging a DLL - @cindex DLL debugging - - @menu - * The Program and the DLL Are Built with GCC/GNAT:: - * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT:: - @end menu - - @noindent - Debugging a DLL is similar to debugging a standard program. But - we have to deal with two different executable parts: the DLL and the - program that uses it. We have the following four possibilities: - - @enumerate 1 - @item - The program and the DLL are built with @code{GCC/GNAT}. - @item - The program is built with foreign tools and the DLL is built with - @code{GCC/GNAT}. - @item - The program is built with @code{GCC/GNAT} and the DLL is built with - foreign tools. - @item - @end enumerate - - @noindent - In this section we address only cases one and two above. - There is no point in trying to debug - a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging - information in it. To do so you must use a debugger compatible with the - tools suite used to build the DLL. - - @node The Program and the DLL Are Built with GCC/GNAT - @subsection The Program and the DLL Are Built with GCC/GNAT - - @noindent - This is the simplest case. Both the DLL and the program have @code{GDB} - compatible debugging information. It is then possible to break anywhere in - the process. Let's suppose here that the main procedure is named - @code{ada_main} and that in the DLL there is an entry point named - @code{ada_dll}. - - @noindent - The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and - program must have been built with the debugging information (see GNAT -g - switch). Here are the step-by-step instructions for debugging it: - - @enumerate 1 - @item Launch @code{GDB} on the main program. - - @smallexample - $ gdb -nw ada_main - @end smallexample - - @item Break on the main procedure and run the program. - - @smallexample - (gdb) break ada_main - (gdb) run - @end smallexample - - @noindent - This step is required to be able to set a breakpoint inside the DLL. As long - as the program is not run, the DLL is not loaded. This has the - consequence that the DLL debugging information is also not loaded, so it is not - possible to set a breakpoint in the DLL. - - @item Set a breakpoint inside the DLL - - @smallexample - (gdb) break ada_dll - (gdb) run - @end smallexample - - @end enumerate - - @noindent - At this stage a breakpoint is set inside the DLL. From there on - you can use the standard approach to debug the whole program - (@pxref{Running and Debugging Ada Programs}). - - @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT - @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT - - @menu - * Debugging the DLL Directly:: - * Attaching to a Running Process:: - @end menu - - @noindent - In this case things are slightly more complex because it is not possible to - start the main program and then break at the beginning to load the DLL and the - associated DLL debugging information. It is not possible to break at the - beginning of the program because there is no @code{GDB} debugging information, - and therefore there is no direct way of getting initial control. This - section addresses this issue by describing some methods that can be used - to break somewhere in the DLL to debug it. - - @noindent - First suppose that the main procedure is named @code{main} (this is for - example some C code built with Microsoft Visual C) and that there is a - DLL named @code{test.dll} containing an Ada entry point named - @code{ada_dll}. - - @noindent - The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have - been built with debugging information (see GNAT -g option). - - @node Debugging the DLL Directly - @subsubsection Debugging the DLL Directly - - @enumerate 1 - @item - Launch the debugger on the DLL. - - @smallexample - $ gdb -nw test.dll - @end smallexample - - @item Set a breakpoint on a DLL subroutine. - - @smallexample - (gdb) break ada_dll - @end smallexample - - @item - Specify the executable file to @code{GDB}. - - @smallexample - (gdb) exec-file main.exe - @end smallexample - - @item - Run the program. - - @smallexample - (gdb) run - @end smallexample - - @noindent - This will run the program until it reaches the breakpoint that has been - set. From that point you can use the standard way to debug a program - as described in (@pxref{Running and Debugging Ada Programs}). - - @end enumerate - - @noindent - It is also possible to debug the DLL by attaching to a running process. - - @node Attaching to a Running Process - @subsubsection Attaching to a Running Process - @cindex DLL debugging, attach to process - - @noindent - With @code{GDB} it is always possible to debug a running process by - attaching to it. It is possible to debug a DLL this way. The limitation - of this approach is that the DLL must run long enough to perform the - attach operation. It may be useful for instance to insert a time wasting - loop in the code of the DLL to meet this criterion. - - @enumerate 1 - - @item Launch the main program @file{main.exe}. - - @smallexample - $ main - @end smallexample - - @item Use the Windows @i{Task Manager} to find the process ID. Let's say - that the process PID for @file{main.exe} is 208. - - @item Launch gdb. - - @smallexample - $ gdb -nw - @end smallexample - - @item Attach to the running process to be debugged. - - @smallexample - (gdb) attach 208 - @end smallexample - - @item Load the process debugging information. - - @smallexample - (gdb) symbol-file main.exe - @end smallexample - - @item Break somewhere in the DLL. - - @smallexample - (gdb) break ada_dll - @end smallexample - - @item Continue process execution. - - @smallexample - (gdb) continue - @end smallexample - - @end enumerate - - @noindent - This last step will resume the process execution, and stop at - the breakpoint we have set. From there you can use the standard - approach to debug a program as described in - (@pxref{Running and Debugging Ada Programs}). - - @node GNAT and COM/DCOM Objects - @section GNAT and COM/DCOM Objects - @findex COM - @findex DCOM - - @noindent - This section is temporarily left blank. - - @ignore - @reread - ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ?????????????????????? - - @node gnatreg : Registry Tool for NT - @section @code{gnatreg} : Registry Tool for NT - @findex gnatreg - @cindex Registry - - @menu - * Changing the GNAT compiler to Use:: - * Adding/Changing a Library Path:: - * Removing a Library Path:: - * List Current Configuration:: - @end menu - - @noindent - This tool can be used to switch from one compiler to another and to manage - the list of directories where GNAT must look to find packages. It is - also a convenient way to do network installation of GNAT. - - The form of the @code{gnatreg} command is - - @smallexample - $ gnatreg [@var{-hqcarf}] parameter - @end smallexample - - @noindent - Commons options are - - @table @code - - @item -h - print a usage message. - - @item -q - quiet/terse - display nothing, just do the job. - - @item -f - force mode - create the registry keys if they do not - exist. @code{gnatreg} will exit with an error if this option is omitted - and some registry keys are not setup correctly. - - @end table - - @subsection Changing the GNAT compiler to use - - @smallexample - $ gnatreg c:\gnatpro - @end smallexample - - @noindent - This will setup the registry to use the GNAT compiler that has been - installed under c:\gnatpro. @code{gnatreg} check that this directory contain - effectively a GNAT compiler. If you want to setup a network installation - and if GNAT has never been installed on this computer you'll have to use - the -f option. - - @subsection Adding/Changing a library path - - @smallexample - $ gnatreg -a COMPNT=c:\ada\components - @end smallexample - - @noindent - Add the directory c:\ada\components to the list of standards libraries. When - running gnatmake the option -Ic:\ada\components is added automatically to the - command line. - - The directory c:\ada\components is associated with the name COMPNT. This - name will be used to remove the library path. - - @subsection Removing a library path - - @smallexample - $ gnatreg -r COMPNT - @end smallexample - - @noindent - Remove the library path named COMPNT. - - @subsection List current configuration - - @smallexample - $ gnatreg -c - @end smallexample - - @noindent - @code{gnatreg} will display the GNAT and AdaGIDE path used and - all the standards libraries and their associated names that have been set. - - @end ignore - @end ifset - - @ifset vxworks - @node VxWorks Topics - @chapter VxWorks Topics - - @noindent - This chapter describes topics that are specific to the GNAT for VxWorks - configurations. - - @menu - * Kernel Configuration for VxWorks:: - * Kernel Compilation Issues for VxWorks:: - * Handling Relocation Issues for PowerPc Targets:: - * Support for Software Floating Point on PowerPC Processors:: - * Interrupt Handling for VxWorks:: - * Simulating Command Line Arguments for VxWorks:: - * Debugging Issues for VxWorks:: - * Using GNAT from the Tornado 2 Project Facility:: - * Frequently Asked Questions for VxWorks:: - @end menu - - @node Kernel Configuration for VxWorks - @section Kernel Configuration for VxWorks - - @noindent - When configuring your VxWorks kernel we recommend including the target - shell. If you omit it from the configuration, you may get undefined - symbols at load time, e.g. - - @smallexample - -> ld < hello.exe - Loading hello.exe - Undefined symbols: - mkdir - @end smallexample - - @noindent - Generally, such undefined symbols are harmless since these are used by - optional parts of the GNAT run time. However if running your application - generates a VxWorks exception or illegal instruction, you should reconfigure - your kernel to resolve these symbols. - - @node Kernel Compilation Issues for VxWorks - @section Kernel Compilation Issues for VxWorks - - @noindent - If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps. - (Note that these recommendations apply to @file{cygnus-2.7.2-960126}, - shipped with Tornado 2 as the C compiler toolchain.) - - @itemize @bullet - @item - Compile your Ada module without linking it with the VxWorks Library: - @smallexample - gnatmake foo.adb -largs -nostdlib - @end smallexample - - @item - Edit your makefile and add on the @code{LIBS} line the exact path and name - of the GCC library file provided with GNAT. - @smallexample - LIBS = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \ - /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a - @end smallexample - - @noindent - To know the exact name and location of this file, type - @code{-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the - one provided with GNAT. - @smallexample - ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name - /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a - @end smallexample - @end itemize - - - @node Handling Relocation Issues for PowerPc Targets - @section Handling Relocation Issues for PowerPc Targets - @cindex Relocation issues for PowerPc VxWorks targets - @cindex PowerPc VxWorks, relocation issues - @cindex VxWorks PowerPc, relocation issues - - @noindent - Under certain circumstances, loading a program onto a PowerPC - board will fail with the message - @emph{Relocation value does not fit in 24 bits}. - - For some background on this issue, please refer to WRS' SPRs - 6040, 20257, and 22767. - In summary, - VxWorks on the PowerPC follows the variation of the SVR4 ABI known - as the Embedded ABI (@emph{EABI}). - @cindex Embedded ABI (for VxWorks on PowerPc) - @cindex EABI (for VxWorks on PowerPc) - In order to save space and time in - embedded applications, the EABI specifies that the default for - subprogram calls should be the branch instruction with relative - addressing using an immediate operand. The immediate operand - to this instruction (relative address) is 24 bits wide. It - is sign extended and 2#00# is appended for the last 2 bits (all - instructions must be on a 4 byte boundary). - The resulting - 26 bit offset means that the target of the branch must be within - +/- 32 Mbytes of the relative branch instruction. When VxWorks - is loading a program it completes the linking phase by - resolving all of the unresolved references in the object being - loaded. When one of those references is a relative address in - a branch instruction, and the linker determines that the target - is more than 32 Mbytes away from the branch, the error occurs. - - This only happens when the BSP is configured to use - more than 32 MBytes of memory. The VxWorks kernel is loaded into - low memory addresses, and the error usually occurs when the target - loader is used (because it loads objects into high memory, and thus - calls from the program to the VxWorks kernel can be too far). - @cindex VxWorks kernel (relocation issues on PowerPc) - - One way to solve this problem is to use the Tornado - host loader; this will place programs in low memory, close to the kernel. - - Another approach is to make use of the @code{-mlongcall} option to the - compiler; - @cindex @code{-mlongcall} (gcc) - GNAT has incorporated WRS' - gcc modification that implements this option. - If a subprogram call is - compiled with the @code{-mlongcall} option, then the generated code - constructs an absolute address in a register and uses a branch - instruction with absolute addressing mode. - - Starting with release 3.15, the GNAT runtime libraries that are - distributed are compiled with the @code{-mlongcall} option. In many - cases the use of these libraries is sufficient to avoid the - relocation problem, since it is the runtime library that contains - calls to the VxWorks kernel that need to span the address space gap. - If you are using an earlier GNAT release or a manually-built runtime, - you should recompile the GNAT runtime library with @code{-mlongcall}; - you can use the - @file{Makefile.adalib} file from the @file{adalib} directory. - - Application code may need to be compiled with @code{-mlongcall} if there - are calls directly to the kernel, the application is very large, - or in some specialized linking/loading scenarios. - - You can compile individual files with @code{-mlongcall} by placing this - option on the @code{gcc} command line (for brevity we are omitting the - @code{powerpc-wrs-vxworks-} prefix on the commands shown in this - paragraph). - If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be - passed to all invocations of @code{gcc} that @code{gnatmake} directly performs. - Note that one other compilation is made by @code{gnatlink}, on the file created - by @code{gnatbind} for the elaboration package body - (see @ref{Binding Using gnatbind}). - Passing @code{-mlongcall} to @code{gnatlink}, either directly - on the @code{gnatlink} command line or by including @code{-mlongcall} in the - @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the - binder file with the @code{-mlongcall} option. - - To see the effect of @code{-mlongcall}, consider the following small example: - - @smallexample - procedure Proc is - procedure Imported_Proc; - pragma Import (Ada, Imported_Proc); - begin - Imported_Proc; - end; - @end smallexample - - @noindent - If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated: - - @smallexample - _ada_proc: - ... - bl imported_proc - ... - @end smallexample - - @noindent - In contrast, here is the result with the @code{-mlongcall} option: - - @smallexample - _ada_proc: - ... - addis 9,0,imported_proc@@ha - addi 0,9,imported_proc@@l - mtlr 0 - blrl - ... - @end smallexample - - - @node Support for Software Floating Point on PowerPC Processors - @section Support for Software Floating Point on PowerPC Processors - - @noindent - The PowerPC 860 processor does not have hardware floating-point support. - In order to build and run GNAT modules properly, you need to install and - invoke software-emulated floating-point support as follows: - - @itemize @bullet - @item - At installation time: - @itemize @bullet - @item - Create a file @file{ada_object_path} under the directory - @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1} - (by default @file{BASE}=@file{c:\gnatpro}) - containing the following line: - @smallexample - rts-soft-float\adalib - @end smallexample - - @item - Create a file @file{ada_source_path} under the directory - @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1} - (by default @file{BASE}=@file{c:\gnatpro}) - containing the following line: - @smallexample - rts-soft-float\adainclude - @end smallexample - @end itemize - - @item - When using the compiler, specify @option{-msoft-float} - as a compiler and a linker option, e.g.: - @smallexample - $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float - @end smallexample - @end itemize - - - @node Interrupt Handling for VxWorks - @section Interrupt Handling for VxWorks - - @noindent - GNAT offers a range of options for hardware interrupt handling. In rough - order of latency and lack of restrictions: - - @itemize @bullet - @item Directly vectored interrupt procedure handlers - @item Directly vectored interrupt procedures that signal a task using - a suspension object - @item Ada 95 protected procedure handlers for interrupts - @item Ada 83 style interrupt entry handlers for interrupts - @end itemize - - @noindent - In general, the range of possible solutions trades off latency versus - restrictions in the handler code. Restrictions in direct vectored - interrupt handlers are documented in the @cite{VxWorks Programmer's Guide}. - Protected procedure handlers have only the - restriction that no potentially blocking operations are performed within - the handler. Interrupt entries have no restrictions. We recommend the - use of the protected procedure mechanism as providing the best balance - of these considerations for most applications. - - All handler types must explicitly perform any required hardware cleanups, - such as issuing an end-of-interrupt if necessary. - - For VxWorks/AE, applications that handle interrupts must be loaded into - the kernel protection domain. - - @itemize @bullet - @item Direct Vectored Interrupt Routines - - @noindent - This approach provides the lowest interrupt latency, but has the most - restrictions on what VxWorks and Ada runtime calls can be made, as well - as on what Ada entities are accessible to the handler code. Such handlers - are most useful when there are stringent latency requirements, and very - little processing is to be performed in the handler. Access to the - necessary VxWorks routines for setting up such handlers is provided in - the package @code{Interfaces.VxWorks}. - - VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}. - Note in particular that floating point context is not automatically saved and - restored when interrupts are vectored to the handler. If the handler is - to execute floating point instructions, the statements involved must be - bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined - in @code{Interfaces.VxWorks}. - - In general, it is a good idea to save and restore the handler that was - installed prior to application startup. The routines @code{intVecGet} - and @code{intVecSet} are used for this purpose. The Ada handler code - is installed into the vector table using routine @code{intConnect}, - which generates wrapper code to save and restore registers. - - Example: - - @smallexample - with Interfaces.VxWorks; use Interfaces.VxWorks; - with System; - - package P is - - Count : Natural := 0; - pragma Atomic (Count); - - -- Interrupt level used by this example - Level : constant := 1; - - -- Be sure to use a reasonable interrupt number for the target - -- board! Refer to the BSP for details. - Interrupt : constant := 16#14#; - - procedure Handler (Parameter : System.Address); - - end P; - - package body P is - - procedure Handler (parameter : System.Address) is - S : Status; - begin - Count := Count + 1; - -- Acknowledge interrupt. Not necessary for all interrupts. - S := sysBusIntAck (intLevel => Level); - end Handler; - end P; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - - with P; use P; - procedure Useint is - task T; - - S : Status; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - -- Save old handler - Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt)); - begin - S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access); - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Put_Line ("value of count:" & P.Count'Img); - end loop; - - -- Restore previous handler - S := sysIntDisable (intLevel => Level); - intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler); - end Useint; - @end smallexample - - @item Direct Vectored Interrupt Routines - - @noindent - A variation on the direct vectored routine that allows for less restrictive - handler code is to separate the interrupt processing into two levels. - - The first level is the same as in the previous section. Here we perform - simple hardware actions and signal a task pending on a Suspension_Object - (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex - and time-consuming operations. The routine @code{Set_True} signals a task - whose body loops and pends on the suspension object using @code{Suspend_Until_True}. - The suspension object is declared in a scope global to both the handler and - the task. This approach can be thought of as a slightly higher-level - application of the @code{C} example using a binary semaphore given in the - VxWorks Programmer's Manual. In fact, the implementation of - @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks - binary semaphore. - - This approach has a latency between the direct vectored approach and the - protected procedure approach. There are no restrictions in the Ada task - code, while the handler code has the same restrictions as any other - direct interrupt handler. - - Example: - - @smallexample - with System; - package Sem_Handler is - - Count : Natural := 0; - pragma Atomic (Count); - - -- Interrupt level used by this example - Level : constant := 1; - Interrupt : constant := 16#14#; - - -- Interrupt handler providing "immediate" handling - procedure Handler (Param : System.Address); - - -- Task whose body provides "deferred" handling - task Receiver is - pragma Interrupt_Priority - (System.Interrupt_Priority'First + Level + 1); - end Receiver; - - end Sem_Handler; - - with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control; - with Interfaces.VxWorks; use Interfaces.VxWorks; - package body Sema_Handler is - - SO : Suspension_Object; - - task body Receiver is - begin - loop - -- Wait for notification from immediate handler - Suspend_Until_True (SO); - - -- Interrupt processing - Count := Count + 1; - end loop; - end Receiver; - - procedure Handler (Param : System.Address) is - S : STATUS; - begin - -- Hardware cleanup, if necessary - S := sysBusIntAck (Level); - - -- Signal the task - Set_True (SO); - end Handler; - - end Sem_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - with Sem_Handler; use Sem_Handler; - procedure Useint is - - S : STATUS; - - task T; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - -- Save old handler - Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt)); - begin - S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access); - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Put_Line ("value of Count:" & Sem_Handler.Count'Img); - end loop; - - -- Restore handler - S := sysIntDisable (intLevel => Level); - intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler); - abort Receiver; - end Useint; - @end smallexample - - @item Protected Procedure Handlers for Interrupts - - @noindent - This is the recommended default mechanism for interrupt handling. - It essentially wraps the hybrid handler / task mechanism in a higher-level - abstraction, and provides a good balance between latency and capability. - - Vectored interrupts are designated by their interrupt number, starting from - 0 and ranging to the number of entries in the interrupt vector table - 1. - - In the GNAT VxWorks implementation, the following priority mappings are used: - @itemize @bullet - @item Normal task priorities are in the range 0 .. 245. - @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager} - task. - @item Interrupt priority 247 is used for vectored interrupts - that do not correspond to those generated via an interrupt controller. - @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels - 0 .. 7. - @item Priority 256 is reserved to the VxWorks kernel. - @end itemize - - Except for reserved priorities, the above are recommendations for setting the - ceiling priority of a protected object that handles interrupts, or the - priority of a task with interrupt entries. It's a very good idea to follow - these recommendations for vectored interrupts that come in through the PIC - as it will determine the priority of execution of the code in the protected - procedure or interrupt entry. - - No vectored interrupt numbers are reserved in this implementation, because - dedicated interrupts are determined by the board support package. Obviously, - careful consideration of the hardware is necessary when handling interrupts. - The VxWorks BSP for the board is the definitive reference for interrupt - assignments. - - Example: - - @smallexample - package PO_Handler is - - -- Interrupt level used by this example - Level : constant := 1; - - Interrupt : constant := 16#14#; - - protected Protected_Handler is - procedure Handler; - pragma Attach_Handler (Handler, Interrupt); - - function Count return Natural; - - pragma Interrupt_Priority (248); - private - The_Count : Natural := 0; - end Protected_Handler; - - end PO_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - package body PO_Handler is - - protected body Protected_Handler is - - procedure Handler is - S : Status; - begin - -- Hardware cleanup if necessary - S := sysBusIntAck (Level); - - -- Interrupt processing - The_Count := The_Count + 1; - end Handler; - - function Count return Natural is - begin - return The_Count; - end Count; - end Protected_Handler; - - end PO_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - - with PO_Handler; use PO_Handler; - procedure Useint is - - task T; - - S : STATUS; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - begin - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Put_Line ("value of count:" & Protected_Handler.Count'Img); - end loop; - - S := sysIntDisable (intLevel => Level); - end Useint; - @end smallexample - - @noindent - This is obviously significantly higher-level and easier to write than the - previous examples. - - @item Ada 83 Style Interrupt Entries - - GNAT provides a full implementation of the Ada 83 interrupt entry mechanism - for vectored interrupts. However, due to latency issues, - we only recommend using these for backward compatibility. The comments in - the previous section regarding interrupt priorities and reserved interrupts - apply here. - - In order to associate an interrupt with an entry, GNAT provides the - standard Ada convenience routine @code{Ada.Interrupts.Reference}. It is used - as follows: - - @smallexample - Interrupt_Address : constant System.Address := - Ada.Interrupts.Reference (Int_Num); - - task Handler_Task is - pragma Interrupt_Priority (248); -- For instance - entry Handler; - for Handler'Address use Interrupt_Address; - end Handler_Task; - @end smallexample - - @noindent - Since there is no restriction within an interrupt entry on blocking operations, - be sure to perform any hardware interrupt controller related operations before - executing a call that could block within the entry's accept statements. It - is assumed that interrupt entries are always open alternatives when they - appear within a selective wait statement. The presence of a guard gives - undefined behavior. - - Example: - - @smallexample - with Ada.Interrupts; - with System; - package Task_Handler is - - -- Interrupt level used by this example - Level : constant := 1; - - Interrupt : constant := 16#14#; - - Interrupt_Address : constant System.Address := - Ada.Interrupts.Reference (Int_Num); - - task Handler_Task is - pragma Interrupt_Priority (248); -- For instance - entry Handler; - for Handler'Address use Interrupt_Address; - - entry Count (Value : out Natural); - end Handler_Task; - end Task_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - package body Task_Handler is - - task body Handler_Task is - The_Count : Natural := 0; - S : STATUS; - begin - loop - select - accept Handler do - -- Hardware cleanup if necessary - S := sysBusIntAck (Level); - - -- Interrupt processing - The_Count := The_Count + 1; - end Handler; - or - accept Count (Value : out Natural) do - Value := The_Count; - end Count; - end select; - end loop; - end Handler_Task; - - end Handler_Task; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - - with Handler_Task; use Handler_Task; - procedure Useint is - - task T; - - S : STATUS; - Current_Count : Natural := 0; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - begin - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Handler_Task.Count (Current_Count); - Put_Line ("value of count:" & Current_Count'Img); - end loop; - - S := sysIntDisable (intLevel => Level); - abort Handler_Task; - end Useint; - @end smallexample - @end itemize - - - @node Simulating Command Line Arguments for VxWorks - @section Simulating Command Line Arguments for VxWorks - - @noindent - The GNAT implementation of @code{Ada.Command_Line} relies on the standard C - symbols @code{argv} and @code{argc}. The model for invoking "programs" under - VxWorks does not provide these symbols. The typical method for invoking a - program under VxWorks is to call the @code{sp} function in order to spawn a - thread in which to execute a designated function (in GNAT, this is the implicit - main generated by gnatbind. @code{sp} provides the capability to push a variable - number of arguments onto the stack when the function is invoked. But this does - not work for the implicit Ada main, because it has no way of knowing how many - arguments might be required. This eliminates the possibility to use - @code{Ada.Command_Line}. - - One way to solve this problem is to define symbols in the VxWorks environment, - then import them into the Ada application. For example, we could define the - following package that imports two symbols, one an int and the other a string: - - @smallexample - with Interfaces.C.Strings; - use Interfaces.C.Strings; - package Args is - -- Define and import a variable for each argument - Int_Arg : Interfaces.C.Int; - String_Arg : Chars_Ptr; - private - pragma Import (C, Int_Arg, "intarg"); - pragma Import (C, String_Arg, "stringarg"); - end Args; - @end smallexample - - @noindent - An Ada unit could then use the two imported variables @code{Int_Arg} and - @code{String_Arg} as follows: - - @smallexample - with Args; use Args; - with Interfaces.C.Strings; - use Interfaces.C, Interfaces.C.Strings; - with Ada.Text_IO; use Ada.Text_IO; - procedure Argtest is - begin - Put_Line (Int'Image (Int_Arg)); - Put_Line (Value (String_Arg)); - end Argtest; - @end smallexample - - @noindent - When invoking the application from the shell, one will then set the values - to be imported, and spawn the application, as follows: - - @smallexample - -> intarg=10 - -> stringarg="Hello" - -> sp (argtest) - @end smallexample - - - @node Debugging Issues for VxWorks - @section Debugging Issues for VxWorks - - @noindent - The debugger can be launched directly from the Tornado environment or from @code{glide} - through its graphical interface: @code{gvd}. It can also be used - directly in text mode as shown below: - @noindent - The command to run @code{GDB} in text mode is - - @smallexample - $ @i{target}-gdb - @end smallexample - - @noindent - where @i{target} is the name of target of the cross GNAT - compiler. In contrast with native @code{gdb}, it is not useful to give the name of - the program to debug on the command line. Before starting a debugging - session, one needs to connect to the VxWorks-configured board and load - the relocatable object produced by @code{gnatlink}. This can be achieved - by the following commands: - - @smallexample - (vxgdb) target wtx myboard - (vxgdb) load program - @end smallexample - - @noindent - where @code{myboard} is the host name or IP number of the target board, and - @code{wtx} is the name of debugging protocol used to communicate - with the VxWorks board. Early versions of VxWorks, up tp 5.2, only - support the @code{} protocol whereas starting with VxWorks 5.3 - and Tornado, another protocol called @code{} was made available. The - choice of the protocol can be made when configuring the VxWorks - kernel itself. When available, the @code{} is greatly preferable - and actually the only supported protocol with GNAT. When the debugger - is launched directly from Tornado, the proper @code{target} command - is automatically generated by the environment. - - The GNAT debugger can be used for debugging multitasking programs in two - different modes and some minimal understanding of these modes is - necessary in order to use the debugger effectively. The two modes are: - - @itemize @bullet - @item Monotask mode: attach to, and debug, a single task. - This mode is equivalent to the capabilities offered by CrossWind. The - debugger interacts with a single task, while not affecting other tasks - (insofar as possible). This is the DEFAULT mode. - - @item Multitask mode: - The debugger has control over all Ada tasks in an application. It is - possible to gather information about all application tasks, and to - switch from one to another within a single debugging session. - @end itemize - - @noindent - It is not advised to switch between the two modes within a debugging - session. A third mode called System mode is also available and can be - used in place of the Multitask mode. Consult the Tornado documentation - for this. - - Among the criteria for selecting the appropriate mode is the effect of - task synchronization on the application's behavior. Debugging a - tasking application affects the timing of the application; minimizing - such effects may be critical in certain situations. The two modes have - different effects: monotask mode only affects the attached task: - others will run normally (if possible). Multitask mode stops all tasks - at each breakpoint and restarts them on single-step, next, finish or - continue; this may help avoid deadlocks in the presence of task - synchronization despite the inherent latency of stopping and - restarting the tasks. - - @subsection Using the debugger in monotask mode - - @noindent - There are two ways to begin your debugging session: - - @itemize @bullet - @item The program is already running on the board. - - @noindent - The sequence of commands to use this mode is: - @itemize @bullet - @item Launch GVD (possibly from the Tornado menu) - - @noindent - Verify that the debugger has access to the debug information of both - your program and the kernel. The Console window should have a message - "Looking for all loaded modules:" followed by the names of the modules - on the board and "ok". If you have some error messages here instead of - "ok", the debugging session may not work as expected. - - @item Attach to the desired task using - @smallexample - File --> Attach... - @end smallexample - @noindent - This task is stopped by the debugger. Other tasks continue to operate - normally (unless they are blocked by synchronization with the stopped - task). The source window should display the code on which the task has - been stopped, and if the stack display is enabled, it should reflect - the stack of the task. - @end itemize - - @item The program hasn't been loaded yet on the board - @itemize @bullet - @item Launch GVD (possibly from the Tornado menu) - @item Load your program to the board: - @smallexample - File --> Open Program... - @end smallexample - - @noindent - GVD should display: - @smallexample - Downloading your_program ...done. - Reading symbols from your_program...expanding to full symbols...done. - @end smallexample - - @item Set breakpoints in your program. - - @noindent - WARNING: they must be set in the main task (if your program runs - several tasks) - - @item Run your program using one of the three methods below: - @itemize @bullet - @item - Click on button or - - @item Menu - @smallexample - Program --> Run/Start - @end smallexample - - @item - Type in GVD's Console window - @smallexample - (gdb) run your_program - @end smallexample - @end itemize - @end itemize - - @item Whichever method you chose to start your debugging session, - you can use the following commands at this point: - @itemize @bullet - @item Browse sources and set breakpoints - @item Examine the call stack (Data --> call stack) - @item Go "up" and "down" in the call stack ("up" & "down" buttons) - @item Examine data - (Data --> Display local variables, or any of the other methods for viewing data in GVD) - @item Continue/finish - @end itemize - - Next/step/finish will only work if the top frame in the call stack has - debug information. This is almost never the case when first attaching - to the task since the task is usually stopped by the attach operation - in the GNAT runtime. You can verify which frames of the call stack - have debug information by: - @smallexample - Data --> call stack - (contextual menu inside the call stack window) - add "file location" - @end smallexample - - @noindent - If the current frame does not have a "file location", then there is no - debug information for the frame. We strongly recommended that you set - breakpoints in the source where debug information can be found and - "continue" until a breakpoint is reached before using - "next/step". Another convenient possibility is to use the "continue - until" capability available from the contextual menu of the Source - window. - - You can also examine the state of other tasks using - @smallexample - Data -> tasks - @end smallexample - - @noindent - but you can't "switch" to another task by clicking on the - elements of the task list. If you try to, you will get an error - message in GVD's console: - @smallexample - "Task switching is not allowed when multi-tasks mode is not active" - @end smallexample - - @noindent - Once you have completed your debugging session on the attached - task, you can detach from the task: - @smallexample - File --> detach - @end smallexample - - @noindent - The task resumes normal execution at this stage. WARNING: when you - detach from a task, be sure that you are in a frame where there is - debug information. Otherwise, the task won't resume properly. You can - then start another attach/detach cycle if you wish. - - Note that it is possible to launch several GVD sessions and - simultaneously attach each to a distinct task in monotask mode: - @smallexample - File --> New Debugger... (uncheck the box: Replace Current Debugger) - File --> Attach... (in the new window) - File --> detach - @end smallexample - @end itemize - - - @subsection Using the debugger in Multitask mode - - @noindent - The steps are as follows - - @itemize @bullet - @item - Launch GVD (possibly from the Tornado menu) - - @noindent - There are two possibilities: - @itemize @bullet - @item - If the program is already loaded on the target board, you need only verify - that debug information has been found by the debugger as described - above. - - @item - Otherwise, load the program on the board using - @smallexample - File --> Open program - @end smallexample - @end itemize - - @item Set breakpoints in the desired parts of the program - - @item Start the program - - @noindent - The simplest way to start the debugger in multitask mode is to use the - menu - @smallexample - Program --> Run/Start - @end smallexample - - @noindent - and check the box "enable vxWorks multi-tasks mode". - You can also use the following gdb commands in the console window - @smallexample - (gdb) set multi-tasks-mode on - (gdb) run your_program - @end smallexample - - @item Debug the stopped program - - @noindent - Once stopped at a breakpoint - (or if you pressed the "stop" button), you can use all the standard - commands listed for monotask mode + task switching (using Data --> - tasks). Using next/step under this mode is possible with the same - restrictions as for monotask mode, but is not recommended because all - tasks are restarted, leading to the possibility that a different task - hits a breakpoint before the stepping operation has completed. Such - an occurrence can result in a confusing state for both the user and - the debugger. So we strongly suggest the use of only breakpoints and - "continue" in this mode. - @end itemize - - A final reminder: whatever the mode, whether you are debugging or not, - the program has to be reloaded before each new execution, so that data - initialized by the loader is set correctly. For instance, if you wish - to restart the same execution of the same program, you can use the - following sequence of gdb commands in the console window: - @smallexample - (gdb) detach - (gdb) unload your_program(.exe) - (gdb) load your_program(.exe) - (gdb) run your_program - @end smallexample - - - @node Using GNAT from the Tornado 2 Project Facility - @section Using GNAT from the Tornado 2 Project Facility - @cindex Tornado II Project - - @menu - * The GNAT Toolchain as Used from the Tornado 2 Project Facility:: - * Building a Simple Application:: - * Mixing C and Ada Code in a Tornado 2 Project:: - * Compilation Switches:: - * Autoscale and Minimal Kernel Configuration:: - * Adapting BSPs to GNAT:: - * Using GNAT Project Files in a Tornado 2 Project:: - @end menu - - @noindent - This section describes how to add an Ada module in a Tornado project - using the Tornado 2 Project facility described in - @cite{Tornado User's Guide}, Chapter 4. - All recommendations apply for both 'Downloadable Modules' and 'Kernel' - project types. - - - @node The GNAT Toolchain as Used from the Tornado 2 Project Facility - @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility - - @noindent - Tornado 2 allows you to integrate third-party C toolchains. - (@cite{Tornado 2 API Programmer's Guide}, Chapter 7). - Thus the GNAT toolchain will be seen as a new C toolchain when used from - the Tornado 2 Project Facility. For each processor you can compile for, - you will find a gnat toolchain, e.g. PPC604gnat. These toolchains will - allow you to include Ada modules into your projects, and simply build them. - - The name of the so-called C compiler is @emph{cc_gnat_}, the name - of the 'linker' is @emph{ld_gnat_}, where is an architecture; e.g., - PPC. These scripts will call the correct executables during the compilation or - link processes, thus the C compiler, the C linker, or the GNAT toolchain, - depending on the context. - - - @node Building a Simple Application - @subsection Building a Simple Application - - @noindent - First, create a new project, using one of the gnat toolchains. - - To add an Ada source file to the current project, just click on - @code{Project -> Add/Include}, browse to the relevant file, and include it. - The Ada source file included should be the Ada entry point. Only - one Ada entry point is allowed in a project. Any other required Ada source - files will be automatically compiled and linked by the underlying tools. - - You can now compile the project, @code{Build->Rebuild all}. - A log of the compilation process can be found in the build directory, in - @file{gnatbuild.log}. It contains all the calls executed by the scripts, and - associated information. - - - @node Mixing C and Ada Code in a Tornado 2 Project - @subsection Mixing C and Ada Code in a Tornado 2 Project - - @noindent - You can mix C and Ada code in your projects. Your source files and the build - options should comply with the recommendations from the section - @cite{Interfacing to C}. - This means that you can have several or no C source files, and one or no Ada entry - point in your Tornado 2 Project. - - - @node Compilation Switches - @subsection Compilation Switches - @noindent - Once you have included all your source files, you may modify some compilation - and linking options. - To pass specific options to the GNAT toolchain, go to the Project's build - settings, on the @code{C/C++ Compiler} tab, and add your arguments in the - input window. - - You must comply with several rules to pass arguments to GNAT. - Arguments to be passed should be - - @itemize @bullet - - @item after any arguments passed to the C toolchain. - - @item prefixed depending on the tool that uses them, with the following syntax - - @itemize @bullet - @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake - @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind - @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink - @end itemize - @end itemize - - @noindent - You will find more information on the compilation process of Ada source files - in the section @cite{The GNAT Compilation Model}. - For a list of all available switches, refer to the sections describing - @code{gnatmake}, @code{gnatbind} and @code{gnatlink}. - - Here is an example that passes the option @code{-v} to the GNAT compiler : - @smallexample - -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT - -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604 - -cargs -v - @end smallexample - - @noindent - Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker, - and @code{-v} and @code{-g} to the compiler : - @smallexample - -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT - -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604 - -cargs -v -g -O2 -bargs -v -largs -v - @end smallexample - - @noindent - In both examples, the following arguments have been automatically added by the Project - Facility, and will be used by the C compiler. - @smallexample - -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT - -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604 - @end smallexample - - @noindent - Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input - boxes is used by the GNAT toolchain. It is required for the compilation - process. You should not remove it from any input box. - - - @node Autoscale and Minimal Kernel Configuration - @subsection Autoscale and Minimal Kernel Configuration - - @noindent - The Autoscale feature, present in the Project Facility can be used on your - VxWorks Kernel projects to determine the minimum set of components required - for your kernel to work. - (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.) - This feature is also available for projects involving Ada code. Just click on - @code{Project->Autoscale} to launch a check and determine the minimal kernel - configuration. - - - @node Adapting BSPs to GNAT - @subsection Adapting BSPs to GNAT - - @noindent - To use your Board Support Packages with the GNAT toolchain, you will have to adapt them, - either manually or using the @code{adaptbsp4gnat} script. - This procedure is described in the @cite{Tornado API Programmer's Guide}, - Chapter 7. - Here is a summary of this setup, depending on the context. - - @itemize @bullet - @item To do the adaptation manually: - - @itemize @bullet - - @item Copy your BSP directory contents into a new directory - - @item Go to this directory - - @item Edit the file @file{Makefile}, - - @itemize @bullet - @item Set tool to gnat, @code{TOOL=gnat} - - @item Reverse the order of the following lines - @itemize @bullet - @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)} - @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)} - @end itemize - - @end itemize - - @end itemize - - @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat} - script. Its syntax is @code{adaptbsp4gnat }. - - @noindent - This script follows the different steps described above to perform the - adaptation. - The name of the new bsp is given after the modification. By default, if - @file{} is the name of your BSP, @file{-gnat}, will be the name of - the BSP created. - @end itemize - - - @node Using GNAT Project Files in a Tornado 2 Project - @subsection Using GNAT Project Files in a Tornado 2 Project - - @noindent - You can use GNAT Project files to compile your Ada files. - To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}. - The path to the project file can be either absolute, or relative to the build - directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}). - Your project file should set the @code{Object_Dir} variable to a specific - value. - @smallexample - project Sample is - - Target := external ("TARGET_DIR"); - for Object_Dir use Target; - - end Sample; - @end smallexample - - - @node Frequently Asked Questions for VxWorks - @section Frequently Asked Questions for VxWorks - - @itemize @bullet - - @item - When I run my program twice on the board, it does not work, why? - - @noindent - Usually, Ada programs require elaboration and finalization, so the - compiler creates a wrapper procedure whose name is the same as the Ada - name of the main subprogram, which takes care of calling the elaboration - and finalization routines before and after your program. But the static - part of the elaboration is taken care of while loading the program - itself and thus if you launch it twice this part of the elaboration will - not be performed. This affects the proper elaboration of the - GNAT runtime and thus it is mandatory to reload your program before - relaunching it. - - @item - Can I load a collection of subprograms rather than a standalone program? - - @noindent - It is possible to write Ada programs with multiple entry points which - can be called from the VxWorks shell; you just need to consider your - main program as the VxWorks shell itself and generate an Ada subsystem - callable from outside @xref{Binding with Non-Ada Main Programs}. If you - use this method, you need to call @code{adainit} manually before calling - any Ada entry point. - - @item - When I use the @code{break exception} command, I get the message - @code{"exception" is not a function}, why? - - You are not in the proper language mode. Issue the command: - @smallexample - (vxgdb) set language ada - @end smallexample - - @item - When I load a large application from the VxWorks shell using the "ld" - command, the load hangs and never finishes. How can I load large - executables? - - This is a classic VxWorks problem when using the default "rsh" communication - method. Using NFS instead should work. Use the @code{nfsShowMount} command to - verify that your program is in a NFS mounted directory. - - @item - When I load a large application from the debugger using the wtx target - connection, the load never finishes, why? - - Make sure that the memory cache size parameter of the target server is - large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.) - See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2. - - @item - When I spawn my program under the VxWorks shell, interactive input does - not work, why? - - Only programs directly launched from the shell can have interactive - input. For a program spawned with the @code{sp} or @code{taskSpawn} - command, you need to have file redirection for input: - @smallexample - -> # here you can have interactive input - -> main - -> # here you cannot - -> sp main - -> # neither here - -> taskSpawn("ess",100,0,8000000,main) - -> # but you can input from a file: - -> taskSpawn("Bae",100,0,8000000,main) < input_file - @end smallexample - @end itemize - - - @node LynxOS Topics - @chapter LynxOS Topics - @noindent - This chapter describes topics that are specific to the GNAT for LynxOS - cross configurations. - - @menu - * Getting Started with GNAT on LynxOS:: - * Kernel Configuration for LynxOS:: - * Patch Level Issues for LynxOS:: - * Debugging Issues for LynxOS:: - * An Example Debugging Session for LynxOS:: - @end menu - - @node Getting Started with GNAT on LynxOS - @section Getting Started with GNAT on LynxOS - - @noindent - This section is a starting point for using GNAT to develop and - execute Ada 95 programs for LynuxWorks' LynxOS target environment from a - Unix host environment. - We assume that you know how to use GNAT in a native environment - and how to start a telnet or other login session to connect to your LynxOS board. - - To compile code for a LynxOS system running on a PowerPC - board, the basic compiler command is - @command{powerpc-xcoff-lynxos-gcc}. - - With GNAT, the easiest way to build the basic @code{Hello World} program is - with @code{gnatmake}. For the LynxOS PowerPC target this would look - like: - - @smallexample - $ powerpc-xcoff-lynxos-gnatmake hello - @i{powerpc-xcoff-lynxos-gcc -c hello.adb - powerpc-xcoff-lynxos-gnatbind -x hello.ali - powerpc-xcoff-lynxos-gnatlink hello.ali} - @end smallexample - - @noindent - (The first line is the command entered by the user -- the subseqent three - are the programs run by @code{gnatmake}.) - - This creates the executable @command{hello}" which you then need to load on the - board (using ftp or an NFS directory for example) to run it. - - - @node Kernel Configuration for LynxOS - @section Kernel Configuration for LynxOS - - @noindent - The appropriate configuration for your LynxOS kernel depends - on the target system and the requirements of your application. GNAT itself - adds no additional demands; however in some situations it may be appropriate - to increase the conservative - resource assumptions made by the default configuration. - - Kernel parameters limiting the maximum number of file descriptors, - kernel and user threads, synchronization objects, etc., may be set in the - file @file{uparam.h}. You may also wish to modify the file - @file{/etc/starttab}, which places limits on data, stack, and core file - size. See the documentation provided by LynuxWorks for more information. - - - @node Patch Level Issues for LynxOS - @section Patch Level Issues for LynxOS - - @noindent - The GNAT runtime requires that your system run at patch level 040 or - later. Please see the file @file{PatchCompatibility.txt} from the - distribution for more information. - - - @node Debugging Issues for LynxOS - @section Debugging Issues for LynxOS - - @noindent - GNAT's debugger is based on the same GNU gdb technology as the debugger - provided by LynxOS, though with a great number of extensions and - enhancements to support the Ada language and GNAT. The LynxOS - documentation is relevant to understanding how to get the debugger - started if you run into difficulties. - - To demonstrate a debugging session, we will use a slightly more complex - program called @file{demo1.adb}, which can be found in the @file{examples} - directory of the GNAT distribution. This program is compiled with - debugging information as follows: - - @smallexample - $ powerpc-xcoff-lynxos-gnatmake -g demo1 - powerpc-xcoff-lynxos-gcc -c -g demo1.adb - powerpc-xcoff-lynxos-gcc -c -g gen_list.adb - powerpc-xcoff-lynxos-gcc -c -g instr.adb - powerpc-xcoff-lynxos-gnatbind -x demo1.ali - powerpc-xcoff-lynxos-gnatlink -g demo1.ali - @end smallexample - - @noindent - Once the executable is created, copy it to your working directory on the - board. In this directory, you will have to launch the gdb server and - choose a free port number on your TCP/IP socket. Presuming the Internet - hostname of the board is @file{myboard} and the port chosen is 2345, - issue the following command: - - @smallexample - myboard> gdbserver myboard:2345 demo1 - @end smallexample - - @noindent - Then return to your host environment. - - The graphical debugger interface, @command{gvd}, supports both native - and cross environments at the same time. @command{gvd} can be launched from - @command{Glide} (see @file{README.Glide} for more information on customizing - @command{Glide} for LynxOS) or it can be launched from the command line as - follows: - - @smallexample - $ gvd --debugger powerpc-xcoff-lynxos-gdb - @end smallexample - - @noindent - Then to attach to the target, enter in @command{gvd}'s command line window: - - @smallexample - (gdb) target remote myboard:2345 - @end smallexample - - @noindent - For more information see the GVD documentation. - - The comments below concern debugging directly from the command line but - they also apply to @command{gvd}, though in most cases an equivalent - graphical command is also available. - - To run the cross debugger from the command line without the visual - interface use the command @code{powerpc-xcoff-lynxos-gdb}. - - You will see something like: - - @smallexample - GNU gdb 4.17.gnat.3.14a1 - Copyright 1998 Free Software Foundation, Inc. - GDB is free software, covered by the GNU General Public License, and you are - welcome to change it and/or distribute copies of it under certain conditions. - Type "show copying" to see the conditions. - There is absolutely no warranty for GDB. Type "show warranty" for details. - This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc - off-lynxos". - (gdb) - @end smallexample - - @noindent - Where @command{(gdb)} is the debugger's prompt. The first thing to do at the - prompt from within @command{gdb} is to load the symbol table from the - executable: - - @smallexample - (gdb) file demo1 - Reading symbols from demo1...done. - (gdb) - @end smallexample - - @noindent - You then have to attach to the server running on the board. Issue the command: - - @smallexample - (gdb) target remote myboard:2345 - @end smallexample - - @noindent - After the server has been started and attached from the host, the program is - running on the target but has halted execution at the very beginning. - The following commands set a breakpoint and continue execution: - - @smallexample - (gdb) break demo1.adb:37 - Breakpoint 1 at 0x100064d0: file demo1.adb, line 37. - (gdb) cont - Continuing. - - Breakpoint 1, demo1 () at demo1.adb:37 - 37 Set_Name (Fuel, "Fuel"); - (gdb) - @end smallexample - - @noindent - Here the execution has stopped at the breakpoint set above. Now - you can use the standard @code{gdb} commands to examine the stack and - program variables. - - Note that once execution has completed, the server on the board must be - restarted before a new debugging session may begin. - - @node An Example Debugging Session for LynxOS - @section An Example Debugging Session for LynxOS - - @noindent - Carrying on a little further with the debugging session, the following - example illustrates some of the usual debugging commands for moving - around and seeing where you are: - - @smallexample - (gdb) next - 38 Set_Name (Water, "Water"); - (gdb) bt - #0 demo1 () at demo1.adb:38 - #1 0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at - b~demo1.adb:118 - #2 0x10017538 in runmainthread () - #3 0x10001048 in __start () - (gdb) up - #1 0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at - b~demo1.adb:118 - 118 Ada_Main_Program; - (gdb) down - #0 demo1 () at demo1.adb:38 - 38 Set_Name (Water, "Water"); - (gdb) - @end smallexample - - @noindent - To examine and modify variables (of a tagged type here): - - @smallexample - (gdb) print speed - $1 = (name => "Speed ", value => -286331154) - (gdb) ptype speed - type = new instr.instrument with record - value: instr.speed; - end record - (gdb) speed.value := 3 - $2 = 3 - (gdb) print speed - $3 = (name => "Speed ", value => 3) - (gdb) info local - speed = (name => "Speed ", value => 3) - fuel = (name => "Fuel ", value => -286331154) - oil = (name => ' ' , value => -286331154, size => 20, - fill => 42 '*', empty => 46 '.') - water = (name => ' ' , value => -286331154, size => 20, - fill => 42 '*', empty => 46 '.') - time = (name => ' ' , seconds => 0, minutes => 0, hours => - 0) - chrono = (name => ' ' , seconds => 0, minutes => 0, - hours => 0) - db = (access demo1.dash_board.internal) 0x0 - (gdb) - @end smallexample - - @noindent - And finally letting the program it run to completion: - - @smallexample - (gdb) c - Continuing. - - Program exited normally. - (gdb) - @end smallexample - @end ifset - - - @node Performance Considerations - @chapter Performance Considerations - @cindex Performance - - @noindent - The GNAT system provides a number of options that allow a trade-off - between - - @itemize @bullet - @item - performance of the generated code - - @item - speed of compilation - - @item - minimization of dependences and recompilation - - @item - the degree of run-time checking. - @end itemize - - @noindent - The defaults (if no options are selected) aim at improving the speed - of compilation and minimizing dependences, at the expense of performance - of the generated code: - - @itemize @bullet - @item - no optimization - - @item - no inlining of subprogram calls - - @item - all run-time checks enabled except overflow and elaboration checks - @end itemize - - @noindent - These options are suitable for most program development purposes. This - chapter describes how you can modify these choices, and also provides - some guidelines on debugging optimized code. - - @menu - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - @ifset vms - * Coverage Analysis:: - @end ifset - @end menu - - @node Controlling Run-Time Checks - @section Controlling Run-Time Checks - - @noindent - By default, GNAT generates all run-time checks, except arithmetic overflow - checking for integer operations and checks for access before elaboration on - subprogram calls. The latter are not required in default mode, because all - necessary checking is done at compile time. - @cindex @option{-gnatp} (@code{gcc}) - @cindex @option{-gnato} (@code{gcc}) - Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to - be modified. @xref{Run-Time Checks}. - - Our experience is that the default is suitable for most development - purposes. - - We treat integer overflow specially because these - are quite expensive and in our experience are not as important as other - run-time checks in the development process. Note that division by zero - is not considered an overflow check, and divide by zero checks are - generated where required by default. - - Elaboration checks are off by default, and also not needed by default, since - GNAT uses a static elaboration analysis approach that avoids the need for - run-time checking. This manual contains a full chapter discussing the issue - of elaboration checks, and if the default is not satisfactory for your use, - you should read this chapter. - - For validity checks, the minimal checks required by the Ada Reference - Manual (for case statements and assignments to array elements) are on - by default. These can be suppressed by use of the @option{-gnatVn} switch. - Note that in Ada 83, there were no validity checks, so if the Ada 83 mode - is acceptable (or when comparing GNAT performance with an Ada 83 compiler), - it may be reasonable to routinely use @option{-gnatVn}. Validity checks - are also suppressed entirely if @option{-gnatp} is used. - - @cindex Overflow checks - @cindex Checks, overflow - @findex Suppress - @findex Unsuppress - @cindex pragma Suppress - @cindex pragma Unsuppress - Note that the setting of the switches controls the default setting of - the checks. They may be modified using either @code{pragma Suppress} (to - remove checks) or @code{pragma Unsuppress} (to add back suppressed - checks) in the program source. - - @node Optimization Levels - @section Optimization Levels - @cindex @code{^-O^/OPTIMIZE^} (@code{gcc}) - - @noindent - The default is optimization off. This results in the fastest compile - times, but GNAT makes absolutely no attempt to optimize, and the - generated programs are considerably larger and slower than when - optimization is enabled. You can use the - @ifclear vms - @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3, - @end ifclear - @ifset vms - @code{/OPTIMIZE} - @end ifset - on the @code{gcc} command line to control the optimization level: - - @table @code - @item -O0 - no optimization (the default) - - @item -O1 - medium level optimization - - @item -O2 - full optimization - - @item -O3 - full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - @end table - - Higher optimization levels perform more global transformations on the - program and apply more expensive analysis algorithms in order to generate - faster and more compact code. The price in compilation time, and the - resulting improvement in execution time, - both depend on the particular application and the hardware environment. - You should experiment to find the best level for your application. - - Note: Unlike some other compilation systems, @code{gcc} has - been tested extensively at all optimization levels. There are some bugs - which appear only with optimization turned on, but there have also been - bugs which show up only in @emph{unoptimized} code. Selecting a lower - level of optimization does not improve the reliability of the code - generator, which in practice is highly reliable at all optimization - levels. - - Note regarding the use of @code{-O3}: The use of this optimization level - is generally discouraged with GNAT, since it often results in larger - executables which run more slowly. See further discussion of this point - in @pxref{Inlining of Subprograms}. - - @node Debugging Optimized Code - @section Debugging Optimized Code - - @noindent - Since the compiler generates debugging tables for a compilation unit before - it performs optimizations, the optimizing transformations may invalidate some - of the debugging data. You therefore need to anticipate certain - anomalous situations that may arise while debugging optimized code. This - section describes the most common cases. - - @enumerate - @item - @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC - bouncing back and forth in the code. This may result from any of the following - optimizations: - - @itemize @bullet - @item - @i{Common subexpression elimination:} using a single instance of code for a - quantity that the source computes several times. As a result you - may not be able to stop on what looks like a statement. - - @item - @i{Invariant code motion:} moving an expression that does not change within a - loop, to the beginning of the loop. - - @item - @i{Instruction scheduling:} moving instructions so as to - overlap loads and stores (typically) with other code, or in - general to move computations of values closer to their uses. Often - this causes you to pass an assignment statement without the assignment - happening and then later bounce back to the statement when the - value is actually needed. Placing a breakpoint on a line of code - and then stepping over it may, therefore, not always cause all the - expected side-effects. - @end itemize - - @item - @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two - identical pieces of code are merged and the program counter suddenly - jumps to a statement that is not supposed to be executed, simply because - it (and the code following) translates to the same thing as the code - that @emph{was} supposed to be executed. This effect is typically seen in - sequences that end in a jump, such as a @code{goto}, a @code{return}, or - a @code{break} in a C @code{switch} statement. - - @item - @i{The "roving variable":} The symptom is an unexpected value in a variable. - There are various reasons for this effect: - - @itemize @bullet - @item - In a subprogram prologue, a parameter may not yet have been moved to its - "home". - - @item - A variable may be dead, and its register re-used. This is - probably the most common cause. - - @item - As mentioned above, the assignment of a value to a variable may - have been moved. - - @item - A variable may be eliminated entirely by value propagation or - other means. In this case, GCC may incorrectly generate debugging - information for the variable - @end itemize - - @noindent - In general, when an unexpected value appears for a local variable or parameter - you should first ascertain if that value was actually computed by - your program, as opposed to being incorrectly reported by the debugger. - Record fields or - array elements in an object designated by an access value - are generally less of a problem, once you have ascertained that the access value - is sensible. - Typically, this means checking variables in the preceding code and in the - calling subprogram to verify that the value observed is explainable from other - values (one must apply the procedure recursively to those - other values); or re-running the code and stopping a little earlier - (perhaps before the call) and stepping to better see how the variable obtained - the value in question; or continuing to step @emph{from} the point of the - strange value to see if code motion had simply moved the variable's - assignments later. - @end enumerate - - @node Inlining of Subprograms - @section Inlining of Subprograms - - @noindent - A call to a subprogram in the current unit is inlined if all the - following conditions are met: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else that @code{gcc} - cannot support in inlined subprograms. - - @item - The call occurs after the definition of the body of the subprogram. - - @item - @cindex pragma Inline - @findex Inline - Either @code{pragma Inline} applies to the subprogram or it is - small and automatic inlining (optimization level @code{-O3}) is - specified. - @end itemize - - @noindent - Calls to subprograms in @code{with}'ed units are normally not inlined. - To achieve this level of inlining, the following conditions must all be - true: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else @code{gcc} cannot - support in inlined subprograms. - - @item - The call appears in a body (not in a package spec). - - @item - There is a @code{pragma Inline} for the subprogram. - - @item - @cindex @option{-gnatn} (@code{gcc}) - The @code{^-gnatn^/INLINE^} switch - is used in the @code{gcc} command line - @end itemize - - Note that specifying the @option{-gnatn} switch causes additional - compilation dependencies. Consider the following: - - @smallexample - @group - @cartouche - @b{package} R @b{is} - @b{procedure} Q; - @b{pragma} Inline (Q); - @b{end} R; - @b{package body} R @b{is} - ... - @b{end} R; - - @b{with} R; - @b{procedure} Main @b{is} - @b{begin} - ... - R.Q; - @b{end} Main; - @end cartouche - @end group - @end smallexample - - @noindent - With the default behavior (no @option{-gnatn} switch specified), the - compilation of the @code{Main} procedure depends only on its own source, - @file{main.adb}, and the spec of the package in file @file{r.ads}. This - means that editing the body of @code{R} does not require recompiling - @code{Main}. - - On the other hand, the call @code{R.Q} is not inlined under these - circumstances. If the @option{-gnatn} switch is present when @code{Main} - is compiled, the call will be inlined if the body of @code{Q} is small - enough, but now @code{Main} depends on the body of @code{R} in - @file{r.adb} as well as on the spec. This means that if this body is edited, - the main program must be recompiled. Note that this extra dependency - occurs whether or not the call is in fact inlined by @code{gcc}. - - The use of front end inlining with @option{-gnatN} generates similar - additional dependencies. - - @cindex @code{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc}) - Note: The @code{^-fno-inline^/INLINE=SUPPRESS^} switch - can be used to prevent - all inlining. This switch overrides all other conditions and ensures - that no inlining occurs. The extra dependences resulting from - @option{-gnatn} will still be active, even if - this switch is used to suppress the resulting inlining actions. - - Note regarding the use of @code{-O3}: There is no difference in inlining - behavior between @code{-O2} and @code{-O3} for subprograms with an explicit - pragma @code{Inline} assuming the use of @option{-gnatn} - or @option{-gnatN} (the switches that activate inlining). If you have used - pragma @code{Inline} in appropriate cases, then it is usually much better - to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which - in this case only has the effect of inlining subprograms you did not - think should be inlined. We often find that the use of @code{-O3} slows - down code by performing excessive inlining, leading to increased instruction - cache pressure from the increased code size. So the bottom line here is - that you should not automatically assume that @code{-O3} is better than - @code{-O2}, and indeed you should use @code{-O3} only if tests show that - it actually improves performance. - - @ifset vms - @node Coverage Analysis - @section Coverage Analysis - - @noindent - GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows - the user to determine the distribution of execution time across a program, - @pxref{Profiling} for details of usage. - @end ifset - - @include fdl.texi - @c GNU Free Documentation License - - @node Index,,GNU Free Documentation License, Top - @unnumbered Index - - @printindex cp - - @contents - - @bye --- 0 ---- diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_ug_unx.texi gcc-3.4.1/gcc/ada/gnat_ug_unx.texi *** gcc-3.4.0/gcc/ada/gnat_ug_unx.texi 2004-03-20 15:33:52.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_ug_unx.texi 1970-01-01 00:00:00.000000000 +0000 *************** *** 1,18802 **** - \input texinfo @c -*-texinfo-*- - @c %**start of header - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c o - @c GNAT DOCUMENTATION o - @c o - @c G N A T _ U G o - @c o - @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. o - @c o - @c GNAT is free software; you can redistribute it and/or modify it under o - @c terms of the GNU General Public License as published by the Free Soft- o - @c ware Foundation; either version 2, or (at your option) any later ver- o - @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o - @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o - @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o - @c for more details. You should have received a copy of the GNU General o - @c Public License distributed with GNAT; see file COPYING. If not, write o - @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o - @c MA 02111-1307, USA. o - @c o - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c - @c GNAT_UG Style Guide - @c - @c 1. Always put a @noindent on the line before the first paragraph - @c after any of these commands: - @c - @c @chapter - @c @section - @c @subsection - @c @subsubsection - @c @subsubsubsection - @c - @c @end smallexample - @c @end itemize - @c @end enumerate - @c - @c 2. DO NOT use @example. Use @smallexample instead. - @c - @c 3. Each @chapter, @section, @subsection, @subsubsection, etc. - @c command must be preceded by two empty lines - @c - @c 4. The @item command must be on a line of its own if it is in an - @c @itemize or @enumerate command. - @c - @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" - @c or "ali". - @c - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - - - @setfilename gnat_ug_unx.info - @settitle GNAT User's Guide for Unix Platforms - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_unx). GNAT User's Guide for Unix Platforms. - @end direntry - - - @include gcc-common.texi - - @setchapternewpage odd - @syncodeindex fn cp - @c %**end of header - - @copying - Copyright @copyright{} 1995-2003, Free Software Foundation - - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with the Invariant Sections being ``GNU Free Documentation License'', with the - Front-Cover Texts being - ``GNAT User's Guide for Unix Platforms'', - and with no Back-Cover Texts. - A copy of the license is included in the section entitled ``GNU - Free Documentation License''. - @end copying - - @titlepage - - - - @title GNAT User's Guide - @center @titlefont{for Unix Platforms} - - - @subtitle GNAT, The GNU Ada 95 Compiler - @subtitle GNAT Version for GCC @value{version-GCC} - - @author Ada Core Technologies, Inc. - - @page - @vskip 0pt plus 1filll - - @insertcopying - - @end titlepage - - @ifnottex - @node Top, About This Guide, (dir), (dir) - @top GNAT User's Guide - - - - GNAT User's Guide for Unix Platforms - - - GNAT, The GNU Ada 95 Compiler - - GNAT Version for GCC @value{version-GCC} - - Ada Core Technologies, Inc. - - @insertcopying - - @menu - * About This Guide:: - * Getting Started with GNAT:: - * The GNAT Compilation Model:: - * Compiling Using gcc:: - * Binding Using gnatbind:: - * Linking Using gnatlink:: - * The GNAT Make Program gnatmake:: - * Renaming Files Using gnatchop:: - * Configuration Pragmas:: - * Handling Arbitrary File Naming Conventions Using gnatname:: - * GNAT Project Manager:: - * Elaboration Order Handling in GNAT:: - * The Cross-Referencing Tools gnatxref and gnatfind:: - * File Name Krunching Using gnatkr:: - * Preprocessing Using gnatprep:: - * The GNAT Library Browser gnatls:: - * GNAT and Libraries:: - * Using the GNU make Utility:: - * Finding Memory Problems with gnatmem:: - * Finding Memory Problems with GNAT Debug Pool:: - * Creating Sample Bodies Using gnatstub:: - * Reducing the Size of Ada Executables with gnatelim:: - * Other Utility Programs:: - * Running and Debugging Ada Programs:: - * Inline Assembler:: - * Performance Considerations:: - * GNU Free Documentation License:: - * Index:: - - --- The Detailed Node Listing --- - - About This Guide - - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - - - Getting Started with GNAT - - * Running GNAT:: - * Running a Simple Ada Program:: - * Running a Program with Multiple Units:: - * Using the gnatmake Utility:: - - The GNAT Compilation Model - - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - - Foreign Language Representation - - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - - Compiling Ada Programs With gcc - - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - - Switches for gcc - - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - - Binding Ada Programs With gnatbind - - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - - Linking Using gnatlink - - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - - The GNAT Make Program gnatmake - - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - - Renaming Files Using gnatchop - - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - - Configuration Pragmas - - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - - Handling Arbitrary File Naming Conventions Using gnatname - - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - - GNAT Project Manager - - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - - Elaboration Order Handling in GNAT - - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - - The Cross-Referencing Tools gnatxref and gnatfind - - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - - File Name Krunching Using gnatkr - - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - - Preprocessing Using gnatprep - - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - - - The GNAT Library Browser gnatls - - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - - - GNAT and Libraries - - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - - Using the GNU make Utility - - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - - Finding Memory Problems with gnatmem - - * Running gnatmem (GDB Mode):: - * Running gnatmem (GMEM Mode):: - * Switches for gnatmem:: - * Examples of gnatmem Usage:: - * GDB and GMEM Modes:: - * Implementation Note:: - - - Finding Memory Problems with GNAT Debug Pool - - Creating Sample Bodies Using gnatstub - - * Running gnatstub:: - * Switches for gnatstub:: - - Reducing the Size of Ada Executables with gnatelim - - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - - Other Utility Programs - - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - - - Running and Debugging Ada Programs - - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - - Inline Assembler - - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - - - - Performance Considerations - - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - - * Index:: - @end menu - @end ifnottex - - @node About This Guide - @unnumbered About This Guide - - @noindent - This guide describes the use of GNAT, a compiler and software development - toolset for the full Ada 95 programming language. - It describes the features of the compiler and tools, and details - how to use them to build Ada 95 applications. - - @menu - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - @end menu - - @node What This Guide Contains - @unnumberedsec What This Guide Contains - - @noindent - This guide contains the following chapters: - @itemize @bullet - @item - @ref{Getting Started with GNAT}, describes how to get started compiling - and running Ada programs with the GNAT Ada programming environment. - @item - @ref{The GNAT Compilation Model}, describes the compilation model used - by GNAT. - @item - @ref{Compiling Using gcc}, describes how to compile - Ada programs with @code{gcc}, the Ada compiler. - @item - @ref{Binding Using gnatbind}, describes how to - perform binding of Ada programs with @code{gnatbind}, the GNAT binding - utility. - @item - @ref{Linking Using gnatlink}, - describes @code{gnatlink}, a - program that provides for linking using the GNAT run-time library to - construct a program. @code{gnatlink} can also incorporate foreign language - object units into the executable. - @item - @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a - utility that automatically determines the set of sources - needed by an Ada compilation unit, and executes the necessary compilations - binding and link. - @item - @ref{Renaming Files Using gnatchop}, describes - @code{gnatchop}, a utility that allows you to preprocess a file that - contains Ada source code, and split it into one or more new files, one - for each compilation unit. - @item - @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT. - @item - @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override - the default GNAT file naming conventions, either for an individual unit or globally. - @item - @ref{GNAT Project Manager}, describes how to use project files to organize large projects. - @item - @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with - elaboration order issues. - @item - @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses - @code{gnatxref} and @code{gnatfind}, two tools that provide an easy - way to navigate through sources. - @item - @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr} - file name krunching utility, used to handle shortened - file names on operating systems with a limit on the length of names. - @item - @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a - preprocessor utility that allows a single source file to be used to - generate multiple or parameterized source files, by means of macro - substitution. - @item - @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a - utility that displays information about compiled units, including dependences - on the corresponding sources files, and consistency of compilations. - @item - @ref{GNAT and Libraries}, describes the process of creating and using - Libraries with GNAT. It also describes how to recompile the GNAT run-time - library. - - @item - @ref{Using the GNU make Utility}, describes some techniques for using - the GNAT toolset in Makefiles. - - @item - @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a - utility that monitors dynamic allocation and deallocation activity in a - program, and displays information about incorrect deallocations and sources - of possible memory leaks. - @item - @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to - use the GNAT-specific Debug Pool in order to detect as early as possible - the use of incorrect memory references. - - @item - @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub}, - a utility that generates empty but compilable bodies for library units. - - @item - @ref{Reducing the Size of Ada Executables with gnatelim}, describes - @code{gnatelim}, a tool which detects unused subprograms and helps - the compiler to create a smaller executable for the program. - - @item - @ref{Other Utility Programs}, discusses several other GNAT utilities, - including @code{gnatpsta}. - - @item - @ref{Running and Debugging Ada Programs}, describes how to run and debug - Ada programs. - - @item - @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program. - - - @item - @ref{Performance Considerations}, reviews the trade offs between using - defaults or options in program development. - @end itemize - - @node What You Should Know before Reading This Guide - @unnumberedsec What You Should Know before Reading This Guide - - @cindex Ada 95 Language Reference Manual - @noindent - This user's guide assumes that you are familiar with Ada 95 language, as - described in the International Standard ANSI/ISO/IEC-8652:1995, Jan - 1995. - - @node Related Information - @unnumberedsec Related Information - - @noindent - For further information about related tools, refer to the following - documents: - - @itemize @bullet - @item - @cite{GNAT Reference Manual}, which contains all reference - material for the GNAT implementation of Ada 95. - - @item - @cite{Ada 95 Language Reference Manual}, which contains all reference - material for the Ada 95 programming language. - - @item - @cite{Debugging with GDB} - contains all details on the use of the GNU source-level debugger. - - @item - @cite{GNU Emacs Manual} - contains full information on the extensible editor and programming - environment Emacs. - - @end itemize - - @node Conventions - @unnumberedsec Conventions - @cindex Conventions - @cindex Typographical conventions - - @noindent - Following are examples of the typographical and graphic conventions used - in this guide: - - @itemize @bullet - @item - @code{Functions}, @code{utility program names}, @code{standard names}, - and @code{classes}. - - @item - @samp{Option flags} - - @item - @file{File Names}, @file{button names}, and @file{field names}. - - @item - @var{Variables}. - - @item - @emph{Emphasis}. - - @item - [optional information or parameters] - - @item - Examples are described by text - @smallexample - and then shown this way. - @end smallexample - @end itemize - - @noindent - Commands that are entered by the user are preceded in this manual by the - characters @w{"@code{$ }"} (dollar sign followed by space). If your system - uses this sequence as a prompt, then the commands will appear exactly as - you see them in the manual. If your system uses some other prompt, then - the command will appear with the @code{$} replaced by whatever prompt - character you are using. - - - @node Getting Started with GNAT - @chapter Getting Started with GNAT - - @noindent - This chapter describes some simple ways of using GNAT to build - executable Ada programs. - - @menu - * Running GNAT:: - * Running a Simple Ada Program:: - - * Running a Program with Multiple Units:: - - * Using the gnatmake Utility:: - * Introduction to Glide and GVD:: - @end menu - - @node Running GNAT - @section Running GNAT - - @noindent - Three steps are needed to create an executable file from an Ada source - file: - - @enumerate - @item - The source file(s) must be compiled. - @item - The file(s) must be bound using the GNAT binder. - @item - All appropriate object files must be linked to produce an executable. - @end enumerate - - @noindent - All three steps are most commonly handled by using the @code{gnatmake} - utility program that, given the name of the main program, automatically - performs the necessary compilation, binding and linking steps. - - @node Running a Simple Ada Program - @section Running a Simple Ada Program - - @noindent - Any text editor may be used to prepare an Ada program. If @code{Glide} is - used, the optional Ada mode may be helpful in laying out the program. The - program text is a normal text file. We will suppose in our initial - example that you have used your editor to prepare the following - standard format text file: - - @smallexample - @group - @cartouche - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - @end cartouche - @end group - @end smallexample - - @noindent - This file should be named @file{hello.adb}. - With the normal default file naming conventions, GNAT requires - that each file - contain a single compilation unit whose file name is the - unit name, - with periods replaced by hyphens; the - extension is @file{ads} for a - spec and @file{adb} for a body. - You can override this default file naming convention by use of the - special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). - Alternatively, if you want to rename your files according to this default - convention, which is probably more convenient if you will be using GNAT - for all your compilations, then the @code{gnatchop} utility - can be used to generate correctly-named source files - (@pxref{Renaming Files Using gnatchop}). - - You can compile the program using the following command (@code{$} is used - as the command prompt in the examples in this document): - - @smallexample - $ gcc -c hello.adb - @end smallexample - - - @noindent - @code{gcc} is the command used to run the compiler. This compiler is - capable of compiling programs in several languages, including Ada 95 and - C. It assumes that you have given it an Ada program if the file extension is - either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile - the specified file. - - The @option{-c} switch is required. It tells @command{gcc} to only do a - compilation. (For C programs, @command{gcc} can also do linking, but this - capability is not used directly for Ada programs, so the @option{-c} - switch must always be present.) - - This compile command generates a file - @file{hello.o}, which is the object - file corresponding to your Ada program. It also generates an "Ada Library Information" file - @file{hello.ali}, - which contains additional information used to check - that an Ada program is consistent. - To build an executable file, - use @code{gnatbind} to bind the program - and @code{gnatlink} to link it. The - argument to both @code{gnatbind} and @code{gnatlink} is the name of the - @file{ali} file, but the default extension of @file{.ali} can - be omitted. This means that in the most common case, the argument - is simply the name of the main program: - - @smallexample - $ gnatbind hello - $ gnatlink hello - @end smallexample - - - @noindent - A simpler method of carrying out these steps is to use - @command{gnatmake}, - a master program that invokes all the required - compilation, binding and linking tools in the correct order. In particular, - @command{gnatmake} automatically recompiles any sources that have been modified - since they were last compiled, or sources that depend - on such modified sources, so that "version skew" is avoided. - @cindex Version skew (avoided by @command{gnatmake}) - - @smallexample - $ gnatmake hello.adb - @end smallexample - - - @noindent - The result is an executable program called @file{hello}, which can be - run by entering: - - @c The following should be removed (BMB 2001-01-23) - @c @smallexample - @c $ ./hello - @c @end smallexample - - @smallexample - $ hello - @end smallexample - - @noindent - assuming that the current directory is on the search path for executable programs. - - @noindent - and, if all has gone well, you will see - - @smallexample - Hello WORLD! - @end smallexample - - @noindent - appear in response to this command. - - - - - @node Running a Program with Multiple Units - @section Running a Program with Multiple Units - - @noindent - Consider a slightly more complicated example that has three files: a - main program, and the spec and body of a package: - - @smallexample - @cartouche - @group - @b{package} Greetings @b{is} - @b{procedure} Hello; - @b{procedure} Goodbye; - @b{end} Greetings; - - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{package} @b{body} Greetings @b{is} - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - - @b{procedure} Goodbye @b{is} - @b{begin} - Put_Line ("Goodbye WORLD!"); - @b{end} Goodbye; - @b{end} Greetings; - @end group - - @group - @b{with} Greetings; - @b{procedure} Gmain @b{is} - @b{begin} - Greetings.Hello; - Greetings.Goodbye; - @b{end} Gmain; - @end group - @end cartouche - @end smallexample - - @noindent - Following the one-unit-per-file rule, place this program in the - following three separate files: - - @table @file - @item greetings.ads - spec of package @code{Greetings} - - @item greetings.adb - body of package @code{Greetings} - - @item gmain.adb - body of main program - @end table - - @noindent - To build an executable version of - this program, we could use four separate steps to compile, bind, and link - the program, as follows: - - @smallexample - $ gcc -c gmain.adb - $ gcc -c greetings.adb - $ gnatbind gmain - $ gnatlink gmain - @end smallexample - - - @noindent - Note that there is no required order of compilation when using GNAT. - In particular it is perfectly fine to compile the main program first. - Also, it is not necessary to compile package specs in the case where - there is an accompanying body; you only need to compile the body. If you want - to submit these files to the compiler for semantic checking and not code generation, - then use the - @option{-gnatc} switch: - - @smallexample - $ gcc -c greetings.ads -gnatc - @end smallexample - - - @noindent - Although the compilation can be done in separate steps as in the - above example, in practice it is almost always more convenient - to use the @code{gnatmake} tool. All you need to know in this case - is the name of the main program's source file. The effect of the above four - commands can be achieved with a single one: - - @smallexample - $ gnatmake gmain.adb - @end smallexample - - - @noindent - In the next section we discuss the advantages of using @code{gnatmake} in - more detail. - - @node Using the gnatmake Utility - @section Using the @command{gnatmake} Utility - - @noindent - If you work on a program by compiling single components at a time using - @code{gcc}, you typically keep track of the units you modify. In order to - build a consistent system, you compile not only these units, but also any - units that depend on the units you have modified. - For example, in the preceding case, - if you edit @file{gmain.adb}, you only need to recompile that file. But if - you edit @file{greetings.ads}, you must recompile both - @file{greetings.adb} and @file{gmain.adb}, because both files contain - units that depend on @file{greetings.ads}. - - @code{gnatbind} will warn you if you forget one of these compilation - steps, so that it is impossible to generate an inconsistent program as a - result of forgetting to do a compilation. Nevertheless it is tedious and - error-prone to keep track of dependencies among units. - One approach to handle the dependency-bookkeeping is to use a - makefile. However, makefiles present maintenance problems of their own: - if the dependencies change as you change the program, you must make - sure that the makefile is kept up-to-date manually, which is also an - error-prone process. - - The @code{gnatmake} utility takes care of these details automatically. - Invoke it using either one of the following forms: - - @smallexample - $ gnatmake gmain.adb - $ gnatmake gmain - @end smallexample - - - @noindent - The argument is the name of the file containing the main program; - you may omit the extension. @code{gnatmake} - examines the environment, automatically recompiles any files that need - recompiling, and binds and links the resulting set of object files, - generating the executable file, @file{gmain}. - In a large program, it - can be extremely helpful to use @code{gnatmake}, because working out by hand - what needs to be recompiled can be difficult. - - Note that @code{gnatmake} - takes into account all the Ada 95 rules that - establish dependencies among units. These include dependencies that result - from inlining subprogram bodies, and from - generic instantiation. Unlike some other - Ada make tools, @code{gnatmake} does not rely on the dependencies that were - found by the compiler on a previous compilation, which may possibly - be wrong when sources change. @code{gnatmake} determines the exact set of - dependencies from scratch each time it is run. - - - @node Introduction to Glide and GVD - @section Introduction to Glide and GVD - @cindex Glide - @cindex GVD - @noindent - Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs. This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger. Additional information may be found in the on-line help for these tools. - - @menu - * Building a New Program with Glide:: - * Simple Debugging with GVD:: - * Other Glide Features:: - @end menu - - @node Building a New Program with Glide - @subsection Building a New Program with Glide - @noindent - The simplest way to invoke Glide is to enter @command{glide} at the command prompt. It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running: - - @smallexample - $ glide& - @end smallexample - - @noindent - Glide will start up with an initial screen displaying the top-level menu items as well as some other information. The menu selections are as follows - @itemize @bullet - @item @code{Buffers} - @item @code{Files} - @item @code{Tools} - @item @code{Edit} - @item @code{Search} - @item @code{Mule} - @item @code{Glide} - @item @code{Help} - @end itemize - - @noindent - For this introductory example, you will need to create a new Ada source file. First, select the @code{Files} menu. This will pop open a menu with around a dozen or so items. To create a file, select the @code{Open file...} choice. Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name. Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name. For this example enter @file{hello.adb} as the name of the file. - - A new buffer will now appear, occupying the entire Glide window, with the file name at the top. The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item. Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file. - - You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines. First, type the following text: - @smallexample - with Ada.Text_IO; use Ada.Text_IO; - procedure Hello is - begin - @end smallexample - - @noindent - Observe that Glide uses different colors to distinguish reserved words from identifiers. Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations. When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left. But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed. - - The main part of the program will be a @code{for} loop. Instead of entering the text explicitly, however, use a statement template. Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives. Choose @code{for loop}. You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed. You should see the beginning of a @code{for} loop appear in the source program window. You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case). Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction). Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax. - - Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop: - @smallexample - Put_Line("Hello, World" & Integer'Image(I)) - @end smallexample - - @noindent - Finally, type @code{end Hello;} as the last line in the program. Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection. You will see a message at the bottom of the buffer confirming that the file has been saved. - - You are now ready to attempt to build the program. Select the @code{Ada} item from the top menu bar. Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable. Thus select @code{Ada build}. This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools. Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window. The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected. - - Correct the error: type in a semicolon to terminate the statement. Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file. This time the build will succeed; the tool output window shows you the options that are supplied by default. The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched. - - To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window: - - @smallexample - Hello, world 1 - Hello, world 2 - Hello, world 3 - Hello, world 4 - Hello, world 5 - @end smallexample - - @node Simple Debugging with GVD - @subsection Simple Debugging with GVD - - @noindent - This section describes how to set breakpoints, examine/modify variables, and step through execution. - - In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}. If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect. You can then launch GVD, e.g. on the @code{hello} program, by issuing the command: - - @smallexample - $ gvd hello - @end smallexample - - @noindent - If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build. Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}. - - GVD comes up in a multi-part window. One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected. - - To the left of the source file pane, you will notice green dots adjacent to some lines. These are lines for which object code exists and where breakpoints can thus be set. You set/reset a breakpoint by clicking the green dot. When a breakpoint is set, the dot is replaced by an @code{X} in a red circle. Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot. - - For this example, set a breakpoint at the statement where @code{Put_Line} is invoked. - - Start program execution by selecting the @code{Run} button on the top menu bar. (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.) Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message. - - You can examine the values of variables in several ways. Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas. - - Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger. Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item. Enter @code{2} as the new value, and press @command{OK}. The box for @code{Ind} shows the update. - - Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}. - - Remove the breakpoint, and resume execution by selecting the @code{Cont} button. You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination. - - - @node Other Glide Features - @subsection Other Glide Features - - @noindent - You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu. These are @emph{shortcut keys} that you can use instead of selecting menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}. - - To abort a Glide command, type @key{Ctrl-g}. - - If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line: - - @smallexample - $ glide hello.adb& - @end smallexample - - @noindent - While you are using Glide, a number of @emph{buffers} exist. You create some explicitly; e.g., when you open/create a file. Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build. If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry. - - If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}. - - If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps: - @itemize @bullet - @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents) - @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu - @end itemize - - @noindent - To exit from Glide, choose @code{Files} @result{} @code{Exit}. - - @node The GNAT Compilation Model - @chapter The GNAT Compilation Model - @cindex GNAT compilation model - @cindex Compilation model - - @menu - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - @end menu - - @noindent - This chapter describes the compilation model used by GNAT. Although - similar to that used by other languages, such as C and C++, this model - is substantially different from the traditional Ada compilation models, - which are based on a library. The model is initially described without - reference to the library-based model. If you have not previously used an - Ada compiler, you need only read the first part of this chapter. The - last section describes and discusses the differences between the GNAT - model and the traditional Ada compiler models. If you have used other - Ada compilers, this section will help you to understand those - differences, and the advantages of the GNAT model. - - @node Source Representation - @section Source Representation - @cindex Latin-1 - - @noindent - Ada source programs are represented in standard text files, using - Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar - 7-bit ASCII set, plus additional characters used for - representing foreign languages (@pxref{Foreign Language Representation} - for support of non-USA character sets). The format effector characters - are represented using their standard ASCII encodings, as follows: - - @table @code - @item VT - @findex VT - Vertical tab, @code{16#0B#} - - @item HT - @findex HT - Horizontal tab, @code{16#09#} - - @item CR - @findex CR - Carriage return, @code{16#0D#} - - @item LF - @findex LF - Line feed, @code{16#0A#} - - @item FF - @findex FF - Form feed, @code{16#0C#} - @end table - - @noindent - Source files are in standard text file format. In addition, GNAT will - recognize a wide variety of stream formats, in which the end of physical - physical lines is marked by any of the following sequences: - @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful - in accommodating files that are imported from other operating systems. - - @cindex End of source file - @cindex Source file, end - @findex SUB - The end of a source file is normally represented by the physical end of - file. However, the control character @code{16#1A#} (@code{SUB}) is also - recognized as signalling the end of the source file. Again, this is - provided for compatibility with other operating systems where this - code is used to represent the end of file. - - Each file contains a single Ada compilation unit, including any pragmas - associated with the unit. For example, this means you must place a - package declaration (a package @dfn{spec}) and the corresponding body in - separate files. An Ada @dfn{compilation} (which is a sequence of - compilation units) is represented using a sequence of files. Similarly, - you will place each subunit or child unit in a separate file. - - @node Foreign Language Representation - @section Foreign Language Representation - - @noindent - GNAT supports the standard character sets defined in Ada 95 as well as - several other non-standard character sets for use in localized versions - of the compiler (@pxref{Character Set Control}). - @menu - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - @end menu - - @node Latin-1 - @subsection Latin-1 - @cindex Latin-1 - - @noindent - The basic character set is Latin-1. This character set is defined by ISO - standard 8859, part 1. The lower half (character codes @code{16#00#} - ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is - used to represent additional characters. These include extended letters - used by European languages, such as French accents, the vowels with umlauts - used in German, and the extra letter A-ring used in Swedish. - - @findex Ada.Characters.Latin_1 - For a complete list of Latin-1 codes and their encodings, see the source - file of library unit @code{Ada.Characters.Latin_1} in file - @file{a-chlat1.ads}. - You may use any of these extended characters freely in character or - string literals. In addition, the extended characters that represent - letters can be used in identifiers. - - @node Other 8-Bit Codes - @subsection Other 8-Bit Codes - - @noindent - GNAT also supports several other 8-bit coding schemes: - - @table @asis - @cindex Latin-2 - @item Latin-2 - Latin-2 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-3 - @cindex Latin-3 - Latin-3 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-4 - @cindex Latin-4 - Latin-4 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-5 - @cindex Latin-5 - @cindex Cyrillic - Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase - equivalence. - - @item IBM PC (code page 437) - @cindex code page 437 - This code page is the normal default for PCs in the U.S. It corresponds - to the original IBM PC character set. This set has some, but not all, of - the extended Latin-1 letters, but these letters do not have the same - encoding as Latin-1. In this mode, these letters are allowed in - identifiers with uppercase and lowercase equivalence. - - @item IBM PC (code page 850) - @cindex code page 850 - This code page is a modification of 437 extended to include all the - Latin-1 letters, but still not with the usual Latin-1 encoding. In this - mode, all these letters are allowed in identifiers with uppercase and - lowercase equivalence. - - @item Full Upper 8-bit - Any character in the range 80-FF allowed in identifiers, and all are - considered distinct. In other words, there are no uppercase and lowercase - equivalences in this range. This is useful in conjunction with - certain encoding schemes used for some foreign character sets (e.g. - the typical method of representing Chinese characters on the PC). - - @item No Upper-Half - No upper-half characters in the range 80-FF are allowed in identifiers. - This gives Ada 83 compatibility for identifier names. - @end table - - @noindent - For precise data on the encodings permitted, and the uppercase and lowercase - equivalences that are recognized, see the file @file{csets.adb} in - the GNAT compiler sources. You will need to obtain a full source release - of GNAT to obtain this file. - - @node Wide Character Encodings - @subsection Wide Character Encodings - - @noindent - GNAT allows wide character codes to appear in character and string - literals, and also optionally in identifiers, by means of the following - possible encoding schemes: - - @table @asis - - @item Hex Coding - In this encoding, a wide character is represented by the following five - character sequence: - - @smallexample - ESC a b c d - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ESC A345 is used to represent the wide character with code - @code{16#A345#}. - This scheme is compatible with use of the full Wide_Character set. - - @item Upper-Half Coding - @cindex Upper-Half Coding - The wide character with encoding @code{16#abcd#} where the upper bit is on (in - other words, "a" is in the range 8-F) is represented as two bytes, - @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control - character, but is not required to be in the upper half. This method can - be also used for shift-JIS or EUC, where the internal coding matches the - external coding. - - @item Shift JIS Coding - @cindex Shift JIS Coding - A wide character is represented by a two-character sequence, - @code{16#ab#} and - @code{16#cd#}, with the restrictions described for upper-half encoding as - described above. The internal character code is the corresponding JIS - character according to the standard algorithm for Shift-JIS - conversion. Only characters defined in the JIS code set table can be - used with this encoding method. - - @item EUC Coding - @cindex EUC Coding - A wide character is represented by a two-character sequence - @code{16#ab#} and - @code{16#cd#}, with both characters being in the upper half. The internal - character code is the corresponding JIS character according to the EUC - encoding algorithm. Only characters defined in the JIS code set table - can be used with this encoding method. - - @item UTF-8 Coding - A wide character is represented using - UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO - 10646-1/Am.2. Depending on the character value, the representation - is a one, two, or three byte sequence: - @smallexample - @iftex - @leftskip=.7cm - @end iftex - 16#0000#-16#007f#: 2#0xxxxxxx# - 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# - 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# - - @end smallexample - - @noindent - where the xxx bits correspond to the left-padded bits of the - 16-bit character value. Note that all lower half ASCII characters - are represented as ASCII bytes and all upper half characters and - other wide characters are represented as sequences of upper-half - (The full UTF-8 scheme allows for encoding 31-bit characters as - 6-byte sequences, but in this implementation, all UTF-8 sequences - of four or more bytes length will be treated as illegal). - @item Brackets Coding - In this encoding, a wide character is represented by the following eight - character sequence: - - @smallexample - [ " a b c d " ] - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ["A345"] is used to represent the wide character with code - @code{16#A345#}. It is also possible (though not required) to use the - Brackets coding for upper half characters. For example, the code - @code{16#A3#} can be represented as @code{["A3"]}. - - This scheme is compatible with use of the full Wide_Character set, - and is also the method used for wide character encoding in the standard - ACVC (Ada Compiler Validation Capability) test suite distributions. - - @end table - - @noindent - Note: Some of these coding schemes do not permit the full use of the - Ada 95 character set. For example, neither Shift JIS, nor EUC allow the - use of the upper half of the Latin-1 set. - - @node File Naming Rules - @section File Naming Rules - - @noindent - The default file name is determined by the name of the unit that the - file contains. The name is formed by taking the full expanded name of - the unit and replacing the separating dots with hyphens and using - lowercase for all letters. - - An exception arises if the file name generated by the above rules starts - with one of the characters - a,g,i, or s, - and the second character is a - minus. In this case, the character tilde is used in place - of the minus. The reason for this special rule is to avoid clashes with - the standard names for child units of the packages System, Ada, - Interfaces, and GNAT, which use the prefixes - s- a- i- and g- - respectively. - - The file extension is @file{.ads} for a spec and - @file{.adb} for a body. The following list shows some - examples of these rules. - - @table @file - @item main.ads - Main (spec) - @item main.adb - Main (body) - @item arith_functions.ads - Arith_Functions (package spec) - @item arith_functions.adb - Arith_Functions (package body) - @item func-spec.ads - Func.Spec (child package spec) - @item func-spec.adb - Func.Spec (child package body) - @item main-sub.adb - Sub (subunit of Main) - @item a~bad.adb - A.Bad (child package body) - @end table - - @noindent - Following these rules can result in excessively long - file names if corresponding - unit names are long (for example, if child units or subunits are - heavily nested). An option is available to shorten such long file names - (called file name "krunching"). This may be particularly useful when - programs being developed with GNAT are to be used on operating systems - with limited file name lengths. @xref{Using gnatkr}. - - Of course, no file shortening algorithm can guarantee uniqueness over - all possible unit names; if file name krunching is used, it is your - responsibility to ensure no name clashes occur. Alternatively you - can specify the exact file names that you want used, as described - in the next section. Finally, if your Ada programs are migrating from a - compiler with a different naming convention, you can use the gnatchop - utility to produce source files that follow the GNAT naming conventions. - (For details @pxref{Renaming Files Using gnatchop}.) - - @node Using Other File Names - @section Using Other File Names - @cindex File names - - @noindent - In the previous section, we have described the default rules used by - GNAT to determine the file name in which a given unit resides. It is - often convenient to follow these default rules, and if you follow them, - the compiler knows without being explicitly told where to find all - the files it needs. - - However, in some cases, particularly when a program is imported from - another Ada compiler environment, it may be more convenient for the - programmer to specify which file names contain which units. GNAT allows - arbitrary file names to be used by means of the Source_File_Name pragma. - The form of this pragma is as shown in the following examples: - @cindex Source_File_Name pragma - - @smallexample - @group - @cartouche - @b{pragma} Source_File_Name (My_Utilities.Stacks, - Spec_File_Name => "myutilst_a.ada"); - @b{pragma} Source_File_name (My_Utilities.Stacks, - Body_File_Name => "myutilst.ada"); - @end cartouche - @end group - @end smallexample - - @noindent - As shown in this example, the first argument for the pragma is the unit - name (in this example a child unit). The second argument has the form - of a named association. The identifier - indicates whether the file name is for a spec or a body; - the file name itself is given by a string literal. - - The source file name pragma is a configuration pragma, which means that - normally it will be placed in the @file{gnat.adc} - file used to hold configuration - pragmas that apply to a complete compilation environment. - For more details on how the @file{gnat.adc} file is created and used - @pxref{Handling of Configuration Pragmas} - @cindex @file{gnat.adc} - - GNAT allows completely arbitrary file names to be specified using the - source file name pragma. However, if the file name specified has an - extension other than @file{.ads} or @file{.adb} it is necessary to use a special - syntax when compiling the file. The name in this case must be preceded - by the special sequence @code{-x} followed by a space and the name of the - language, here @code{ada}, as in: - - @smallexample - $ gcc -c -x ada peculiar_file_name.sim - @end smallexample - - @noindent - @code{gnatmake} handles non-standard file names in the usual manner (the - non-standard file name for the main program is simply used as the - argument to gnatmake). Note that if the extension is also non-standard, - then it must be included in the gnatmake command, it may not be omitted. - - @node Alternative File Naming Schemes - @section Alternative File Naming Schemes - @cindex File naming schemes, alternative - @cindex File names - - In the previous section, we described the use of the @code{Source_File_Name} - pragma to allow arbitrary names to be assigned to individual source files. - However, this approach requires one pragma for each file, and especially in - large systems can result in very long @file{gnat.adc} files, and also create - a maintenance problem. - - GNAT also provides a facility for specifying systematic file naming schemes - other than the standard default naming scheme previously described. An - alternative scheme for naming is specified by the use of - @code{Source_File_Name} pragmas having the following format: - @cindex Source_File_Name pragma - - @smallexample - pragma Source_File_Name ( - Spec_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Body_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Subunit_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - FILE_NAME_PATTERN ::= STRING_LITERAL - CASING_SPEC ::= Lowercase | Uppercase | Mixedcase - - @end smallexample - - @noindent - The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. - It contains a single asterisk character, and the unit name is substituted - systematically for this asterisk. The optional parameter - @code{Casing} indicates - whether the unit name is to be all upper-case letters, all lower-case letters, - or mixed-case. If no - @code{Casing} parameter is used, then the default is all - lower-case. - - The optional @code{Dot_Replacement} string is used to replace any periods - that occur in subunit or child unit names. If no @code{Dot_Replacement} - argument is used then separating dots appear unchanged in the resulting - file name. - Although the above syntax indicates that the - @code{Casing} argument must appear - before the @code{Dot_Replacement} argument, but it - is also permissible to write these arguments in the opposite order. - - As indicated, it is possible to specify different naming schemes for - bodies, specs, and subunits. Quite often the rule for subunits is the - same as the rule for bodies, in which case, there is no need to give - a separate @code{Subunit_File_Name} rule, and in this case the - @code{Body_File_name} rule is used for subunits as well. - - The separate rule for subunits can also be used to implement the rather - unusual case of a compilation environment (e.g. a single directory) which - contains a subunit and a child unit with the same unit name. Although - both units cannot appear in the same partition, the Ada Reference Manual - allows (but does not require) the possibility of the two units coexisting - in the same environment. - - The file name translation works in the following steps: - - @itemize @bullet - - @item - If there is a specific @code{Source_File_Name} pragma for the given unit, - then this is always used, and any general pattern rules are ignored. - - @item - If there is a pattern type @code{Source_File_Name} pragma that applies to - the unit, then the resulting file name will be used if the file exists. If - more than one pattern matches, the latest one will be tried first, and the - first attempt resulting in a reference to a file that exists will be used. - - @item - If no pattern type @code{Source_File_Name} pragma that applies to the unit - for which the corresponding file exists, then the standard GNAT default - naming rules are used. - - @end itemize - - @noindent - As an example of the use of this mechanism, consider a commonly used scheme - in which file names are all lower case, with separating periods copied - unchanged to the resulting file name, and specs end with ".1.ada", and - bodies end with ".2.ada". GNAT will follow this scheme if the following - two pragmas appear: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.1.ada"); - pragma Source_File_Name - (Body_File_Name => "*.2.ada"); - @end smallexample - - @noindent - The default GNAT scheme is actually implemented by providing the following - default pragmas internally: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.ads", Dot_Replacement => "-"); - pragma Source_File_Name - (Body_File_Name => "*.adb", Dot_Replacement => "-"); - @end smallexample - - @noindent - Our final example implements a scheme typically used with one of the - Ada 83 compilers, where the separator character for subunits was "__" - (two underscores), specs were identified by adding @file{_.ADA}, bodies - by adding @file{.ADA}, and subunits by - adding @file{.SEP}. All file names were - upper case. Child units were not present of course since this was an - Ada 83 compiler, but it seems reasonable to extend this scheme to use - the same double underscore separator for child units. - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*_.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Body_File_Name => "*.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Subunit_File_Name => "*.SEP", - Dot_Replacement => "__", - Casing = Uppercase); - @end smallexample - - @node Generating Object Files - @section Generating Object Files - - @noindent - An Ada program consists of a set of source files, and the first step in - compiling the program is to generate the corresponding object files. - These are generated by compiling a subset of these source files. - The files you need to compile are the following: - - @itemize @bullet - @item - If a package spec has no body, compile the package spec to produce the - object file for the package. - - @item - If a package has both a spec and a body, compile the body to produce the - object file for the package. The source file for the package spec need - not be compiled in this case because there is only one object file, which - contains the code for both the spec and body of the package. - - @item - For a subprogram, compile the subprogram body to produce the object file - for the subprogram. The spec, if one is present, is as usual in a - separate file, and need not be compiled. - - @item - @cindex Subunits - In the case of subunits, only compile the parent unit. A single object - file is generated for the entire subunit tree, which includes all the - subunits. - - @item - Compile child units independently of their parent units - (though, of course, the spec of all the ancestor unit must be present in order - to compile a child unit). - - @item - @cindex Generics - Compile generic units in the same manner as any other units. The object - files in this case are small dummy files that contain at most the - flag used for elaboration checking. This is because GNAT always handles generic - instantiation by means of macro expansion. However, it is still necessary to - compile generic units, for dependency checking and elaboration purposes. - @end itemize - - @noindent - The preceding rules describe the set of files that must be compiled to - generate the object files for a program. Each object file has the same - name as the corresponding source file, except that the extension is - @file{.o} as usual. - - You may wish to compile other files for the purpose of checking their - syntactic and semantic correctness. For example, in the case where a - package has a separate spec and body, you would not normally compile the - spec. However, it is convenient in practice to compile the spec to make - sure it is error-free before compiling clients of this spec, because such - compilations will fail if there is an error in the spec. - - GNAT provides an option for compiling such files purely for the - purposes of checking correctness; such compilations are not required as - part of the process of building a program. To compile a file in this - checking mode, use the @option{-gnatc} switch. - - @node Source Dependencies - @section Source Dependencies - - @noindent - A given object file clearly depends on the source file which is compiled - to produce it. Here we are using @dfn{depends} in the sense of a typical - @code{make} utility; in other words, an object file depends on a source - file if changes to the source file require the object file to be - recompiled. - In addition to this basic dependency, a given object may depend on - additional source files as follows: - - @itemize @bullet - @item - If a file being compiled @code{with}'s a unit @var{X}, the object file - depends on the file containing the spec of unit @var{X}. This includes - files that are @code{with}'ed implicitly either because they are parents - of @code{with}'ed child units or they are run-time units required by the - language constructs used in a particular unit. - - @item - If a file being compiled instantiates a library level generic unit, the - object file depends on both the spec and body files for this generic - unit. - - @item - If a file being compiled instantiates a generic unit defined within a - package, the object file depends on the body file for the package as - well as the spec file. - - @item - @findex Inline - @cindex @option{-gnatn} switch - If a file being compiled contains a call to a subprogram for which - pragma @code{Inline} applies and inlining is activated with the - @option{-gnatn} switch, the object file depends on the file containing the - body of this subprogram as well as on the file containing the spec. Note - that for inlining to actually occur as a result of the use of this switch, - it is necessary to compile in optimizing mode. - - @cindex @option{-gnatN} switch - The use of @option{-gnatN} activates a more extensive inlining optimization - that is performed by the front end of the compiler. This inlining does - not require that the code generation be optimized. Like @option{-gnatn}, - the use of this switch generates additional dependencies. - - @item - If an object file O depends on the proper body of a subunit through inlining - or instantiation, it depends on the parent unit of the subunit. This means that - any modification of the parent unit or one of its subunits affects the - compilation of O. - - @item - The object file for a parent unit depends on all its subunit body files. - - @item - The previous two rules meant that for purposes of computing dependencies and - recompilation, a body and all its subunits are treated as an indivisible whole. - - @noindent - These rules are applied transitively: if unit @code{A} @code{with}'s - unit @code{B}, whose elaboration calls an inlined procedure in package - @code{C}, the object file for unit @code{A} will depend on the body of - @code{C}, in file @file{c.adb}. - - The set of dependent files described by these rules includes all the - files on which the unit is semantically dependent, as described in the - Ada 95 Language Reference Manual. However, it is a superset of what the - ARM describes, because it includes generic, inline, and subunit dependencies. - - An object file must be recreated by recompiling the corresponding source - file if any of the source files on which it depends are modified. For - example, if the @code{make} utility is used to control compilation, - the rule for an Ada object file must mention all the source files on - which the object file depends, according to the above definition. - The determination of the necessary - recompilations is done automatically when one uses @code{gnatmake}. - @end itemize - - @node The Ada Library Information Files - @section The Ada Library Information Files - @cindex Ada Library Information files - @cindex @file{ali} files - - @noindent - Each compilation actually generates two output files. The first of these - is the normal object file that has a @file{.o} extension. The second is a - text file containing full dependency information. It has the same - name as the source file, but an @file{.ali} extension. - This file is known as the Ada Library Information (@file{ali}) file. - The following information is contained in the @file{ali} file. - - @itemize @bullet - @item - Version information (indicates which version of GNAT was used to compile - the unit(s) in question) - - @item - Main program information (including priority and time slice settings, - as well as the wide character encoding used during compilation). - - @item - List of arguments used in the @code{gcc} command for the compilation - - @item - Attributes of the unit, including configuration pragmas used, an indication - of whether the compilation was successful, exception model used etc. - - @item - A list of relevant restrictions applying to the unit (used for consistency) - checking. - - @item - Categorization information (e.g. use of pragma @code{Pure}). - - @item - Information on all @code{with}'ed units, including presence of - @code{Elaborate} or @code{Elaborate_All} pragmas. - - @item - Information from any @code{Linker_Options} pragmas used in the unit - - @item - Information on the use of @code{Body_Version} or @code{Version} - attributes in the unit. - - @item - Dependency information. This is a list of files, together with - time stamp and checksum information. These are files on which - the unit depends in the sense that recompilation is required - if any of these units are modified. - - @item - Cross-reference data. Contains information on all entities referenced - in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to - provide cross-reference information. - - @end itemize - - @noindent - For a full detailed description of the format of the @file{ali} file, - see the source of the body of unit @code{Lib.Writ}, contained in file - @file{lib-writ.adb} in the GNAT compiler sources. - - @node Binding an Ada Program - @section Binding an Ada Program - - @noindent - When using languages such as C and C++, once the source files have been - compiled the only remaining step in building an executable program - is linking the object modules together. This means that it is possible to - link an inconsistent version of a program, in which two units have - included different versions of the same header. - - The rules of Ada do not permit such an inconsistent program to be built. - For example, if two clients have different versions of the same package, - it is illegal to build a program containing these two clients. - These rules are enforced by the GNAT binder, which also determines an - elaboration order consistent with the Ada rules. - - The GNAT binder is run after all the object files for a program have - been created. It is given the name of the main program unit, and from - this it determines the set of units required by the program, by reading the - corresponding ALI files. It generates error messages if the program is - inconsistent or if no valid order of elaboration exists. - - If no errors are detected, the binder produces a main program, in Ada by - default, that contains calls to the elaboration procedures of those - compilation unit that require them, followed by - a call to the main program. This Ada program is compiled to generate the - object file for the main program. The name of - the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec - @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the - main program unit. - - Finally, the linker is used to build the resulting executable program, - using the object from the main program from the bind step as well as the - object files for the Ada units of the program. - - @node Mixed Language Programming - @section Mixed Language Programming - @cindex Mixed Language Programming - - @menu - * Interfacing to C:: - * Calling Conventions:: - @end menu - - @node Interfacing to C - @subsection Interfacing to C - @noindent - There are two ways to - build a program that contains some Ada files and some other language - files depending on whether the main program is in Ada or not. - If the main program is in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake -c my_main.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind my_main.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. For instance: - @smallexample - gnatlink my_main.ali file1.o file2.o - @end smallexample - @end enumerate - - The three last steps can be grouped in a single command: - @smallexample - gnatmake my_main.adb -largs file1.o file2.o - @end smallexample - - @cindex Binder output file - @noindent - If the main program is in some language other than Ada, you may - have more than one entry point in the Ada subsystem. You must use a - special option of the binder to generate callable routines to initialize - and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). - Calls to the initialization and finalization routines must be inserted in - the main program, or some other appropriate point in the code. The call to - initialize the Ada units must occur before the first Ada subprogram is - called, and the call to finalize the Ada units must occur after the last - Ada subprogram returns. You use the same procedure for building the - program as described previously. In this case, however, the binder - only places the initialization and finalization subprograms into file - @file{b~@var{xxx}.adb} instead of the main program. - So, if the main program is not in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake -c entry_point1.adb - gnatmake -c entry_point2.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind -n entry_point1.ali entry_point2.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. You only need to give the last entry point here. For instance: - @smallexample - gnatlink entry_point2.ali file1.o file2.o - @end smallexample - @end enumerate - - @node Calling Conventions - @subsection Calling Conventions - @cindex Foreign Languages - @cindex Calling Conventions - GNAT follows standard calling sequence conventions and will thus interface - to any other language that also follows these conventions. The following - Convention identifiers are recognized by GNAT: - - @itemize @bullet - @cindex Interfacing to Ada - @cindex Other Ada compilers - @cindex Convention Ada - @item - Ada. This indicates that the standard Ada calling sequence will be - used and all Ada data items may be passed without any limitations in the - case where GNAT is used to generate both the caller and callee. It is also - possible to mix GNAT generated code and code generated by another Ada - compiler. In this case, the data types should be restricted to simple - cases, including primitive types. Whether complex data types can be passed - depends on the situation. Probably it is safe to pass simple arrays, such - as arrays of integers or floats. Records may or may not work, depending - on whether both compilers lay them out identically. Complex structures - involving variant records, access parameters, tasks, or protected types, - are unlikely to be able to be passed. - - Note that in the case of GNAT running - on a platform that supports DEC Ada 83, a higher degree of compatibility - can be guaranteed, and in particular records are layed out in an identical - manner in the two compilers. Note also that if output from two different - compilers is mixed, the program is responsible for dealing with elaboration - issues. Probably the safest approach is to write the main program in the - version of Ada other than GNAT, so that it takes care of its own elaboration - requirements, and then call the GNAT-generated adainit procedure to ensure - elaboration of the GNAT components. Consult the documentation of the other - Ada compiler for further details on elaboration. - - However, it is not possible to mix the tasking run time of GNAT and - DEC Ada 83, All the tasking operations must either be entirely within - GNAT compiled sections of the program, or entirely within DEC Ada 83 - compiled sections of the program. - - @cindex Interfacing to Assembly - @cindex Convention Assembler - @item - Assembler. Specifies assembler as the convention. In practice this has the - same effect as convention Ada (but is not equivalent in the sense of being - considered the same convention). - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembler. - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembly. - - @cindex Interfacing to COBOL - @cindex Convention COBOL - @findex COBOL - @item - COBOL. Data will be passed according to the conventions described - in section B.4 of the Ada 95 Reference Manual. - - @findex C - @cindex Interfacing to C - @cindex Convention C - @item - C. Data will be passed according to the conventions described - in section B.3 of the Ada 95 Reference Manual. - - @cindex Convention Default - @findex Default - @item - Default. Equivalent to C. - - @cindex Convention External - @findex External - @item - External. Equivalent to C. - - @findex C++ - @cindex Interfacing to C++ - @cindex Convention C++ - @item - CPP. This stands for C++. For most purposes this is identical to C. - See the separate description of the specialized GNAT pragmas relating to - C++ interfacing for further details. - - @findex Fortran - @cindex Interfacing to Fortran - @cindex Convention Fortran - @item - Fortran. Data will be passed according to the conventions described - in section B.5 of the Ada 95 Reference Manual. - - @item - Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95 - Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, - this means that the body of the subprogram is provided by the compiler itself, - usually by means of an efficient code sequence, and that the user does not - supply an explicit body for it. In an application program, the pragma can only - be applied to the following two sets of names, which the GNAT compiler - recognizes. - @itemize @bullet - @item - Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_- - Arithmetic. The corresponding subprogram declaration must have - two formal parameters. The - first one must be a signed integer type or a modular type with a binary - modulus, and the second parameter must be of type Natural. - The return type must be the same as the type of the first argument. The size - of this type can only be 8, 16, 32, or 64. - @item binary arithmetic operators: "+", "-", "*", "/" - The corresponding operator declaration must have parameters and result type - that have the same root numeric type (for example, all three are long_float - types). This simplifies the definition of operations that use type checking - to perform dimensional checks: - @smallexample - type Distance is new Long_Float; - type Time is new Long_Float; - type Velocity is new Long_Float; - function "/" (D : Distance; T : Time) - return Velocity; - pragma Import (Intrinsic, "/"); - @end smallexample - @noindent - This common idiom is often programmed with a generic definition and an explicit - body. The pragma makes it simpler to introduce such declarations. It incurs - no overhead in compilation time or code size, because it is implemented as a - single machine instruction. - @end itemize - @noindent - - @findex Stdcall - @cindex Convention Stdcall - @item - Stdcall. This is relevant only to NT/Win95 implementations of GNAT, - and specifies that the Stdcall calling sequence will be used, as defined - by the NT API. - - @findex DLL - @cindex Convention DLL - @item - DLL. This is equivalent to Stdcall. - - @findex Win32 - @cindex Convention Win32 - @item - Win32. This is equivalent to Stdcall. - - @findex Stubbed - @cindex Convention Stubbed - @item - Stubbed. This is a special convention that indicates that the compiler - should provide a stub body that raises @code{Program_Error}. - @end itemize - - @noindent - GNAT additionally provides a useful pragma @code{Convention_Identifier} - that can be used to parametrize conventions and allow additional synonyms - to be specified. For example if you have legacy code in which the convention - identifier Fortran77 was used for Fortran, you can use the configuration - pragma: - - @smallexample - pragma Convention_Identifier (Fortran77, Fortran); - @end smallexample - - @noindent - And from now on the identifier Fortran77 may be used as a convention - identifier (for example in an @code{Import} pragma) with the same - meaning as Fortran. - - @node Building Mixed Ada & C++ Programs - @section Building Mixed Ada & C++ Programs - - @noindent - Building a mixed application containing both Ada and C++ code may be a - challenge for the unaware programmer. As a matter of fact, this - interfacing has not been standardized in the Ada 95 reference manual due - to the immaturity and lack of standard of C++ at the time. This - section gives a few hints that should make this task easier. In - particular the first section addresses the differences with - interfacing with C. The second section looks into the delicate problem - of linking the complete application from its Ada and C++ parts. The last - section give some hints on how the GNAT run time can be adapted in order - to allow inter-language dispatching with a new C++ compiler. - - @menu - * Interfacing to C++:: - * Linking a Mixed C++ & Ada Program:: - * A Simple Example:: - * Adapting the Run Time to a New C++ Compiler:: - @end menu - - @node Interfacing to C++ - @subsection Interfacing to C++ - - @noindent - GNAT supports interfacing with C++ compilers generating code that is - compatible with the standard Application Binary Interface of the given - platform. - - @noindent - Interfacing can be done at 3 levels: simple data, subprograms and - classes. In the first 2 cases, GNAT offer a specific @var{Convention - CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle - names of subprograms and currently GNAT does not provide any help to - solve the demangling problem. This problem can be addressed in 2 ways: - @itemize @bullet - @item - by modifying the C++ code in order to force a C convention using - the @var{extern "C"} syntax. - - @item - by figuring out the mangled name and use it as the Link_Name argument of - the pragma import. - @end itemize - - @noindent - Interfacing at the class level can be achieved by using the GNAT specific - pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT - Reference Manual for additional information. - - @node Linking a Mixed C++ & Ada Program - @subsection Linking a Mixed C++ & Ada Program - - @noindent - Usually the linker of the C++ development system must be used to link - mixed applications because most C++ systems will resolve elaboration - issues (such as calling constructors on global class instances) - transparently during the link phase. GNAT has been adapted to ease the - use of a foreign linker for the last phase. Three cases can be - considered: - @enumerate - - @item - Using GNAT and G++ (GNU C++ compiler) from the same GCC - installation. The c++ linker can simply be called by using the c++ - specific driver called @code{c++}. Note that this setup is not - very common because it may request recompiling the whole GCC - tree from sources and it does not allow to upgrade easily to a new - version of one compiler for one of the two languages without taking the - risk of destabilizing the other. - - @smallexample - $ c++ -c file1.C - $ c++ -c file2.C - $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++ - @end smallexample - - @item - Using GNAT and G++ from 2 different GCC installations. If both compilers - are on the PATH, the same method can be used. It is important to be - aware that environment variables such as C_INCLUDE_PATH, - GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at - the same time and thus may make one of the 2 compilers operate - improperly if they are set for the other. In particular it is important - that the link command has access to the proper gcc library @file{libgcc.a}, - that is to say the one that is part of the C++ compiler - installation. The implicit link command as suggested in the gnatmake - command from the former example can be replaced by an explicit link - command with full verbosity in order to verify which library is used: - @smallexample - $ gnatbind ada_unit - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ - @end smallexample - If there is a problem due to interfering environment variables, it can - be workaround by using an intermediate script. The following example - shows the proper script to use when GNAT has not been installed at its - default location and g++ has been installed at its default location: - - @smallexample - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - unset BINUTILS_ROOT - unset GCC_ROOT - c++ $* - @end smallexample - - @item - Using a non GNU C++ compiler. The same set of command as previously - described can be used to insure that the c++ linker is - used. Nonetheless, you need to add the path to libgcc explicitely, since some - libraries needed by GNAT are located in this directory: - - @smallexample - - $ gnatlink ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - CC $* `gcc -print-libgcc-file-name` - - @end smallexample - - Where CC is the name of the non GNU C++ compiler. - - @end enumerate - - @node A Simple Example - @subsection A Simple Example - @noindent - The following example, provided as part of the GNAT examples, show how - to achieve procedural interfacing between Ada and C++ in both - directions. The C++ class A has 2 methods. The first method is exported - to Ada by the means of an extern C wrapper function. The second method - calls an Ada subprogram. On the Ada side, The C++ calls is modelized by - a limited record with a layout comparable to the C++ class. The Ada - subprogram, in turn, calls the c++ method. So from the C++ main program - the code goes back and forth between the 2 languages. - - @noindent - Here are the compilation commands - for native configurations: - @smallexample - $ gnatmake -c simple_cpp_interface - $ c++ -c cpp_main.C - $ c++ -c ex7.C - $ gnatbind -n simple_cpp_interface - $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS) - -lstdc++ ex7.o cpp_main.o - @end smallexample - @noindent - Here are the corresponding sources: - @smallexample - - //cpp_main.C - - #include "ex7.h" - - extern "C" @{ - void adainit (void); - void adafinal (void); - void method1 (A *t); - @} - - void method1 (A *t) - @{ - t->method1 (); - @} - - int main () - @{ - A obj; - adainit (); - obj.method2 (3030); - adafinal (); - @} - - //ex7.h - - class Origin @{ - public: - int o_value; - @}; - class A : public Origin @{ - public: - void method1 (void); - virtual void method2 (int v); - A(); - int a_value; - @}; - - //ex7.C - - #include "ex7.h" - #include - - extern "C" @{ void ada_method2 (A *t, int v);@} - - void A::method1 (void) - @{ - a_value = 2020; - printf ("in A::method1, a_value = %d \n",a_value); - - @} - - void A::method2 (int v) - @{ - ada_method2 (this, v); - printf ("in A::method2, a_value = %d \n",a_value); - - @} - - A::A(void) - @{ - a_value = 1010; - printf ("in A::A, a_value = %d \n",a_value); - @} - - -- Ada sources - @b{package} @b{body} Simple_Cpp_Interface @b{is} - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is} - @b{begin} - Method1 (This); - This.A_Value := V; - @b{end} Ada_Method2; - - @b{end} Simple_Cpp_Interface; - - @b{package} Simple_Cpp_Interface @b{is} - @b{type} A @b{is} @b{limited} - @b{record} - O_Value : Integer; - A_Value : Integer; - @b{end} @b{record}; - @b{pragma} Convention (C, A); - - @b{procedure} Method1 (This : @b{in} @b{out} A); - @b{pragma} Import (C, Method1); - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer); - @b{pragma} Export (C, Ada_Method2); - - @b{end} Simple_Cpp_Interface; - @end smallexample - - @node Adapting the Run Time to a New C++ Compiler - @subsection Adapting the Run Time to a New C++ Compiler - @noindent - GNAT offers the capability to derive Ada 95 tagged types directly from - preexisting C++ classes and . See "Interfacing with C++" in the GNAT - reference manual. The mechanism used by GNAT for achieving such a goal - has been made user configurable through a GNAT library unit - @code{Interfaces.CPP}. The default version of this file is adapted to - the GNU c++ compiler. Internal knowledge of the virtual - table layout used by the new C++ compiler is needed to configure - properly this unit. The Interface of this unit is known by the compiler - and cannot be changed except for the value of the constants defining the - characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, - CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source - of this unit for more details. - - @node Comparison between GNAT and C/C++ Compilation Models - @section Comparison between GNAT and C/C++ Compilation Models - - @noindent - The GNAT model of compilation is close to the C and C++ models. You can - think of Ada specs as corresponding to header files in C. As in C, you - don't need to compile specs; they are compiled when they are used. The - Ada @code{with} is similar in effect to the @code{#include} of a C - header. - - One notable difference is that, in Ada, you may compile specs separately - to check them for semantic and syntactic accuracy. This is not always - possible with C headers because they are fragments of programs that have - less specific syntactic or semantic rules. - - The other major difference is the requirement for running the binder, - which performs two important functions. First, it checks for - consistency. In C or C++, the only defense against assembling - inconsistent programs lies outside the compiler, in a makefile, for - example. The binder satisfies the Ada requirement that it be impossible - to construct an inconsistent program when the compiler is used in normal - mode. - - @cindex Elaboration order control - The other important function of the binder is to deal with elaboration - issues. There are also elaboration issues in C++ that are handled - automatically. This automatic handling has the advantage of being - simpler to use, but the C++ programmer has no control over elaboration. - Where @code{gnatbind} might complain there was no valid order of - elaboration, a C++ compiler would simply construct a program that - malfunctioned at run time. - - @node Comparison between GNAT and Conventional Ada Library Models - @section Comparison between GNAT and Conventional Ada Library Models - - @noindent - This section is intended to be useful to Ada programmers who have - previously used an Ada compiler implementing the traditional Ada library - model, as described in the Ada 95 Language Reference Manual. If you - have not used such a system, please go on to the next section. - - @cindex GNAT library - In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of - source files themselves acts as the library. Compiling Ada programs does - not generate any centralized information, but rather an object file and - a ALI file, which are of interest only to the binder and linker. - In a traditional system, the compiler reads information not only from - the source file being compiled, but also from the centralized library. - This means that the effect of a compilation depends on what has been - previously compiled. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the version of the unit most recently compiled into the library. - - @item - Inlining is effective only if the necessary body has already been - compiled into the library. - - @item - Compiling a unit may obsolete other units in the library. - @end itemize - - @noindent - In GNAT, compiling one unit never affects the compilation of any other - units because the compiler reads only source files. Only changes to source - files can affect the results of a compilation. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the source version of the unit that is currently accessible to the - compiler. - - @item - @cindex Inlining - Inlining requires the appropriate source files for the package or - subprogram bodies to be available to the compiler. Inlining is always - effective, independent of the order in which units are complied. - - @item - Compiling a unit never affects any other compilations. The editing of - sources may cause previous compilations to be out of date if they - depended on the source file being modified. - @end itemize - - @noindent - The most important result of these differences is that order of compilation - is never significant in GNAT. There is no situation in which one is - required to do one compilation before another. What shows up as order of - compilation requirements in the traditional Ada library becomes, in - GNAT, simple source dependencies; in other words, there is only a set - of rules saying what source files must be present when a file is - compiled. - - @node Compiling Using gcc - @chapter Compiling Using @code{gcc} - - @noindent - This chapter discusses how to compile Ada programs using the @code{gcc} - command. It also describes the set of switches - that can be used to control the behavior of the compiler. - @menu - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - @end menu - - @node Compiling Programs - @section Compiling Programs - - @noindent - The first step in creating an executable program is to compile the units - of the program using the @code{gcc} command. You must compile the - following files: - - @itemize @bullet - @item - the body file (@file{.adb}) for a library level subprogram or generic - subprogram - - @item - the spec file (@file{.ads}) for a library level package or generic - package that has no body - - @item - the body file (@file{.adb}) for a library level package - or generic package that has a body - - @end itemize - - @noindent - You need @emph{not} compile the following files - - @itemize @bullet - - @item - the spec of a library unit which has a body - - @item - subunits - @end itemize - - @noindent - because they are compiled as part of compiling related units. GNAT - package specs - when the corresponding body is compiled, and subunits when the parent is - compiled. - @cindex No code generated - If you attempt to compile any of these files, you will get one of the - following error messages (where fff is the name of the file you compiled): - - @smallexample - No code generated for file @var{fff} (@var{package spec}) - No code generated for file @var{fff} (@var{subunit}) - @end smallexample - - @noindent - The basic command for compiling a file containing an Ada unit is - - @smallexample - $ gcc -c [@var{switches}] @file{file name} - @end smallexample - - @noindent - where @var{file name} is the name of the Ada file (usually - having an extension - @file{.ads} for a spec or @file{.adb} for a body). - You specify the - @code{-c} switch to tell @code{gcc} to compile, but not link, the file. - The result of a successful compilation is an object file, which has the - same name as the source file but an extension of @file{.o} and an Ada - Library Information (ALI) file, which also has the same name as the - source file, but with @file{.ali} as the extension. GNAT creates these - two output files in the current directory, but you may specify a source - file in any directory using an absolute or relative path specification - containing the directory information. - - @findex gnat1 - @code{gcc} is actually a driver program that looks at the extensions of - the file arguments and loads the appropriate compiler. For example, the - GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}. - These programs are in directories known to the driver program (in some - configurations via environment variables you set), but need not be in - your path. The @code{gcc} driver also calls the assembler and any other - utilities needed to complete the generation of the required object - files. - - It is possible to supply several file names on the same @code{gcc} - command. This causes @code{gcc} to call the appropriate compiler for - each file. For example, the following command lists three separate - files to be compiled: - - @smallexample - $ gcc -c x.adb y.adb z.c - @end smallexample - - @noindent - calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and - @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}. - The compiler generates three object files @file{x.o}, @file{y.o} and - @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the - Ada compilations. Any switches apply to all the files listed, - except for - @option{-gnat@var{x}} switches, which apply only to Ada compilations. - - @node Switches for gcc - @section Switches for @code{gcc} - - @noindent - The @code{gcc} command accepts switches that control the - compilation process. These switches are fully described in this section. - First we briefly list all the switches, in alphabetical order, then we - describe the switches in more detail in functionally grouped sections. - - @menu - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - @end menu - - @table @code - @cindex @code{-b} (@code{gcc}) - @item -b @var{target} - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gcc}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item -c - @cindex @code{-c} (@code{gcc}) - Compile. Always use this switch when compiling Ada programs. - - Note: for some other languages when using @code{gcc}, notably in - the case of C and C++, it is possible to use - use @code{gcc} without a @code{-c} switch to - compile and link in one step. In the case of GNAT, you - cannot use this approach, because the binder must be run - and @code{gcc} cannot be used to run the GNAT binder. - - @item -g - @cindex @code{-g} (@code{gcc}) - Generate debugging information. This information is stored in the object - file and copied from there to the final executable file by the linker, - where it can be read by the debugger. You must use the - @code{-g} switch if you plan on using the debugger. - - @item -I@var{dir} - @cindex @code{-I} (@code{gcc}) - @cindex RTL - Direct GNAT to search the @var{dir} directory for source files needed by - the current compilation - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -I- - @cindex @code{-I-} (@code{gcc}) - @cindex RTL - Except for the source file named in the command line, do not look for source files - in the directory containing the source file named in the command line - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -o @var{file} - @cindex @code{-o} (@code{gcc}) - This switch is used in @code{gcc} to redirect the generated object file - and its associated ALI file. Beware of this switch with GNAT, because it may - cause the object file and ALI file to have different names which in turn - may confuse the binder and the linker. - - @item -O[@var{n}] - @cindex @code{-O} (@code{gcc}) - @var{n} controls the optimization level. - - @table @asis - @item n = 0 - No optimization, the default setting if no @code{-O} appears - - @item n = 1 - Normal optimization, the default if you specify @code{-O} without - an operand. - - @item n = 2 - Extensive optimization - - @item n = 3 - Extensive optimization with automatic inlining. This applies only to - inlining within a unit. For details on control of inter-unit inlining - see @xref{Subprogram Inlining Control}. - @end table - - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gcc}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -S - @cindex @code{-S} (@code{gcc}) - Used in place of @code{-c} to - cause the assembler source file to be - generated, using @file{.s} as the extension, - instead of the object file. - This may be useful if you need to examine the generated assembly code. - - @item -v - @cindex @code{-v} (@code{gcc}) - Show commands generated by the @code{gcc} driver. Normally used only for - debugging purposes or if you need to be sure what version of the - compiler you are executing. - - @item -V @var{ver} - @cindex @code{-V} (@code{gcc}) - Execute @var{ver} version of the compiler. This is the @code{gcc} - version, not the GNAT version. - - @item -gnata - Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be - activated. - - @item -gnatA - Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored. - - @item -gnatb - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -gnatc - Check syntax and semantics only (no code generation attempted). - - @item -gnatC - Compress debug information and external symbol name table entries. - - @item -gnatD - Output expanded source files for source level debugging. This switch - also suppress generation of cross-reference information (see -gnatx). - - @item -gnatec@var{path} - Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files}) - - @item -gnatem@var{path} - Specify a mapping file. (see @ref{Units to Sources Mapping Files}) - - @item -gnatE - Full dynamic elaboration checks. - - @item -gnatf - Full errors. Multiple errors per line, all undefined references. - - @item -gnatF - Externals names are folded to all uppercase. - - @item -gnatg - Internal GNAT implementation mode. This should not be used for - applications programs, it is intended only for use by the compiler - and its run-time library. For documentation, see the GNAT sources. - - @item -gnatG - List generated expanded code in source form. - - @item -gnati@var{c} - Identifier character set - (@var{c}=1/2/3/4/8/9/p/f/n/w). - - @item -gnath - Output usage information. The output is written to @file{stdout}. - - @item -gnatk@var{n} - Limit file names to @var{n} (1-999) characters (@code{k} = krunch). - - @item -gnatl - Output full source listing with embedded error messages. - - @item -gnatm@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item -gnatn - Activate inlining across unit boundaries for subprograms for which - pragma @code{inline} is specified. - - @item -gnatN - Activate front end inlining. - - @item -fno-inline - Suppresses all inlining, even if other optimization or inlining switches - are set. - - @item -fstack-check - Activates stack checking. See separate section on stack checking for - details of the use of this option. - - @item -gnato - Enable numeric overflow checking (which is not normally enabled by - default). Not that division by zero is a separate check that is not - controlled by this switch (division by zero checking is on by default). - - @item -gnatp - Suppress all checks. - - @item -gnatq - Don't quit; try semantics, even if parse errors. - - @item -gnatQ - Don't quit; generate @file{ali} and tree files even if illegalities. - - @item -gnatP - Enable polling. This is required on some systems (notably Windows NT) to - obtain asynchronous abort and asynchronous transfer of control capability. - See the description of pragma Polling in the GNAT Reference Manual for - full details. - - @item -gnatR[0/1/2/3][s] - Output representation information for declared types and objects. - - @item -gnats - Syntax check only. - - @item -gnatt - Tree output file to be generated. - - @item -gnatT nnn - Set time slice to specified number of microseconds - - @item -gnatu - List units for this compilation. - - @item -gnatU - Tag all error messages with the unique string "error:" - - @item -gnatv - Verbose mode. Full error output with source lines to @file{stdout}. - - @item -gnatV - Control level of validity checking. See separate section describing - this feature. - - @item -gnatwxxx@var{xxx} - Warning mode where - @var{xxx} is a string of options describing the exact warnings that - are enabled or disabled. See separate section on warning control. - - @item -gnatW@var{e} - Wide character encoding method - (@var{e}=n/h/u/s/e/8). - - @item -gnatx - Suppress generation of cross-reference information. - - @item -gnaty - Enable built-in style checks. See separate section describing this feature. - - @item -gnatz@var{m} - Distribution stub generation and compilation - (@var{m}=r/c for receiver/caller stubs). - - @item -gnat83 - Enforce Ada 83 restrictions. - - @item -pass-exit-codes - Catch exit codes from the compiler and use the most meaningful as - exit status. - @end table - - You may combine a sequence of GNAT switches into a single switch. For - example, the combined switch - - @cindex Combining GNAT switches - @smallexample - -gnatofi3 - @end smallexample - - @noindent - is equivalent to specifying the following sequence of switches: - - @smallexample - -gnato -gnatf -gnati3 - @end smallexample - - @noindent - The following restrictions apply to the combination of switches - in this manner: - - @itemize @bullet - @item - The switch @option{-gnatc} if combined with other switches must come - first in the string. - - @item - The switch @option{-gnats} if combined with other switches must come - first in the string. - - @item - Once a "y" appears in the string (that is a use of the @option{-gnaty} - switch), then all further characters in the switch are interpreted - as style modifiers (see description of @option{-gnaty}). - - @item - Once a "d" appears in the string (that is a use of the @option{-gnatd} - switch), then all further characters in the switch are interpreted - as debug flags (see description of @option{-gnatd}). - - @item - Once a "w" appears in the string (that is a use of the @option{-gnatw} - switch), then all further characters in the switch are interpreted - as warning mode modifiers (see description of @option{-gnatw}). - - @item - Once a "V" appears in the string (that is a use of the @option{-gnatV} - switch), then all further characters in the switch are interpreted - as validity checking options (see description of @option{-gnatV}). - - @end itemize - - @node Output and Error Message Control - @subsection Output and Error Message Control - @findex stderr - - @noindent - The standard default format for error messages is called "brief format." - Brief format messages are written to @file{stderr} (the standard error - file) and have the following form: - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:4:20: ";" should be "is" - @end smallexample - - @noindent - The first integer after the file name is the line number in the file, - and the second integer is the column number within the line. - @code{glide} can parse the error messages - and point to the referenced character. - The following switches provide control over the error message - format: - - @table @code - @item -gnatv - @cindex @option{-gnatv} (@code{gcc}) - @findex stdout - The v stands for verbose. - The effect of this setting is to write long-format error - messages to @file{stdout} (the standard output file. - The same program compiled with the - @option{-gnatv} switch would generate: - - @smallexample - @group - @cartouche - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - @end cartouche - @end group - @end smallexample - - @noindent - The vertical bar indicates the location of the error, and the @samp{>>>} - prefix can be used to search for error messages. When this switch is - used the only source lines output are those with errors. - - @item -gnatl - @cindex @option{-gnatl} (@code{gcc}) - The @code{l} stands for list. - This switch causes a full listing of - the file to be generated. The output might look as follows: - - @smallexample - @group - @cartouche - 1. procedure E is - 2. V : Integer; - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - 5. begin - 6. return Q + Q; - 7. end; - 8. begin - 9. V := X + X; - 10.end E; - @end cartouche - @end group - @end smallexample - - @noindent - @findex stderr - When you specify the @option{-gnatv} or @option{-gnatl} switches and - standard output is redirected, a brief summary is written to - @file{stderr} (standard error) giving the number of error messages and - warning messages generated. - - @item -gnatU - @cindex @option{-gnatU} (@code{gcc}) - This switch forces all error messages to be preceded by the unique - string "error:". This means that error messages take a few more - characters in space, but allows easy searching for and identification - of error messages. - - @item -gnatb - @cindex @option{-gnatb} (@code{gcc}) - The @code{b} stands for brief. - This switch causes GNAT to generate the - brief format error messages to @file{stderr} (the standard error - file) as well as the verbose - format message or full listing (which as usual is written to - @file{stdout} (the standard output file). - - @item -gnatm@var{n} - @cindex @option{-gnatm} (@code{gcc}) - The @code{m} stands for maximum. - @var{n} is a decimal integer in the - range of 1 to 999 and limits the number of error messages to be - generated. For example, using @option{-gnatm2} might yield - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:5:35: missing ".." - fatal error: maximum errors reached - compilation abandoned - @end smallexample - - @item -gnatf - @cindex @option{-gnatf} (@code{gcc}) - @cindex Error messages, suppressing - The @code{f} stands for full. - Normally, the compiler suppresses error messages that are likely to be - redundant. This switch causes all error - messages to be generated. In particular, in the case of - references to undefined variables. If a given variable is referenced - several times, the normal format of messages is - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:7:07: "V" is undefined (more references follow) - @end smallexample - - @noindent - where the parenthetical comment warns that there are additional - references to the variable @code{V}. Compiling the same program with the - @option{-gnatf} switch yields - - @smallexample - e.adb:7:07: "V" is undefined - e.adb:8:07: "V" is undefined - e.adb:8:12: "V" is undefined - e.adb:8:16: "V" is undefined - e.adb:9:07: "V" is undefined - e.adb:9:12: "V" is undefined - @end smallexample - - @item -gnatq - @cindex @option{-gnatq} (@code{gcc}) - The @code{q} stands for quit (really "don't quit"). - In normal operation mode, the compiler first parses the program and - determines if there are any syntax errors. If there are, appropriate - error messages are generated and compilation is immediately terminated. - This switch tells - GNAT to continue with semantic analysis even if syntax errors have been - found. This may enable the detection of more errors in a single run. On - the other hand, the semantic analyzer is more likely to encounter some - internal fatal error when given a syntactically invalid tree. - - @item -gnatQ - In normal operation mode, the @file{ali} file is not generated if any - illegalities are detected in the program. The use of @option{-gnatQ} forces - generation of the @file{ali} file. This file is marked as being in - error, so it cannot be used for binding purposes, but it does contain - reasonably complete cross-reference information, and thus may be useful - for use by tools (e.g. semantic browsing tools or integrated development - environments) that are driven from the @file{ali} file. - - In addition, if @option{-gnatt} is also specified, then the tree file is - generated even if there are illegalities. It may be useful in this case - to also specify @option{-gnatq} to ensure that full semantic processing - occurs. The resulting tree file can be processed by ASIS, for the purpose - of providing partial information about illegal units, but if the error - causes the tree to be badly malformed, then ASIS may crash during the - analysis. - - @end table - - @noindent - In addition to error messages, which correspond to illegalities as defined - in the Ada 95 Reference Manual, the compiler detects two kinds of warning - situations. - - @cindex Warning messages - First, the compiler considers some constructs suspicious and generates a - warning message to alert you to a possible error. Second, if the - compiler detects a situation that is sure to raise an exception at - run time, it generates a warning message. The following shows an example - of warning messages: - @smallexample - @iftex - @leftskip=.2cm - @end iftex - e.adb:4:24: warning: creation of object may raise Storage_Error - e.adb:10:17: warning: static value out of range - e.adb:10:17: warning: "Constraint_Error" will be raised at run time - - @end smallexample - - @noindent - GNAT considers a large number of situations as appropriate - for the generation of warning messages. As always, warnings are not - definite indications of errors. For example, if you do an out-of-range - assignment with the deliberate intention of raising a - @code{Constraint_Error} exception, then the warning that may be - issued does not indicate an error. Some of the situations for which GNAT - issues warnings (at least some of the time) are given in the following - list, which is not necessarily complete. - - @itemize @bullet - @item - Possible infinitely recursive calls - - @item - Out-of-range values being assigned - - @item - Possible order of elaboration problems - - @item - Unreachable code - - @item - Fixed-point type declarations with a null range - - @item - Variables that are never assigned a value - - @item - Variables that are referenced before being initialized - - @item - Task entries with no corresponding accept statement - - @item - Duplicate accepts for the same task entry in a select - - @item - Objects that take too much storage - - @item - Unchecked conversion between types of differing sizes - - @item - Missing return statements along some execution paths in a function - - @item - Incorrect (unrecognized) pragmas - - @item - Incorrect external names - - @item - Allocation from empty storage pool - - @item - Potentially blocking operations in protected types - - @item - Suspicious parenthesization of expressions - - @item - Mismatching bounds in an aggregate - - @item - Attempt to return local value by reference - - @item - Unrecognized pragmas - - @item - Premature instantiation of a generic body - - @item - Attempt to pack aliased components - - @item - Out of bounds array subscripts - - @item - Wrong length on string assignment - - @item - Violations of style rules if style checking is enabled - - @item - Unused with clauses - - @item - Bit_Order usage that does not have any effect - - @item - Compile time biased rounding of floating-point constant - - @item - Standard.Duration used to resolve universal fixed expression - - @item - Dereference of possibly null value - - @item - Declaration that is likely to cause storage error - - @item - Internal GNAT unit with'ed by application unit - - @item - Values known to be out of range at compile time - - @item - Unreferenced labels and variables - - @item - Address overlays that could clobber memory - - @item - Unexpected initialization when address clause present - - @item - Bad alignment for address clause - - @item - Useless type conversions - - @item - Redundant assignment statements - - @item - Accidental hiding of name by child unit - - @item - Unreachable code - - @item - Access before elaboration detected at compile time - - @item - A range in a @code{for} loop that is known to be null or might be null - - @end itemize - - @noindent - The following switches are available to control the handling of - warning messages: - - @table @code - @item -gnatwa (activate all optional errors) - @cindex @option{-gnatwa} (@code{gcc}) - This switch activates most optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. The warnings that are not turned on by this - switch are @option{-gnatwb} (biased rounding), - @option{-gnatwd} (implicit dereferencing), - and @option{-gnatwh} (hiding). All other optional warnings are - turned on. - - @item -gnatwA (suppress all optional errors) - @cindex @option{-gnatwA} (@code{gcc}) - This switch suppresses all optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. - - @item -gnatwb (activate warnings on biased rounding) - @cindex @option{-gnatwb} (@code{gcc}) - @cindex Rounding, biased - @cindex Biased rounding - If a static floating-point expression has a value that is exactly half - way between two adjacent machine numbers, then the rules of Ada - (Ada Reference Manual, section 4.9(38)) require that this rounding - be done away from zero, even if the normal unbiased rounding rules - at run time would require rounding towards zero. This warning message - alerts you to such instances where compile-time rounding and run-time - rounding are not equivalent. If it is important to get proper run-time - rounding, then you can force this by making one of the operands into - a variable. The default is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwB (suppress warnings on biased rounding) - @cindex @option{-gnatwB} (@code{gcc}) - This switch disables warnings on biased rounding. - - @item -gnatwc (activate warnings on conditionals) - @cindex @option{-gnatwc} (@code{gcc}) - @cindex Conditionals, constant - This switch activates warnings for conditional expressions used in - tests that are known to be True or False at compile time. The default - is that such warnings are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwC (suppress warnings on conditionals) - @cindex @option{-gnatwC} (@code{gcc}) - This switch suppresses warnings for conditional expressions used in - tests that are known to be True or False at compile time. - - @item -gnatwd (activate warnings on implicit dereferencing) - @cindex @option{-gnatwd} (@code{gcc}) - If this switch is set, then the use of a prefix of an access type - in an indexed component, slice, or selected component without an - explicit @code{.all} will generate a warning. With this warning - enabled, access checks occur only at points where an explicit - @code{.all} appears in the source code (assuming no warnings are - generated as a result of this switch). The default is that such - warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwD (suppress warnings on implicit dereferencing) - @cindex @option{-gnatwD} (@code{gcc}) - @cindex Implicit dereferencing - @cindex Dereferencing, implicit - This switch suppresses warnings for implicit deferences in - indexed components, slices, and selected components. - - @item -gnatwe (treat warnings as errors) - @cindex @option{-gnatwe} (@code{gcc}) - @cindex Warnings, treat as error - This switch causes warning messages to be treated as errors. - The warning string still appears, but the warning messages are counted - as errors, and prevent the generation of an object file. - - @item -gnatwf (activate warnings on unreferenced formals) - @cindex @option{-gnatwf} (@code{gcc}) - @cindex Formals, unreferenced - This switch causes a warning to be generated if a formal parameter - is not referenced in the body of the subprogram. This warning can - also be turned on using @option{-gnatwa} or @option{-gnatwu}. - - @item -gnatwF (suppress warnings on unreferenced formals) - @cindex @option{-gnatwF} (@code{gcc}) - This switch suppresses warnings for unreferenced formal - parameters. Note that the - combination @option{-gnatwu} followed by @option{-gnatwF} has the - effect of warning on unreferenced entities other than subprogram - formals. - - @item -gnatwh (activate warnings on hiding) - @cindex @option{-gnatwh} (@code{gcc}) - @cindex Hiding of Declarations - This switch activates warnings on hiding declarations. - A declaration is considered hiding - if it is for a non-overloadable entity, and it declares an entity with the - same name as some other entity that is directly or use-visible. The default - is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of this warning option. - - @item -gnatwH (suppress warnings on hiding) - @cindex @option{-gnatwH} (@code{gcc}) - This switch suppresses warnings on hiding declarations. - - @item -gnatwi (activate warnings on implementation units). - @cindex @option{-gnatwi} (@code{gcc}) - This switch activates warnings for a @code{with} of an internal GNAT - implementation unit, defined as any unit from the @code{Ada}, - @code{Interfaces}, @code{GNAT}, - or @code{System} - hierarchies that is not - documented in either the Ada Reference Manual or the GNAT - Programmer's Reference Manual. Such units are intended only - for internal implementation purposes and should not be @code{with}'ed - by user programs. The default is that such warnings are generated - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwI (disable warnings on implementation units). - @cindex @option{-gnatwI} (@code{gcc}) - This switch disables warnings for a @code{with} of an internal GNAT - implementation unit. - - @item -gnatwl (activate warnings on elaboration pragmas) - @cindex @option{-gnatwl} (@code{gcc}) - @cindex Elaboration, warnings - This switch activates warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. The default is that such warnings - are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwL (suppress warnings on elaboration pragmas) - @cindex @option{-gnatwL} (@code{gcc}) - This switch suppresses warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. - - @item -gnatwo (activate warnings on address clause overlays) - @cindex @option{-gnatwo} (@code{gcc}) - @cindex Address Clauses, warnings - This switch activates warnings for possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. The default is that such warnings are generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwO (suppress warnings on address clause overlays) - @cindex @option{-gnatwO} (@code{gcc}) - This switch suppresses warnings on possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. - - @item -gnatwp (activate warnings on ineffective pragma Inlines) - @cindex @option{-gnatwp} (@code{gcc}) - @cindex Inlining, warnings - This switch activates warnings for failure of front end inlining - (activated by @option{-gnatN}) to inline a particular call. There are - many reasons for not being able to inline a call, including most - commonly that the call is too complex to inline. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwP (suppress warnings on ineffective pragma Inlines) - @cindex @option{-gnatwP} (@code{gcc}) - This switch suppresses warnings on ineffective pragma Inlines. If the - inlining mechanism cannot inline a call, it will simply ignore the - request silently. - - @item -gnatwr (activate warnings on redundant constructs) - @cindex @option{-gnatwr} (@code{gcc}) - This switch activates warnings for redundant constructs. The following - is the current list of constructs regarded as redundant: - This warning can also be turned on using @option{-gnatwa}. - - @itemize @bullet - @item - Assignment of an item to itself. - @item - Type conversion that converts an expression to its own type. - @item - Use of the attribute @code{Base} where @code{typ'Base} is the same - as @code{typ}. - @item - Use of pragma @code{Pack} when all components are placed by a record - representation clause. - @end itemize - - @item -gnatwR (suppress warnings on redundant constructs) - @cindex @option{-gnatwR} (@code{gcc}) - This switch suppresses warnings for redundant constructs. - - @item -gnatws (suppress all warnings) - @cindex @option{-gnatws} (@code{gcc}) - This switch completely suppresses the - output of all warning messages from the GNAT front end. - Note that it does not suppress warnings from the @code{gcc} back end. - To suppress these back end warnings as well, use the switch @code{-w} - in addition to @option{-gnatws}. - - @item -gnatwu (activate warnings on unused entities) - @cindex @option{-gnatwu} (@code{gcc}) - This switch activates warnings to be generated for entities that - are defined but not referenced, and for units that are @code{with}'ed - and not - referenced. In the case of packages, a warning is also generated if - no entities in the package are referenced. This means that if the package - is referenced but the only references are in @code{use} - clauses or @code{renames} - declarations, a warning is still generated. A warning is also generated - for a generic package that is @code{with}'ed but never instantiated. - In the case where a package or subprogram body is compiled, and there - is a @code{with} on the corresponding spec - that is only referenced in the body, - a warning is also generated, noting that the - @code{with} can be moved to the body. The default is that - such warnings are not generated. - This switch also activates warnings on unreferenced formals - (it is includes the effect of @option{-gnatwf}). - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwU (suppress warnings on unused entities) - @cindex @option{-gnatwU} (@code{gcc}) - This switch suppresses warnings for unused entities and packages. - It also turns off warnings on unreferenced formals (and thus includes - the effect of @option{-gnatwF}). - - @noindent - A string of warning parameters can be used in the same parameter. For example: - - @smallexample - -gnatwaLe - @end smallexample - - @noindent - Would turn on all optional warnings except for elaboration pragma warnings, - and also specify that warnings should be treated as errors. - - @item -w - @cindex @code{-w} - This switch suppresses warnings from the @code{gcc} backend. It may be - used in conjunction with @option{-gnatws} to ensure that all warnings - are suppressed during the entire compilation process. - - @end table - - @node Debugging and Assertion Control - @subsection Debugging and Assertion Control - - @table @code - @item -gnata - @cindex @option{-gnata} (@code{gcc}) - @findex Assert - @findex Debug - @cindex Assertions - - @noindent - The pragmas @code{Assert} and @code{Debug} normally have no effect and - are ignored. This switch, where @samp{a} stands for assert, causes - @code{Assert} and @code{Debug} pragmas to be activated. - - The pragmas have the form: - - @smallexample - @group - @cartouche - @b{pragma} Assert (@var{Boolean-expression} [, - @var{static-string-expression}]) - @b{pragma} Debug (@var{procedure call}) - @end cartouche - @end group - @end smallexample - - @noindent - The @code{Assert} pragma causes @var{Boolean-expression} to be tested. - If the result is @code{True}, the pragma has no effect (other than - possible side effects from evaluating the expression). If the result is - @code{False}, the exception @code{Assert_Failure} declared in the package - @code{System.Assertions} is - raised (passing @var{static-string-expression}, if present, as the - message associated with the exception). If no string expression is - given the default is a string giving the file name and line number - of the pragma. - - The @code{Debug} pragma causes @var{procedure} to be called. Note that - @code{pragma Debug} may appear within a declaration sequence, allowing - debugging procedures to be called between declarations. - - @end table - - @node Validity Checking - @subsection Validity Checking - @findex Validity Checking - - @noindent - The Ada 95 Reference Manual has specific requirements for checking - for invalid values. In particular, RM 13.9.1 requires that the - evaluation of invalid values (for example from unchecked conversions), - not result in erroneous execution. In GNAT, the result of such an - evaluation in normal default mode is to either use the value - unmodified, or to raise Constraint_Error in those cases where use - of the unmodified value would cause erroneous execution. The cases - where unmodified values might lead to erroneous execution are case - statements (where a wild jump might result from an invalid value), - and subscripts on the left hand side (where memory corruption could - occur as a result of an invalid value). - - The @option{-gnatVx} switch allows more control over the validity checking - mode. The @code{x} argument here is a string of letters which control which - validity checks are performed in addition to the default checks described - above. - - @itemize @bullet - @item - @option{-gnatVc} Validity checks for copies - - The right hand side of assignments, and the initializing values of - object declarations are validity checked. - - @item - @option{-gnatVd} Default (RM) validity checks - - Some validity checks are done by default following normal Ada semantics - (RM 13.9.1 (9-11)). - A check is done in case statements that the expression is within the range - of the subtype. If it is not, Constraint_Error is raised. - For assignments to array components, a check is done that the expression used - as index is within the range. If it is not, Constraint_Error is raised. - Both these validity checks may be turned off using switch @option{-gnatVD}. - They are turned on by default. If @option{-gnatVD} is specified, a subsequent - switch @option{-gnatVd} will leave the checks turned on. - Switch @option{-gnatVD} should be used only if you are sure that all such - expressions have valid values. If you use this switch and invalid values - are present, then the program is erroneous, and wild jumps or memory - overwriting may occur. - - @item - @option{-gnatVi} Validity checks for @code{in} mode parameters - - Arguments for parameters of mode @code{in} are validity checked in function - and procedure calls at the point of call. - - @item - @option{-gnatVm} Validity checks for @code{in out} mode parameters - - Arguments for parameters of mode @code{in out} are validity checked in - procedure calls at the point of call. The @code{'m'} here stands for - modify, since this concerns parameters that can be modified by the call. - Note that there is no specific option to test @code{out} parameters, - but any reference within the subprogram will be tested in the usual - manner, and if an invalid value is copied back, any reference to it - will be subject to validity checking. - - @item - @option{-gnatVo} Validity checks for operator and attribute operands - - Arguments for predefined operators and attributes are validity checked. - This includes all operators in package @code{Standard}, - the shift operators defined as intrinsic in package @code{Interfaces} - and operands for attributes such as @code{Pos}. - - @item - @option{-gnatVr} Validity checks for function returns - - The expression in @code{return} statements in functions is validity - checked. - - @item - @option{-gnatVs} Validity checks for subscripts - - All subscripts expressions are checked for validity, whether they appear - on the right side or left side (in default mode only left side subscripts - are validity checked). - - @item - @option{-gnatVt} Validity checks for tests - - Expressions used as conditions in @code{if}, @code{while} or @code{exit} - statements are checked, as well as guard expressions in entry calls. - - @item - @option{-gnatVf} Validity checks for floating-point values - - In the absence of this switch, validity checking occurs only for discrete - values. If @option{-gnatVf} is specified, then validity checking also applies - for floating-point values, and NaN's and infinities are considered invalid, - as well as out of range values for constrained types. Note that this means - that standard @code{IEEE} infinity mode is not allowed. The exact contexts - in which floating-point values are checked depends on the setting of other - options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does - not matter) specifies that floating-point parameters of mode @code{in} should - be validity checked. - - @item - @option{-gnatVa} All validity checks - - All the above validity checks are turned on. That is @option{-gnatVa} is - equivalent to @code{gnatVcdfimorst}. - - @item - @option{-gnatVn} No validity checks - - This switch turns off all validity checking, including the default checking - for case statements and left hand side subscripts. Note that the use of - the switch @option{-gnatp} supresses all run-time checks, including - validity checks, and thus implies @option{-gnatVn}. - - @end itemize - - The @option{-gnatV} switch may be followed by a string of letters to turn on - a series of validity checking options. For example, @option{-gnatVcr} specifies - that in addition to the default validity checking, copies and function - return expressions be validity checked. In order to make it easier to specify - a set of options, the upper case letters @code{CDFIMORST} may be used to turn - off the corresponding lower case option, so for example @option{-gnatVaM} turns - on all validity checking options except for checking of @code{in out} - procedure arguments. - - The specification of additional validity checking generates extra code (and - in the case of @option{-gnatva} the code expansion can be substantial. However, - these additional checks can be very useful in smoking out cases of - uninitialized variables, incorrect use of unchecked conversion, and other - errors leading to invalid values. The use of pragma @code{Initialize_Scalars} - is useful in conjunction with the extra validity checking, since this - ensures that wherever possible uninitialized variables have invalid values. - - See also the pragma @code{Validity_Checks} which allows modification of - the validity checking mode at the program source level, and also allows for - temporary disabling of validity checks. - - @node Style Checking - @subsection Style Checking - @findex Style checking - - @noindent - The -gnaty@var{x} switch causes the compiler to - enforce specified style rules. A limited set of style rules has been used - in writing the GNAT sources themselves. This switch allows user programs - to activate all or some of these checks. If the source program fails a - specified style check, an appropriate warning message is given, preceded by - the character sequence "(style)". - The string @var{x} is a sequence of letters or digits - indicating the particular style - checks to be performed. The following checks are defined: - - @table @code - @item 1-9 (specify indentation level) - If a digit from 1-9 appears in the string after @option{-gnaty} then proper - indentation is checked, with the digit indicating the indentation level - required. The general style of required indentation is as specified by - the examples in the Ada Reference Manual. Full line comments must be - aligned with the @code{--} starting on a column that is a multiple of - the alignment level. - - @item a (check attribute casing) - If the letter a appears in the string after @option{-gnaty} then - attribute names, including the case of keywords such as @code{digits} - used as attributes names, must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item b (blanks not allowed at statement end) - If the letter b appears in the string after @option{-gnaty} then - trailing blanks are not allowed at the end of statements. The purpose of this - rule, together with h (no horizontal tabs), is to enforce a canonical format - for the use of blanks to separate source tokens. - - @item c (check comments) - If the letter c appears in the string after @option{-gnaty} then - comments must meet the following set of rules: - - @itemize @bullet - - @item - The "--" that starts the column must either start in column one, or else - at least one blank must precede this sequence. - - @item - Comments that follow other tokens on a line must have at least one blank - following the "--" at the start of the comment. - - @item - Full line comments must have two blanks following the "--" that starts - the comment, with the following exceptions. - - @item - A line consisting only of the "--" characters, possibly preceded by blanks - is permitted. - - @item - A comment starting with "--x" where x is a special character is permitted. - This alows proper processing of the output generated by specialized tools - including @code{gnatprep} (where --! is used) and the SPARK annnotation - language (where --# is used). For the purposes of this rule, a special - character is defined as being in one of the ASCII ranges - 16#21#..16#2F# or 16#3A#..16#3F#. - - @item - A line consisting entirely of minus signs, possibly preceded by blanks, is - permitted. This allows the construction of box comments where lines of minus - signs are used to form the top and bottom of the box. - - @item - If a comment starts and ends with "--" is permitted as long as at least - one blank follows the initial "--". Together with the preceding rule, - this allows the construction of box comments, as shown in the following - example: - @smallexample - --------------------------- - -- This is a box comment -- - -- with two text lines. -- - --------------------------- - @end smallexample - @end itemize - - @item e (check end/exit labels) - If the letter e appears in the string after @option{-gnaty} then - optional labels on @code{end} statements ending subprograms and on - @code{exit} statements exiting named loops, are required to be present. - - @item f (no form feeds or vertical tabs) - If the letter f appears in the string after @option{-gnaty} then - neither form feeds nor vertical tab characters are not permitted - in the source text. - - @item h (no horizontal tabs) - If the letter h appears in the string after @option{-gnaty} then - horizontal tab characters are not permitted in the source text. - Together with the b (no blanks at end of line) check, this - enforces a canonical form for the use of blanks to separate - source tokens. - - @item i (check if-then layout) - If the letter i appears in the string after @option{-gnaty}, - then the keyword @code{then} must appear either on the same - line as corresponding @code{if}, or on a line on its own, lined - up under the @code{if} with at least one non-blank line in between - containing all or part of the condition to be tested. - - @item k (check keyword casing) - If the letter k appears in the string after @option{-gnaty} then - all keywords must be in lower case (with the exception of keywords - such as @code{digits} used as attribute names to which this check - does not apply). - - @item l (check layout) - If the letter l appears in the string after @option{-gnaty} then - layout of statement and declaration constructs must follow the - recommendations in the Ada Reference Manual, as indicated by the - form of the syntax rules. For example an @code{else} keyword must - be lined up with the corresponding @code{if} keyword. - - There are two respects in which the style rule enforced by this check - option are more liberal than those in the Ada Reference Manual. First - in the case of record declarations, it is permissible to put the - @code{record} keyword on the same line as the @code{type} keyword, and - then the @code{end} in @code{end record} must line up under @code{type}. - For example, either of the following two layouts is acceptable: - - @smallexample - @group - @cartouche - @b{type} q @b{is record} - a : integer; - b : integer; - @b{end record}; - - @b{type} q @b{is} - @b{record} - a : integer; - b : integer; - @b{end record}; - @end cartouche - @end group - @end smallexample - - @noindent - Second, in the case of a block statement, a permitted alternative - is to put the block label on the same line as the @code{declare} or - @code{begin} keyword, and then line the @code{end} keyword up under - the block label. For example both the following are permitted: - - @smallexample - @group - @cartouche - Block : @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - - Block : - @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - @end cartouche - @end group - @end smallexample - - @noindent - The same alternative format is allowed for loops. For example, both of - the following are permitted: - - @smallexample - @group - @cartouche - Clear : @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - - Clear : - @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - @end cartouche - @end group - @end smallexample - - @item m (check maximum line length) - If the letter m appears in the string after @option{-gnaty} - then the length of source lines must not exceed 79 characters, including - any trailing blanks. The value of 79 allows convenient display on an - 80 character wide device or window, allowing for possible special - treatment of 80 character lines. - - @item Mnnn (set maximum line length) - If the sequence Mnnn, where nnn is a decimal number, appears in - the string after @option{-gnaty} then the length of lines must not exceed the - given value. - - @item n (check casing of entities in Standard) - If the letter n appears in the string - after @option{-gnaty} then any identifier from Standard must be cased - to match the presentation in the Ada Reference Manual (for example, - @code{Integer} and @code{ASCII.NUL}). - - @item o (check order of subprogram bodies) - If the letter o appears in the string - after @option{-gnaty} then all subprogram bodies in a given scope - (e.g. a package body) must be in alphabetical order. The ordering - rule uses normal Ada rules for comparing strings, ignoring casing - of letters, except that if there is a trailing numeric suffix, then - the value of this suffix is used in the ordering (e.g. Junk2 comes - before Junk10). - - @item p (check pragma casing) - If the letter p appears in the string after @option{-gnaty} then - pragma names must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item r (check references) - If the letter r appears in the string after @option{-gnaty} - then all identifier references must be cased in the same way as the - corresponding declaration. No specific casing style is imposed on - identifiers. The only requirement is for consistency of references - with declarations. - - @item s (check separate specs) - If the letter s appears in the string after @option{-gnaty} then - separate declarations ("specs") are required for subprograms (a - body is not allowed to serve as its own declaration). The only - exception is that parameterless library level procedures are - not required to have a separate declaration. This exception covers - the most frequent form of main program procedures. - - @item t (check token spacing) - If the letter t appears in the string after @option{-gnaty} then - the following token spacing rules are enforced: - - @itemize @bullet - - @item - The keywords @code{abs} and @code{not} must be followed by a space. - - @item - The token @code{=>} must be surrounded by spaces. - - @item - The token @code{<>} must be preceded by a space or a left parenthesis. - - @item - Binary operators other than @code{**} must be surrounded by spaces. - There is no restriction on the layout of the @code{**} binary operator. - - @item - Colon must be surrounded by spaces. - - @item - Colon-equal (assignment) must be surrounded by spaces. - - @item - Comma must be the first non-blank character on the line, or be - immediately preceded by a non-blank character, and must be followed - by a space. - - @item - If the token preceding a left paren ends with a letter or digit, then - a space must separate the two tokens. - - @item - A right parenthesis must either be the first non-blank character on - a line, or it must be preceded by a non-blank character. - - @item - A semicolon must not be preceded by a space, and must not be followed by - a non-blank character. - - @item - A unary plus or minus may not be followed by a space. - - @item - A vertical bar must be surrounded by spaces. - @end itemize - - @noindent - In the above rules, appearing in column one is always permitted, that is, - counts as meeting either a requirement for a required preceding space, - or as meeting a requirement for no preceding space. - - Appearing at the end of a line is also always permitted, that is, counts - as meeting either a requirement for a following space, or as meeting - a requirement for no following space. - - @end table - - @noindent - If any of these style rules is violated, a message is generated giving - details on the violation. The initial characters of such messages are - always "(style)". Note that these messages are treated as warning - messages, so they normally do not prevent the generation of an object - file. The @option{-gnatwe} switch can be used to treat warning messages, - including style messages, as fatal errors. - - @noindent - The switch - @option{-gnaty} on its own (that is not followed by any letters or digits), - is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking - options are enabled with - the exception of -gnatyo, - with an indentation level of 3. This is the standard - checking option that is used for the GNAT sources. - - @node Run-Time Checks - @subsection Run-Time Checks - @cindex Division by zero - @cindex Access before elaboration - @cindex Checks, division by zero - @cindex Checks, access before elaboration - - @noindent - If you compile with the default options, GNAT will insert many run-time - checks into the compiled code, including code that performs range - checking against constraints, but not arithmetic overflow checking for - integer operations (including division by zero) or checks for access - before elaboration on subprogram calls. All other run-time checks, as - required by the Ada 95 Reference Manual, are generated by default. - The following @code{gcc} switches refine this default behavior: - - @table @code - @item -gnatp - @cindex @option{-gnatp} (@code{gcc}) - @cindex Suppressing checks - @cindex Checks, suppressing - @findex Suppress - Suppress all run-time checks as though @code{pragma Suppress (all_checks}) - had been present in the source. Validity checks are also suppressed (in - other words @option{-gnatp} also implies @option{-gnatVn}. - Use this switch to improve the performance - of the code at the expense of safety in the presence of invalid data or - program bugs. - - @item -gnato - @cindex @option{-gnato} (@code{gcc}) - @cindex Overflow checks - @cindex Check, overflow - Enables overflow checking for integer operations. - This causes GNAT to generate slower and larger executable - programs by adding code to check for overflow (resulting in raising - @code{Constraint_Error} as required by standard Ada - semantics). These overflow checks correspond to situations in which - the true value of the result of an operation may be outside the base - range of the result type. The following example shows the distinction: - - @smallexample - X1 : Integer := Integer'Last; - X2 : Integer range 1 .. 5 := 5; - ... - X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error - X2 := X2 + 1; -- range check, @option{-gnato} has no effect here - @end smallexample - - @noindent - Here the first addition results in a value that is outside the base range - of Integer, and hence requires an overflow check for detection of the - constraint error. The second increment operation results in a violation - of the explicit range constraint, and such range checks are always - performed. Basically the compiler can assume that in the absence of - the @option{-gnato} switch that any value of type @code{xxx} is - in range of the base type of @code{xxx}. - - @findex Machine_Overflows - Note that the @option{-gnato} switch does not affect the code generated - for any floating-point operations; it applies only to integer - semantics). - For floating-point, GNAT has the @code{Machine_Overflows} - attribute set to @code{False} and the normal mode of operation is to - generate IEEE NaN and infinite values on overflow or invalid operations - (such as dividing 0.0 by 0.0). - - The reason that we distinguish overflow checking from other kinds of - range constraint checking is that a failure of an overflow check can - generate an incorrect value, but cannot cause erroneous behavior. This - is unlike the situation with a constraint check on an array subscript, - where failure to perform the check can result in random memory description, - or the range check on a case statement, where failure to perform the check - can cause a wild jump. - - Note again that @option{-gnato} is off by default, so overflow checking is - not performed in default mode. This means that out of the box, with the - default settings, GNAT does not do all the checks expected from the - language description in the Ada Reference Manual. If you want all constraint - checks to be performed, as described in this Manual, then you must - explicitly use the -gnato switch either on the @code{gnatmake} or - @code{gcc} command. - - @item -gnatE - @cindex @option{-gnatE} (@code{gcc}) - @cindex Elaboration checks - @cindex Check, elaboration - Enables dynamic checks for access-before-elaboration - on subprogram calls and generic instantiations. - For full details of the effect and use of this switch, - @xref{Compiling Using gcc}. - @end table - - @findex Unsuppress - @noindent - The setting of these switches only controls the default setting of the - checks. You may modify them using either @code{Suppress} (to remove - checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in - the program source. - - @node Stack Overflow Checking - @subsection Stack Overflow Checking - @cindex Stack Overflow Checking - @cindex -fstack-check - - @noindent - For most operating systems, @code{gcc} does not perform stack overflow - checking by default. This means that if the main environment task or - some other task exceeds the available stack space, then unpredictable - behavior will occur. - - To activate stack checking, compile all units with the gcc option - @code{-fstack-check}. For example: - - @smallexample - gcc -c -fstack-check package1.adb - @end smallexample - - @noindent - Units compiled with this option will generate extra instructions to check - that any use of the stack (for procedure calls or for declaring local - variables in declare blocks) do not exceed the available stack space. - If the space is exceeded, then a @code{Storage_Error} exception is raised. - - For declared tasks, the stack size is always controlled by the size - given in an applicable @code{Storage_Size} pragma (or is set to - the default size if no pragma is used. - - For the environment task, the stack size depends on - system defaults and is unknown to the compiler. The stack - may even dynamically grow on some systems, precluding the - normal Ada semantics for stack overflow. In the worst case, - unbounded stack usage, causes unbounded stack expansion - resulting in the system running out of virtual memory. - - The stack checking may still work correctly if a fixed - size stack is allocated, but this cannot be guaranteed. - To ensure that a clean exception is signalled for stack - overflow, set the environment variable - @code{GNAT_STACK_LIMIT} to indicate the maximum - stack area that can be used, as in: - @cindex GNAT_STACK_LIMIT - - @smallexample - SET GNAT_STACK_LIMIT 1600 - @end smallexample - - @noindent - The limit is given in kilobytes, so the above declaration would - set the stack limit of the environment task to 1.6 megabytes. - Note that the only purpose of this usage is to limit the amount - of stack used by the environment task. If it is necessary to - increase the amount of stack for the environment task, then this - is an operating systems issue, and must be addressed with the - appropriate operating systems commands. - - @node Run-Time Control - @subsection Run-Time Control - - @table @code - @item -gnatT nnn - @cindex @option{-gnatT} (@code{gcc}) - @cindex Time Slicing - - @noindent - The @code{gnatT} switch can be used to specify the time-slicing value - to be used for task switching between equal priority tasks. The value - @code{nnn} is given in microseconds as a decimal integer. - - Setting the time-slicing value is only effective if the underlying thread - control system can accommodate time slicing. Check the documentation of - your operating system for details. Note that the time-slicing value can - also be set by use of pragma @code{Time_Slice} or by use of the - @code{t} switch in the gnatbind step. The pragma overrides a command - line argument if both are present, and the @code{t} switch for gnatbind - overrides both the pragma and the @code{gcc} command line switch. - @end table - - @node Using gcc for Syntax Checking - @subsection Using @code{gcc} for Syntax Checking - @table @code - @item -gnats - @cindex @option{-gnats} (@code{gcc}) - - @noindent - The @code{s} stands for syntax. - - Run GNAT in syntax checking only mode. For - example, the command - - @smallexample - $ gcc -c -gnats x.adb - @end smallexample - - @noindent - compiles file @file{x.adb} in syntax-check-only mode. You can check a - series of files in a single command - , and can use wild cards to specify such a group of files. - Note that you must specify the @code{-c} (compile - only) flag in addition to the @option{-gnats} flag. - . - - You may use other switches in conjunction with @option{-gnats}. In - particular, @option{-gnatl} and @option{-gnatv} are useful to control the - format of any generated error messages. - - The output is simply the error messages, if any. No object file or ALI - file is generated by a syntax-only compilation. Also, no units other - than the one specified are accessed. For example, if a unit @code{X} - @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax - check only mode does not access the source file containing unit - @code{Y}. - - @cindex Multiple units, syntax checking - Normally, GNAT allows only a single unit in a source file. However, this - restriction does not apply in syntax-check-only mode, and it is possible - to check a file containing multiple compilation units concatenated - together. This is primarily used by the @code{gnatchop} utility - (@pxref{Renaming Files Using gnatchop}). - @end table - - @node Using gcc for Semantic Checking - @subsection Using @code{gcc} for Semantic Checking - @table @code - @item -gnatc - @cindex @option{-gnatc} (@code{gcc}) - - @noindent - The @code{c} stands for check. - Causes the compiler to operate in semantic check mode, - with full checking for all illegalities specified in the - Ada 95 Reference Manual, but without generation of any object code - (no object file is generated). - - Because dependent files must be accessed, you must follow the GNAT - semantic restrictions on file structuring to operate in this mode: - - @itemize @bullet - @item - The needed source files must be accessible - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item - Each file must contain only one compilation unit. - - @item - The file name and unit name must match (@pxref{File Naming Rules}). - @end itemize - - The output consists of error messages as appropriate. No object file is - generated. An @file{ALI} file is generated for use in the context of - cross-reference tools, but this file is marked as not being suitable - for binding (since no object file is generated). - The checking corresponds exactly to the notion of - legality in the Ada 95 Reference Manual. - - Any unit can be compiled in semantics-checking-only mode, including - units that would not normally be compiled (subunits, - and specifications where a separate body is present). - @end table - - @node Compiling Ada 83 Programs - @subsection Compiling Ada 83 Programs - @table @code - @cindex Ada 83 compatibility - @item -gnat83 - @cindex @option{-gnat83} (@code{gcc}) - @cindex ACVC, Ada 83 tests - - @noindent - Although GNAT is primarily an Ada 95 compiler, it accepts this switch to - specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify - this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics - where this can be done easily. - It is not possible to guarantee this switch does a perfect - job; for example, some subtle tests, such as are - found in earlier ACVC tests (that have been removed from the ACVC suite for Ada - 95), may not compile correctly. However, for most purposes, using - this switch should help to ensure that programs that compile correctly - under the @option{-gnat83} switch can be ported easily to an Ada 83 - compiler. This is the main use of the switch. - - With few exceptions (most notably the need to use @code{<>} on - @cindex Generic formal parameters - unconstrained generic formal parameters, the use of the new Ada 95 - keywords, and the use of packages - with optional bodies), it is not necessary to use the - @option{-gnat83} switch when compiling Ada 83 programs, because, with rare - exceptions, Ada 95 is upwardly compatible with Ada 83. This - means that a correct Ada 83 program is usually also a correct Ada 95 - program. - - @end table - - @node Character Set Control - @subsection Character Set Control - @table @code - @item -gnati@var{c} - @cindex @code{-gnati} (@code{gcc}) - - @noindent - Normally GNAT recognizes the Latin-1 character set in source program - identifiers, as described in the Ada 95 Reference Manual. - This switch causes - GNAT to recognize alternate character sets in identifiers. @var{c} is a - single character indicating the character set, as follows: - - @table @code - @item 1 - Latin-1 identifiers - - @item 2 - Latin-2 letters allowed in identifiers - - @item 3 - Latin-3 letters allowed in identifiers - - @item 4 - Latin-4 letters allowed in identifiers - - @item 5 - Latin-5 (Cyrillic) letters allowed in identifiers - - @item 9 - Latin-9 letters allowed in identifiers - - @item p - IBM PC letters (code page 437) allowed in identifiers - - @item 8 - IBM PC letters (code page 850) allowed in identifiers - - @item f - Full upper-half codes allowed in identifiers - - @item n - No upper-half codes allowed in identifiers - - @item w - Wide-character codes (that is, codes greater than 255) - allowed in identifiers - @end table - - @xref{Foreign Language Representation}, for full details on the - implementation of these character sets. - - @item -gnatW@var{e} - @cindex @code{-gnatW} (@code{gcc}) - Specify the method of encoding for wide characters. - @var{e} is one of the following: - - @table @code - - @item h - Hex encoding (brackets coding also recognized) - - @item u - Upper half encoding (brackets encoding also recognized) - - @item s - Shift/JIS encoding (brackets encoding also recognized) - - @item e - EUC encoding (brackets encoding also recognized) - - @item 8 - UTF-8 encoding (brackets encoding also recognized) - - @item b - Brackets encoding only (default value) - @end table - For full details on the these encoding - methods see @xref{Wide Character Encodings}. - Note that brackets coding is always accepted, even if one of the other - options is specified, so for example @option{-gnatW8} specifies that both - brackets and @code{UTF-8} encodings will be recognized. The units that are - with'ed directly or indirectly will be scanned using the specified - representation scheme, and so if one of the non-brackets scheme is - used, it must be used consistently throughout the program. However, - since brackets encoding is always recognized, it may be conveniently - used in standard libraries, allowing these libraries to be used with - any of the available coding schemes. - scheme. If no @option{-gnatW?} parameter is present, then the default - representation is Brackets encoding only. - - Note that the wide character representation that is specified (explicitly - or by default) for the main program also acts as the default encoding used - for Wide_Text_IO files if not specifically overridden by a WCEM form - parameter. - - @end table - @node File Naming Control - @subsection File Naming Control - - @table @code - @item -gnatk@var{n} - @cindex @option{-gnatk} (@code{gcc}) - Activates file name "krunching". @var{n}, a decimal integer in the range - 1-999, indicates the maximum allowable length of a file name (not - including the @file{.ads} or @file{.adb} extension). The default is not - to enable file name krunching. - - For the source file naming rules, @xref{File Naming Rules}. - @end table - - @node Subprogram Inlining Control - @subsection Subprogram Inlining Control - - @table @code - @item -gnatn - @cindex @option{-gnatn} (@code{gcc}) - The @code{n} here is intended to suggest the first syllable of the - word "inline". - GNAT recognizes and processes @code{Inline} pragmas. However, for the - inlining to actually occur, optimization must be enabled. To enable - inlining across unit boundaries, this is, inlining a call in one unit of - a subprogram declared in a @code{with}'ed unit, you must also specify - this switch. - In the absence of this switch, GNAT does not attempt - inlining across units and does not need to access the bodies of - subprograms for which @code{pragma Inline} is specified if they are not - in the current unit. - - If you specify this switch the compiler will access these bodies, - creating an extra source dependency for the resulting object file, and - where possible, the call will be inlined. - For further details on when inlining is possible - see @xref{Inlining of Subprograms}. - - @item -gnatN - @cindex @option{-gnatN} (@code{gcc}) - The front end inlining activated by this switch is generally more extensive, - and quite often more effective than the standard @option{-gnatn} inlining mode. - It will also generate additional dependencies. - - @end table - - @node Auxiliary Output Control - @subsection Auxiliary Output Control - - @table @code - @item -gnatt - @cindex @option{-gnatt} (@code{gcc}) - @cindex Writing internal trees - @cindex Internal trees, writing to file - Causes GNAT to write the internal tree for a unit to a file (with the - extension @file{.adt}. - This not normally required, but is used by separate analysis tools. - Typically - these tools do the necessary compilations automatically, so you should - not have to specify this switch in normal operation. - - @item -gnatu - @cindex @option{-gnatu} (@code{gcc}) - Print a list of units required by this compilation on @file{stdout}. - The listing includes all units on which the unit being compiled depends - either directly or indirectly. - - @item -pass-exit-codes - @cindex @code{-pass-exit-codes} (@code{gcc}) - If this switch is not used, the exit code returned by @code{gcc} when - compiling multiple files indicates whether all source files have - been successfully used to generate object files or not. - - When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended - exit status and allows an integrated development environment to better - react to a compilation failure. Those exit status are: - - @table @asis - @item 5 - There was an error in at least one source file. - @item 3 - At least one source file did not generate an object file. - @item 2 - The compiler died unexpectedly (internal error for example). - @item 0 - An object file has been generated for every source file. - @end table - @end table - - @node Debugging Control - @subsection Debugging Control - - @table @code - @cindex Debugging options - @item -gnatd@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - outputs desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Debug} unit in the compiler source - file @file{debug.adb}. - - @item -gnatG - @cindex @option{-gnatG} (@code{gcc}) - This switch causes the compiler to generate auxiliary output containing - a pseudo-source listing of the generated expanded code. Like most Ada - compilers, GNAT works by first transforming the high level Ada code into - lower level constructs. For example, tasking operations are transformed - into calls to the tasking run-time routines. A unique capability of GNAT - is to list this expanded code in a form very close to normal Ada source. - This is very useful in understanding the implications of various Ada - usage on the efficiency of the generated code. There are many cases in - Ada (e.g. the use of controlled types), where simple Ada statements can - generate a lot of run-time code. By using @option{-gnatG} you can identify - these cases, and consider whether it may be desirable to modify the coding - approach to improve efficiency. - - The format of the output is very similar to standard Ada source, and is - easily understood by an Ada programmer. The following special syntactic - additions correspond to low level features used in the generated code that - do not have any exact analogies in pure Ada source form. The following - is a partial list of these special constructions. See the specification - of package @code{Sprint} in file @file{sprint.ads} for a full list. - - @table @code - @item new @var{xxx} [storage_pool = @var{yyy}] - Shows the storage pool being used for an allocator. - - @item at end @var{procedure-name}; - Shows the finalization (cleanup) procedure for a scope. - - @item (if @var{expr} then @var{expr} else @var{expr}) - Conditional expression equivalent to the @code{x?y:z} construction in C. - - @item @var{target}^(@var{source}) - A conversion with floating-point truncation instead of rounding. - - @item @var{target}?(@var{source}) - A conversion that bypasses normal Ada semantic checking. In particular - enumeration types and fixed-point types are treated simply as integers. - - @item @var{target}?^(@var{source}) - Combines the above two cases. - - @item @var{x} #/ @var{y} - @itemx @var{x} #mod @var{y} - @itemx @var{x} #* @var{y} - @itemx @var{x} #rem @var{y} - A division or multiplication of fixed-point values which are treated as - integers without any kind of scaling. - - @item free @var{expr} [storage_pool = @var{xxx}] - Shows the storage pool associated with a @code{free} statement. - - @item freeze @var{typename} [@var{actions}] - Shows the point at which @var{typename} is frozen, with possible - associated actions to be performed at the freeze point. - - @item reference @var{itype} - Reference (and hence definition) to internal type @var{itype}. - - @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) - Intrinsic function call. - - @item @var{labelname} : label - Declaration of label @var{labelname}. - - @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr} - A multiple concatenation (same effect as @var{expr} & @var{expr} & - @var{expr}, but handled more efficiently). - - @item [constraint_error] - Raise the @code{Constraint_Error} exception. - - @item @var{expression}'reference - A pointer to the result of evaluating @var{expression}. - - @item @var{target-type}!(@var{source-expression}) - An unchecked conversion of @var{source-expression} to @var{target-type}. - - @item [@var{numerator}/@var{denominator}] - Used to represent internal real literals (that) have no exact - representation in base 2-16 (for example, the result of compile time - evaluation of the expression 1.0/27.0). - - @item -gnatD - @cindex @option{-gnatD} (@code{gcc}) - This switch is used in conjunction with @option{-gnatG} to cause the expanded - source, as described above to be written to files with names - @file{xxx.dg}, where @file{xxx} is the normal file name, - for example, if the source file name is @file{hello.adb}, - then a file @file{hello.adb.dg} will be written. - The debugging information generated - by the @code{gcc} @code{-g} switch will refer to the generated - @file{xxx.dg} file. This allows you to do source level debugging using - the generated code which is sometimes useful for complex code, for example - to find out exactly which part of a complex construction raised an - exception. This switch also suppress generation of cross-reference - information (see -gnatx). - - @item -gnatC - @cindex @option{-gnatE} (@code{gcc}) - In the generated debugging information, and also in the case of long external - names, the compiler uses a compression mechanism if the name is very long. - This compression method uses a checksum, and avoids trouble on some operating - systems which have difficulty with very long names. The @option{-gnatC} switch - forces this compression approach to be used on all external names and names - in the debugging information tables. This reduces the size of the generated - executable, at the expense of making the naming scheme more complex. The - compression only affects the qualification of the name. Thus a name in - the source: - - @smallexample - Very_Long_Package.Very_Long_Inner_Package.Var - @end smallexample - - @noindent - would normally appear in these tables as: - - @smallexample - very_long_package__very_long_inner_package__var - @end smallexample - - @noindent - but if the @option{-gnatC} switch is used, then the name appears as - - @smallexample - XCb7e0c705__var - @end smallexample - - @noindent - Here b7e0c705 is a compressed encoding of the qualification prefix. - The GNAT Ada aware version of GDB understands these encoded prefixes, so if this - debugger is used, the encoding is largely hidden from the user of the compiler. - - @end table - - @item -gnatR[0|1|2|3][s] - @cindex @option{-gnatR} (@code{gcc}) - This switch controls output from the compiler of a listing showing - representation information for declared types and objects. For - @option{-gnatR0}, no information is output (equivalent to omitting - the @option{-gnatR} switch). For @option{-gnatR1} (which is the default, - so @option{-gnatR} with no parameter has the same effect), size and alignment - information is listed for declared array and record types. For - @option{-gnatR2}, size and alignment information is listed for all - expression information for values that are computed at run time for - variant records. These symbolic expressions have a mostly obvious - format with #n being used to represent the value of the n'th - discriminant. See source files @file{repinfo.ads/adb} in the - @code{GNAT} sources for full detalis on the format of @option{-gnatR3} - output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then - the output is to a file with the name @file{file.rep} where - file is the name of the corresponding source file. - - @item -gnatx - @cindex @option{-gnatx} (@code{gcc}) - Normally the compiler generates full cross-referencing information in - the @file{ALI} file. This information is used by a number of tools, - including @code{gnatfind} and @code{gnatxref}. The -gnatx switch - suppresses this information. This saves some space and may slightly - speed up compilation, but means that these tools cannot be used. - @end table - - @node Units to Sources Mapping Files - @subsection Units to Sources Mapping Files - - @table @code - - @item -gnatem@var{path} - @cindex @option{-gnatem} (@code{gcc}) - A mapping file is a way to communicate to the compiler two mappings: - from unit names to file names (without any directory information) and from - file names to path names (with full directory information). These mappings - are used by the compiler to short-circuit the path search. - - A mapping file is a sequence of sets of three lines. In each set, - the first line is the unit name, in lower case, with "%s" appended for - specifications and "%b" appended for bodies; the second line is the file - name; and the third line is the path name. - - Example: - @smallexample - main%b - main.2.ada - /gnat/project1/sources/main.2.ada - @end smallexample - - When the switch @option{-gnatem} is specified, the compiler will create - in memory the two mappings from the specified file. If there is any problem - (non existent file, truncated file or duplicate entries), no mapping - will be created. - - Several @option{-gnatem} switches may be specified; however, only the last - one on the command line will be taken into account. - - When using a project file, @code{gnatmake} create a temporary mapping file - and communicates it to the compiler using this switch. - - @end table - - @node Search Paths and the Run-Time Library (RTL) - @section Search Paths and the Run-Time Library (RTL) - - @noindent - With the GNAT source-based library system, the compiler must be able to - find source files for units that are needed by the unit being compiled. - Search paths are used to guide this process. - - The compiler compiles one source file whose name must be given - explicitly on the command line. In other words, no searching is done - for this file. To find all other source files that are needed (the most - common being the specs of units), the compiler examines the following - directories, in the following order: - - @enumerate - @item - The directory containing the source file of the main unit being compiled - (the file name on the command line). - - @item - Each directory named by an @code{-I} switch given on the @code{gcc} - command line, in the order given. - - @item - @findex ADA_INCLUDE_PATH - Each of the directories listed in the value of the - @code{ADA_INCLUDE_PATH} environment variable. - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version). - @item - The content of the "ada_source_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) source files. - @ref{Installing an Ada Library} - @end enumerate - - @noindent - Specifying the switch @code{-I-} - inhibits the use of the directory - containing the source file named in the command line. You can still - have this directory on your search path, but in this case it must be - explicitly requested with a @code{-I} switch. - - Specifying the switch @code{-nostdinc} - inhibits the search of the default location for the GNAT Run Time - Library (RTL) source files. - - The compiler outputs its object files and ALI files in the current - working directory. - Caution: The object file can be redirected with the @code{-o} switch; - however, @code{gcc} and @code{gnat1} have not been coordinated on this - so the ALI file will not go to the right place. Therefore, you should - avoid using the @code{-o} switch. - - @findex System.IO - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT RTL, together with the simple @code{System.IO} - package used in the "Hello World" example. The sources for these units - are needed by the compiler and are kept together in one directory. Not - all of the bodies are needed, but all of the sources are kept together - anyway. In a normal installation, you need not specify these directory - names when compiling or binding. Either the environment variables or - the built-in defaults cause these files to be found. - - In addition to the language-defined hierarchies (System, Ada and - Interfaces), the GNAT distribution provides a fourth hierarchy, - consisting of child units of GNAT. This is a collection of generally - useful routines. See the GNAT Reference Manual for further details. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Order of Compilation Issues - @section Order of Compilation Issues - - @noindent - If, in our earlier example, there was a spec for the @code{hello} - procedure, it would be contained in the file @file{hello.ads}; yet this - file would not have to be explicitly compiled. This is the result of the - model we chose to implement library management. Some of the consequences - of this model are as follows: - - @itemize @bullet - @item - There is no point in compiling specs (except for package - specs with no bodies) because these are compiled as needed by clients. If - you attempt a useless compilation, you will receive an error message. - It is also useless to compile subunits because they are compiled as needed - by the parent. - - @item - There are no order of compilation requirements: performing a - compilation never obsoletes anything. The only way you can obsolete - something and require recompilations is to modify one of the - source files on which it depends. - - @item - There is no library as such, apart from the ALI files - (@pxref{The Ada Library Information Files}, for information on the format of these - files). For now we find it convenient to create separate ALI files, but - eventually the information therein may be incorporated into the object - file directly. - - @item - When you compile a unit, the source files for the specs of all units - that it @code{with}'s, all its subunits, and the bodies of any generics it - instantiates must be available (reachable by the search-paths mechanism - described above), or you will receive a fatal error message. - @end itemize - - @node Examples - @section Examples - - @noindent - The following are some typical Ada compilation command line examples: - - @table @code - @item $ gcc -c xyz.adb - Compile body in file @file{xyz.adb} with all default options. - - @item $ gcc -c -O2 -gnata xyz-def.adb - - Compile the child unit package in file @file{xyz-def.adb} with extensive - optimizations, and pragma @code{Assert}/@code{Debug} statements - enabled. - - @item $ gcc -c -gnatc abc-def.adb - Compile the subunit in file @file{abc-def.adb} in semantic-checking-only - mode. - @end table - - @node Binding Using gnatbind - @chapter Binding Using @code{gnatbind} - @findex gnatbind - - @menu - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - @end menu - - @noindent - This chapter describes the GNAT binder, @code{gnatbind}, which is used - to bind compiled GNAT objects. The @code{gnatbind} program performs - four separate functions: - - @enumerate - @item - Checks that a program is consistent, in accordance with the rules in - Chapter 10 of the Ada 95 Reference Manual. In particular, error - messages are generated if a program uses inconsistent versions of a - given unit. - - @item - Checks that an acceptable order of elaboration exists for the program - and issues an error message if it cannot find an order of elaboration - that satisfies the rules in Chapter 10 of the Ada 95 Language Manual. - - @item - Generates a main program incorporating the given elaboration order. - This program is a small Ada package (body and spec) that - must be subsequently compiled - using the GNAT compiler. The necessary compilation step is usually - performed automatically by @code{gnatlink}. The two most important - functions of this program - are to call the elaboration routines of units in an appropriate order - and to call the main program. - - @item - Determines the set of object files required by the given main program. - This information is output in the forms of comments in the generated program, - to be read by the @code{gnatlink} utility used to link the Ada application. - @end enumerate - - @node Running gnatbind - @section Running @code{gnatbind} - - @noindent - The form of the @code{gnatbind} command is - - @smallexample - $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}] - @end smallexample - - @noindent - where @var{mainprog}.adb is the Ada file containing the main program - unit body. If no switches are specified, @code{gnatbind} constructs an Ada - package in two files which names are - @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}. - For example, if given the - parameter @samp{hello.ali}, for a main program contained in file - @file{hello.adb}, the binder output files would be @file{b~hello.ads} - and @file{b~hello.adb}. - - When doing consistency checking, the binder takes into consideration - any source files it can locate. For example, if the binder determines - that the given main program requires the package @code{Pack}, whose - @file{.ali} - file is @file{pack.ali} and whose corresponding source spec file is - @file{pack.ads}, it attempts to locate the source file @file{pack.ads} - (using the same search path conventions as previously described for the - @code{gcc} command). If it can locate this source file, it checks that - the time stamps - or source checksums of the source and its references to in @file{ali} files - match. In other words, any @file{ali} files that mentions this spec must have - resulted from compiling this version of the source file (or in the case - where the source checksums match, a version close enough that the - difference does not matter). - - @cindex Source files, use by binder - The effect of this consistency checking, which includes source files, is - that the binder ensures that the program is consistent with the latest - version of the source files that can be located at bind time. Editing a - source file without compiling files that depend on the source file cause - error messages to be generated by the binder. - - For example, suppose you have a main program @file{hello.adb} and a - package @code{P}, from file @file{p.ads} and you perform the following - steps: - - @enumerate - @item - Enter @code{gcc -c hello.adb} to compile the main program. - - @item - Enter @code{gcc -c p.ads} to compile package @code{P}. - - @item - Edit file @file{p.ads}. - - @item - Enter @code{gnatbind hello}. - @end enumerate - - At this point, the file @file{p.ali} contains an out-of-date time stamp - because the file @file{p.ads} has been edited. The attempt at binding - fails, and the binder generates the following error messages: - - @smallexample - error: "hello.adb" must be recompiled ("p.ads" has been modified) - error: "p.ads" has been modified and must be recompiled - @end smallexample - - @noindent - Now both files must be recompiled as indicated, and then the bind can - succeed, generating a main program. You need not normally be concerned - with the contents of this file, but it is similar to the following which - is the binder file generated for a simple "hello world" program. - - @smallexample - @iftex - @leftskip=0cm - @end iftex - -- The package is called Ada_Main unless this name is actually used - -- as a unit name in the partition, in which case some other unique - -- name is used. - - with System; - package ada_main is - - Elab_Final_Code : Integer; - pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); - - -- The main program saves the parameters (argument count, - -- argument values, environment pointer) in global variables - -- for later access by other units including - -- Ada.Command_Line. - - gnat_argc : Integer; - gnat_argv : System.Address; - gnat_envp : System.Address; - - -- The actual variables are stored in a library routine. This - -- is useful for some shared library situations, where there - -- are problems if variables are not in the library. - - pragma Import (C, gnat_argc); - pragma Import (C, gnat_argv); - pragma Import (C, gnat_envp); - - -- The exit status is similarly an external location - - gnat_exit_status : Integer; - pragma Import (C, gnat_exit_status); - - GNAT_Version : constant String := - "GNAT Version: 3.15w (20010315)"; - pragma Export (C, GNAT_Version, "__gnat_version"); - - -- This is the generated adafinal routine that performs - -- finalization at the end of execution. In the case where - -- Ada is the main program, this main program makes a call - -- to adafinal at program termination. - - procedure adafinal; - pragma Export (C, adafinal, "adafinal"); - - -- This is the generated adainit routine that performs - -- initialization at the start of execution. In the case - -- where Ada is the main program, this main program makes - -- a call to adainit at program startup. - - procedure adainit; - pragma Export (C, adainit, "adainit"); - - -- This routine is called at the start of execution. It is - -- a dummy routine that is used by the debugger to breakpoint - -- at the start of execution. - - procedure Break_Start; - pragma Import (C, Break_Start, "__gnat_break_start"); - - -- This is the actual generated main program (it would be - -- suppressed if the no main program switch were used). As - -- required by standard system conventions, this program has - -- the external name main. - - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer; - pragma Export (C, main, "main"); - - -- The following set of constants give the version - -- identification values for every unit in the bound - -- partition. This identification is computed from all - -- dependent semantic units, and corresponds to the - -- string that would be returned by use of the - -- Body_Version or Version attributes. - - type Version_32 is mod 2 ** 32; - u00001 : constant Version_32 := 16#7880BEB3#; - u00002 : constant Version_32 := 16#0D24CBD0#; - u00003 : constant Version_32 := 16#3283DBEB#; - u00004 : constant Version_32 := 16#2359F9ED#; - u00005 : constant Version_32 := 16#664FB847#; - u00006 : constant Version_32 := 16#68E803DF#; - u00007 : constant Version_32 := 16#5572E604#; - u00008 : constant Version_32 := 16#46B173D8#; - u00009 : constant Version_32 := 16#156A40CF#; - u00010 : constant Version_32 := 16#033DABE0#; - u00011 : constant Version_32 := 16#6AB38FEA#; - u00012 : constant Version_32 := 16#22B6217D#; - u00013 : constant Version_32 := 16#68A22947#; - u00014 : constant Version_32 := 16#18CC4A56#; - u00015 : constant Version_32 := 16#08258E1B#; - u00016 : constant Version_32 := 16#367D5222#; - u00017 : constant Version_32 := 16#20C9ECA4#; - u00018 : constant Version_32 := 16#50D32CB6#; - u00019 : constant Version_32 := 16#39A8BB77#; - u00020 : constant Version_32 := 16#5CF8FA2B#; - u00021 : constant Version_32 := 16#2F1EB794#; - u00022 : constant Version_32 := 16#31AB6444#; - u00023 : constant Version_32 := 16#1574B6E9#; - u00024 : constant Version_32 := 16#5109C189#; - u00025 : constant Version_32 := 16#56D770CD#; - u00026 : constant Version_32 := 16#02F9DE3D#; - u00027 : constant Version_32 := 16#08AB6B2C#; - u00028 : constant Version_32 := 16#3FA37670#; - u00029 : constant Version_32 := 16#476457A0#; - u00030 : constant Version_32 := 16#731E1B6E#; - u00031 : constant Version_32 := 16#23C2E789#; - u00032 : constant Version_32 := 16#0F1BD6A1#; - u00033 : constant Version_32 := 16#7C25DE96#; - u00034 : constant Version_32 := 16#39ADFFA2#; - u00035 : constant Version_32 := 16#571DE3E7#; - u00036 : constant Version_32 := 16#5EB646AB#; - u00037 : constant Version_32 := 16#4249379B#; - u00038 : constant Version_32 := 16#0357E00A#; - u00039 : constant Version_32 := 16#3784FB72#; - u00040 : constant Version_32 := 16#2E723019#; - u00041 : constant Version_32 := 16#623358EA#; - u00042 : constant Version_32 := 16#107F9465#; - u00043 : constant Version_32 := 16#6843F68A#; - u00044 : constant Version_32 := 16#63305874#; - u00045 : constant Version_32 := 16#31E56CE1#; - u00046 : constant Version_32 := 16#02917970#; - u00047 : constant Version_32 := 16#6CCBA70E#; - u00048 : constant Version_32 := 16#41CD4204#; - u00049 : constant Version_32 := 16#572E3F58#; - u00050 : constant Version_32 := 16#20729FF5#; - u00051 : constant Version_32 := 16#1D4F93E8#; - u00052 : constant Version_32 := 16#30B2EC3D#; - u00053 : constant Version_32 := 16#34054F96#; - u00054 : constant Version_32 := 16#5A199860#; - u00055 : constant Version_32 := 16#0E7F912B#; - u00056 : constant Version_32 := 16#5760634A#; - u00057 : constant Version_32 := 16#5D851835#; - - -- The following Export pragmas export the version numbers - -- with symbolic names ending in B (for body) or S - -- (for spec) so that they can be located in a link. The - -- information provided here is sufficient to track down - -- the exact versions of units used in a given build. - - pragma Export (C, u00001, "helloB"); - pragma Export (C, u00002, "system__standard_libraryB"); - pragma Export (C, u00003, "system__standard_libraryS"); - pragma Export (C, u00004, "adaS"); - pragma Export (C, u00005, "ada__text_ioB"); - pragma Export (C, u00006, "ada__text_ioS"); - pragma Export (C, u00007, "ada__exceptionsB"); - pragma Export (C, u00008, "ada__exceptionsS"); - pragma Export (C, u00009, "gnatS"); - pragma Export (C, u00010, "gnat__heap_sort_aB"); - pragma Export (C, u00011, "gnat__heap_sort_aS"); - pragma Export (C, u00012, "systemS"); - pragma Export (C, u00013, "system__exception_tableB"); - pragma Export (C, u00014, "system__exception_tableS"); - pragma Export (C, u00015, "gnat__htableB"); - pragma Export (C, u00016, "gnat__htableS"); - pragma Export (C, u00017, "system__exceptionsS"); - pragma Export (C, u00018, "system__machine_state_operationsB"); - pragma Export (C, u00019, "system__machine_state_operationsS"); - pragma Export (C, u00020, "system__machine_codeS"); - pragma Export (C, u00021, "system__storage_elementsB"); - pragma Export (C, u00022, "system__storage_elementsS"); - pragma Export (C, u00023, "system__secondary_stackB"); - pragma Export (C, u00024, "system__secondary_stackS"); - pragma Export (C, u00025, "system__parametersB"); - pragma Export (C, u00026, "system__parametersS"); - pragma Export (C, u00027, "system__soft_linksB"); - pragma Export (C, u00028, "system__soft_linksS"); - pragma Export (C, u00029, "system__stack_checkingB"); - pragma Export (C, u00030, "system__stack_checkingS"); - pragma Export (C, u00031, "system__tracebackB"); - pragma Export (C, u00032, "system__tracebackS"); - pragma Export (C, u00033, "ada__streamsS"); - pragma Export (C, u00034, "ada__tagsB"); - pragma Export (C, u00035, "ada__tagsS"); - pragma Export (C, u00036, "system__string_opsB"); - pragma Export (C, u00037, "system__string_opsS"); - pragma Export (C, u00038, "interfacesS"); - pragma Export (C, u00039, "interfaces__c_streamsB"); - pragma Export (C, u00040, "interfaces__c_streamsS"); - pragma Export (C, u00041, "system__file_ioB"); - pragma Export (C, u00042, "system__file_ioS"); - pragma Export (C, u00043, "ada__finalizationB"); - pragma Export (C, u00044, "ada__finalizationS"); - pragma Export (C, u00045, "system__finalization_rootB"); - pragma Export (C, u00046, "system__finalization_rootS"); - pragma Export (C, u00047, "system__finalization_implementationB"); - pragma Export (C, u00048, "system__finalization_implementationS"); - pragma Export (C, u00049, "system__string_ops_concat_3B"); - pragma Export (C, u00050, "system__string_ops_concat_3S"); - pragma Export (C, u00051, "system__stream_attributesB"); - pragma Export (C, u00052, "system__stream_attributesS"); - pragma Export (C, u00053, "ada__io_exceptionsS"); - pragma Export (C, u00054, "system__unsigned_typesS"); - pragma Export (C, u00055, "system__file_control_blockS"); - pragma Export (C, u00056, "ada__finalization__list_controllerB"); - pragma Export (C, u00057, "ada__finalization__list_controllerS"); - - -- BEGIN ELABORATION ORDER - -- ada (spec) - -- gnat (spec) - -- gnat.heap_sort_a (spec) - -- gnat.heap_sort_a (body) - -- gnat.htable (spec) - -- gnat.htable (body) - -- interfaces (spec) - -- system (spec) - -- system.machine_code (spec) - -- system.parameters (spec) - -- system.parameters (body) - -- interfaces.c_streams (spec) - -- interfaces.c_streams (body) - -- system.standard_library (spec) - -- ada.exceptions (spec) - -- system.exception_table (spec) - -- system.exception_table (body) - -- ada.io_exceptions (spec) - -- system.exceptions (spec) - -- system.storage_elements (spec) - -- system.storage_elements (body) - -- system.machine_state_operations (spec) - -- system.machine_state_operations (body) - -- system.secondary_stack (spec) - -- system.stack_checking (spec) - -- system.soft_links (spec) - -- system.soft_links (body) - -- system.stack_checking (body) - -- system.secondary_stack (body) - -- system.standard_library (body) - -- system.string_ops (spec) - -- system.string_ops (body) - -- ada.tags (spec) - -- ada.tags (body) - -- ada.streams (spec) - -- system.finalization_root (spec) - -- system.finalization_root (body) - -- system.string_ops_concat_3 (spec) - -- system.string_ops_concat_3 (body) - -- system.traceback (spec) - -- system.traceback (body) - -- ada.exceptions (body) - -- system.unsigned_types (spec) - -- system.stream_attributes (spec) - -- system.stream_attributes (body) - -- system.finalization_implementation (spec) - -- system.finalization_implementation (body) - -- ada.finalization (spec) - -- ada.finalization (body) - -- ada.finalization.list_controller (spec) - -- ada.finalization.list_controller (body) - -- system.file_control_block (spec) - -- system.file_io (spec) - -- system.file_io (body) - -- ada.text_io (spec) - -- ada.text_io (body) - -- hello (body) - -- END ELABORATION ORDER - - end ada_main; - - -- The following source file name pragmas allow the generated file - -- names to be unique for different main programs. They are needed - -- since the package name will always be Ada_Main. - - pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads"); - pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb"); - - -- Generated package body for Ada_Main starts here - - package body ada_main is - - -- The actual finalization is performed by calling the - -- library routine in System.Standard_Library.Adafinal - - procedure Do_Finalize; - pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); - - ------------- - -- adainit -- - ------------- - - @findex adainit - procedure adainit is - - -- These booleans are set to True once the associated unit has - -- been elaborated. It is also used to avoid elaborating the - -- same unit twice. - - E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E"); - E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E"); - E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E"); - E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E"); - E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E"); - E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E"); - E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E"); - E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E"); - E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E"); - E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E"); - E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E"); - E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E"); - E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E"); - E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E"); - E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E"); - E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E"); - E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E"); - - -- Set_Globals is a library routine that stores away the - -- value of the indicated set of global values in global - -- variables within the library. - - procedure Set_Globals - (Main_Priority : Integer; - Time_Slice_Value : Integer; - WC_Encoding : Character; - Locking_Policy : Character; - Queuing_Policy : Character; - Task_Dispatching_Policy : Character; - Adafinal : System.Address; - Unreserve_All_Interrupts : Integer; - Exception_Tracebacks : Integer); - @findex __gnat_set_globals - pragma Import (C, Set_Globals, "__gnat_set_globals"); - - -- SDP_Table_Build is a library routine used to build the - -- exception tables. See unit Ada.Exceptions in files - -- a-except.ads/adb for full details of how zero cost - -- exception handling works. This procedure, the call to - -- it, and the two following tables are all omitted if the - -- build is in longjmp/setjump exception mode. - - @findex SDP_Table_Build - @findex Zero Cost Exceptions - procedure SDP_Table_Build - (SDP_Addresses : System.Address; - SDP_Count : Natural; - Elab_Addresses : System.Address; - Elab_Addr_Count : Natural); - pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); - - -- Table of Unit_Exception_Table addresses. Used for zero - -- cost exception handling to build the top level table. - - ST : aliased constant array (1 .. 23) of System.Address := ( - Hello'UET_Address, - Ada.Text_Io'UET_Address, - Ada.Exceptions'UET_Address, - Gnat.Heap_Sort_A'UET_Address, - System.Exception_Table'UET_Address, - System.Machine_State_Operations'UET_Address, - System.Secondary_Stack'UET_Address, - System.Parameters'UET_Address, - System.Soft_Links'UET_Address, - System.Stack_Checking'UET_Address, - System.Traceback'UET_Address, - Ada.Streams'UET_Address, - Ada.Tags'UET_Address, - System.String_Ops'UET_Address, - Interfaces.C_Streams'UET_Address, - System.File_Io'UET_Address, - Ada.Finalization'UET_Address, - System.Finalization_Root'UET_Address, - System.Finalization_Implementation'UET_Address, - System.String_Ops_Concat_3'UET_Address, - System.Stream_Attributes'UET_Address, - System.File_Control_Block'UET_Address, - Ada.Finalization.List_Controller'UET_Address); - - -- Table of addresses of elaboration routines. Used for - -- zero cost exception handling to make sure these - -- addresses are included in the top level procedure - -- address table. - - EA : aliased constant array (1 .. 23) of System.Address := ( - adainit'Code_Address, - Do_Finalize'Code_Address, - Ada.Exceptions'Elab_Spec'Address, - System.Exceptions'Elab_Spec'Address, - Interfaces.C_Streams'Elab_Spec'Address, - System.Exception_Table'Elab_Body'Address, - Ada.Io_Exceptions'Elab_Spec'Address, - System.Stack_Checking'Elab_Spec'Address, - System.Soft_Links'Elab_Body'Address, - System.Secondary_Stack'Elab_Body'Address, - Ada.Tags'Elab_Spec'Address, - Ada.Tags'Elab_Body'Address, - Ada.Streams'Elab_Spec'Address, - System.Finalization_Root'Elab_Spec'Address, - Ada.Exceptions'Elab_Body'Address, - System.Finalization_Implementation'Elab_Spec'Address, - System.Finalization_Implementation'Elab_Body'Address, - Ada.Finalization'Elab_Spec'Address, - Ada.Finalization.List_Controller'Elab_Spec'Address, - System.File_Control_Block'Elab_Spec'Address, - System.File_Io'Elab_Body'Address, - Ada.Text_Io'Elab_Spec'Address, - Ada.Text_Io'Elab_Body'Address); - - -- Start of processing for adainit - - begin - - -- Call SDP_Table_Build to build the top level procedure - -- table for zero cost exception handling (omitted in - -- longjmp/setjump mode). - - SDP_Table_Build (ST'Address, 23, EA'Address, 23); - - -- Call Set_Globals to record various information for - -- this partition. The values are derived by the binder - -- from information stored in the ali files by the compiler. - - @findex __gnat_set_globals - Set_Globals - (Main_Priority => -1, - -- Priority of main program, -1 if no pragma Priority used - - Time_Slice_Value => -1, - -- Time slice from Time_Slice pragma, -1 if none used - - WC_Encoding => 'b', - -- Wide_Character encoding used, default is brackets - - Locking_Policy => ' ', - -- Locking_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Queuing_Policy => ' ', - -- Queuing_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Task_Dispatching_Policy => ' ', - -- Task_Dispatching_Policy used, default of space means - -- not specified, otherwise first character of the - -- policy name. - - Adafinal => System.Null_Address, - -- Address of Adafinal routine, not used anymore - - Unreserve_All_Interrupts => 0, - -- Set true if pragma Unreserve_All_Interrupts was used - - Exception_Tracebacks => 0); - -- Indicates if exception tracebacks are enabled - - Elab_Final_Code := 1; - - -- Now we have the elaboration calls for all units in the partition. - -- The Elab_Spec and Elab_Body attributes generate references to the - -- implicit elaboration procedures generated by the compiler for - -- each unit that requires elaboration. - - if not E040 then - Interfaces.C_Streams'Elab_Spec; - end if; - E040 := True; - if not E008 then - Ada.Exceptions'Elab_Spec; - end if; - if not E014 then - System.Exception_Table'Elab_Body; - E014 := True; - end if; - if not E053 then - Ada.Io_Exceptions'Elab_Spec; - E053 := True; - end if; - if not E017 then - System.Exceptions'Elab_Spec; - E017 := True; - end if; - if not E030 then - System.Stack_Checking'Elab_Spec; - end if; - if not E028 then - System.Soft_Links'Elab_Body; - E028 := True; - end if; - E030 := True; - if not E024 then - System.Secondary_Stack'Elab_Body; - E024 := True; - end if; - if not E035 then - Ada.Tags'Elab_Spec; - end if; - if not E035 then - Ada.Tags'Elab_Body; - E035 := True; - end if; - if not E033 then - Ada.Streams'Elab_Spec; - E033 := True; - end if; - if not E046 then - System.Finalization_Root'Elab_Spec; - end if; - E046 := True; - if not E008 then - Ada.Exceptions'Elab_Body; - E008 := True; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Spec; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Body; - E048 := True; - end if; - if not E044 then - Ada.Finalization'Elab_Spec; - end if; - E044 := True; - if not E057 then - Ada.Finalization.List_Controller'Elab_Spec; - end if; - E057 := True; - if not E055 then - System.File_Control_Block'Elab_Spec; - E055 := True; - end if; - if not E042 then - System.File_Io'Elab_Body; - E042 := True; - end if; - if not E006 then - Ada.Text_Io'Elab_Spec; - end if; - if not E006 then - Ada.Text_Io'Elab_Body; - E006 := True; - end if; - - Elab_Final_Code := 0; - end adainit; - - -------------- - -- adafinal -- - -------------- - - @findex adafinal - procedure adafinal is - begin - Do_Finalize; - end adafinal; - - ---------- - -- main -- - ---------- - - -- main is actually a function, as in the ANSI C standard, - -- defined to return the exit status. The three parameters - -- are the argument count, argument values and environment - -- pointer. - - @findex Main Program - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer - is - -- The initialize routine performs low level system - -- initialization using a standard library routine which - -- sets up signal handling and performs any other - -- required setup. The routine can be found in file - -- a-init.c. - - @findex __gnat_initialize - procedure initialize; - pragma Import (C, initialize, "__gnat_initialize"); - - -- The finalize routine performs low level system - -- finalization using a standard library routine. The - -- routine is found in file a-final.c and in the standard - -- distribution is a dummy routine that does nothing, so - -- really this is a hook for special user finalization. - - @findex __gnat_finalize - procedure finalize; - pragma Import (C, finalize, "__gnat_finalize"); - - -- We get to the main program of the partition by using - -- pragma Import because if we try to with the unit and - -- call it Ada style, then not only do we waste time - -- recompiling it, but also, we don't really know the right - -- switches (e.g. identifier character set) to be used - -- to compile it. - - procedure Ada_Main_Program; - pragma Import (Ada, Ada_Main_Program, "_ada_hello"); - - -- Start of processing for main - - begin - -- Save global variables - - gnat_argc := argc; - gnat_argv := argv; - gnat_envp := envp; - - -- Call low level system initialization - - Initialize; - - -- Call our generated Ada initialization routine - - adainit; - - -- This is the point at which we want the debugger to get - -- control - - Break_Start; - - -- Now we call the main program of the partition - - Ada_Main_Program; - - -- Perform Ada finalization - - adafinal; - - -- Perform low level system finalization - - Finalize; - - -- Return the proper exit status - return (gnat_exit_status); - end; - - -- This section is entirely comments, so it has no effect on the - -- compilation of the Ada_Main package. It provides the list of - -- object files and linker options, as well as some standard - -- libraries needed for the link. The gnatlink utility parses - -- this b~hello.adb file to read these comment lines to generate - -- the appropriate command line arguments for the call to the - -- system linker. The BEGIN/END lines are used for sentinels for - -- this parsing operation. - - -- The exact file names will of course depend on the environment, - -- host/target and location of files on the host system. - - @findex Object file list - -- BEGIN Object file/option list - -- ./hello.o - -- -L./ - -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ - -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a - -- END Object file/option list - - end ada_main; - - @end smallexample - - @noindent - The Ada code in the above example is exactly what is generated by the - binder. We have added comments to more clearly indicate the function - of each part of the generated @code{Ada_Main} package. - - The code is standard Ada in all respects, and can be processed by any - tools that handle Ada. In particular, it is possible to use the debugger - in Ada mode to debug the generated Ada_Main package. For example, suppose - that for reasons that you do not understand, your program is blowing up - during elaboration of the body of @code{Ada.Text_IO}. To chase this bug - down, you can place a breakpoint on the call: - - @smallexample - Ada.Text_Io'Elab_Body; - @end smallexample - - @noindent - and trace the elaboration routine for this package to find out where - the problem might be (more usually of course you would be debugging - elaboration code in your own application). - - @node Generating the Binder Program in C - @section Generating the Binder Program in C - @noindent - In most normal usage, the default mode of @code{gnatbind} which is to - generate the main package in Ada, as described in the previous section. - In particular, this means that any Ada programmer can read and understand - the generated main program. It can also be debugged just like any other - Ada code provided the @code{-g} switch is used for @code{gnatbind} - and @code{gnatlink}. - - However for some purposes it may be convenient to generate the main - program in C rather than Ada. This may for example be helpful when you - are generating a mixed language program with the main program in C. The - GNAT compiler itself is an example. The use of the @code{-C} switch - for both @code{gnatbind} and @code{gnatlink} will cause the program to - be generated in C (and compiled using the gnu C compiler). The - following shows the C code generated for the same "Hello World" - program: - - @smallexample - - #ifdef __STDC__ - #define PARAMS(paramlist) paramlist - #else - #define PARAMS(paramlist) () - #endif - - extern void __gnat_set_globals - PARAMS ((int, int, int, int, int, int, - void (*) PARAMS ((void)), int, int)); - extern void adafinal PARAMS ((void)); - extern void adainit PARAMS ((void)); - extern void system__standard_library__adafinal PARAMS ((void)); - extern int main PARAMS ((int, char **, char **)); - extern void exit PARAMS ((int)); - extern void __gnat_break_start PARAMS ((void)); - extern void _ada_hello PARAMS ((void)); - extern void __gnat_initialize PARAMS ((void)); - extern void __gnat_finalize PARAMS ((void)); - - extern void ada__exceptions___elabs PARAMS ((void)); - extern void system__exceptions___elabs PARAMS ((void)); - extern void interfaces__c_streams___elabs PARAMS ((void)); - extern void system__exception_table___elabb PARAMS ((void)); - extern void ada__io_exceptions___elabs PARAMS ((void)); - extern void system__stack_checking___elabs PARAMS ((void)); - extern void system__soft_links___elabb PARAMS ((void)); - extern void system__secondary_stack___elabb PARAMS ((void)); - extern void ada__tags___elabs PARAMS ((void)); - extern void ada__tags___elabb PARAMS ((void)); - extern void ada__streams___elabs PARAMS ((void)); - extern void system__finalization_root___elabs PARAMS ((void)); - extern void ada__exceptions___elabb PARAMS ((void)); - extern void system__finalization_implementation___elabs PARAMS ((void)); - extern void system__finalization_implementation___elabb PARAMS ((void)); - extern void ada__finalization___elabs PARAMS ((void)); - extern void ada__finalization__list_controller___elabs PARAMS ((void)); - extern void system__file_control_block___elabs PARAMS ((void)); - extern void system__file_io___elabb PARAMS ((void)); - extern void ada__text_io___elabs PARAMS ((void)); - extern void ada__text_io___elabb PARAMS ((void)); - - extern int __gnat_inside_elab_final_code; - - extern int gnat_argc; - extern char **gnat_argv; - extern char **gnat_envp; - extern int gnat_exit_status; - - char __gnat_version[] = "GNAT Version: 3.15w (20010315)"; - void adafinal () @{ - system__standard_library__adafinal (); - @} - - void adainit () - @{ - extern char ada__exceptions_E; - extern char system__exceptions_E; - extern char interfaces__c_streams_E; - extern char system__exception_table_E; - extern char ada__io_exceptions_E; - extern char system__secondary_stack_E; - extern char system__stack_checking_E; - extern char system__soft_links_E; - extern char ada__tags_E; - extern char ada__streams_E; - extern char system__finalization_root_E; - extern char system__finalization_implementation_E; - extern char ada__finalization_E; - extern char ada__finalization__list_controller_E; - extern char system__file_control_block_E; - extern char system__file_io_E; - extern char ada__text_io_E; - - extern void *__gnat_hello__SDP; - extern void *__gnat_ada__text_io__SDP; - extern void *__gnat_ada__exceptions__SDP; - extern void *__gnat_gnat__heap_sort_a__SDP; - extern void *__gnat_system__exception_table__SDP; - extern void *__gnat_system__machine_state_operations__SDP; - extern void *__gnat_system__secondary_stack__SDP; - extern void *__gnat_system__parameters__SDP; - extern void *__gnat_system__soft_links__SDP; - extern void *__gnat_system__stack_checking__SDP; - extern void *__gnat_system__traceback__SDP; - extern void *__gnat_ada__streams__SDP; - extern void *__gnat_ada__tags__SDP; - extern void *__gnat_system__string_ops__SDP; - extern void *__gnat_interfaces__c_streams__SDP; - extern void *__gnat_system__file_io__SDP; - extern void *__gnat_ada__finalization__SDP; - extern void *__gnat_system__finalization_root__SDP; - extern void *__gnat_system__finalization_implementation__SDP; - extern void *__gnat_system__string_ops_concat_3__SDP; - extern void *__gnat_system__stream_attributes__SDP; - extern void *__gnat_system__file_control_block__SDP; - extern void *__gnat_ada__finalization__list_controller__SDP; - - void **st[23] = @{ - &__gnat_hello__SDP, - &__gnat_ada__text_io__SDP, - &__gnat_ada__exceptions__SDP, - &__gnat_gnat__heap_sort_a__SDP, - &__gnat_system__exception_table__SDP, - &__gnat_system__machine_state_operations__SDP, - &__gnat_system__secondary_stack__SDP, - &__gnat_system__parameters__SDP, - &__gnat_system__soft_links__SDP, - &__gnat_system__stack_checking__SDP, - &__gnat_system__traceback__SDP, - &__gnat_ada__streams__SDP, - &__gnat_ada__tags__SDP, - &__gnat_system__string_ops__SDP, - &__gnat_interfaces__c_streams__SDP, - &__gnat_system__file_io__SDP, - &__gnat_ada__finalization__SDP, - &__gnat_system__finalization_root__SDP, - &__gnat_system__finalization_implementation__SDP, - &__gnat_system__string_ops_concat_3__SDP, - &__gnat_system__stream_attributes__SDP, - &__gnat_system__file_control_block__SDP, - &__gnat_ada__finalization__list_controller__SDP@}; - - extern void ada__exceptions___elabs (); - extern void system__exceptions___elabs (); - extern void interfaces__c_streams___elabs (); - extern void system__exception_table___elabb (); - extern void ada__io_exceptions___elabs (); - extern void system__stack_checking___elabs (); - extern void system__soft_links___elabb (); - extern void system__secondary_stack___elabb (); - extern void ada__tags___elabs (); - extern void ada__tags___elabb (); - extern void ada__streams___elabs (); - extern void system__finalization_root___elabs (); - extern void ada__exceptions___elabb (); - extern void system__finalization_implementation___elabs (); - extern void system__finalization_implementation___elabb (); - extern void ada__finalization___elabs (); - extern void ada__finalization__list_controller___elabs (); - extern void system__file_control_block___elabs (); - extern void system__file_io___elabb (); - extern void ada__text_io___elabs (); - extern void ada__text_io___elabb (); - - void (*ea[23]) () = @{ - adainit, - system__standard_library__adafinal, - ada__exceptions___elabs, - system__exceptions___elabs, - interfaces__c_streams___elabs, - system__exception_table___elabb, - ada__io_exceptions___elabs, - system__stack_checking___elabs, - system__soft_links___elabb, - system__secondary_stack___elabb, - ada__tags___elabs, - ada__tags___elabb, - ada__streams___elabs, - system__finalization_root___elabs, - ada__exceptions___elabb, - system__finalization_implementation___elabs, - system__finalization_implementation___elabb, - ada__finalization___elabs, - ada__finalization__list_controller___elabs, - system__file_control_block___elabs, - system__file_io___elabb, - ada__text_io___elabs, - ada__text_io___elabb@}; - - __gnat_SDP_Table_Build (&st, 23, ea, 23); - __gnat_set_globals ( - -1, /* Main_Priority */ - -1, /* Time_Slice_Value */ - 'b', /* WC_Encoding */ - ' ', /* Locking_Policy */ - ' ', /* Queuing_Policy */ - ' ', /* Tasking_Dispatching_Policy */ - 0, /* Finalization routine address, not used anymore */ - 0, /* Unreserve_All_Interrupts */ - 0); /* Exception_Tracebacks */ - - __gnat_inside_elab_final_code = 1; - - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabs (); - @} - if (system__exceptions_E == 0) @{ - system__exceptions___elabs (); - system__exceptions_E++; - @} - if (interfaces__c_streams_E == 0) @{ - interfaces__c_streams___elabs (); - @} - interfaces__c_streams_E = 1; - if (system__exception_table_E == 0) @{ - system__exception_table___elabb (); - system__exception_table_E++; - @} - if (ada__io_exceptions_E == 0) @{ - ada__io_exceptions___elabs (); - ada__io_exceptions_E++; - @} - if (system__stack_checking_E == 0) @{ - system__stack_checking___elabs (); - @} - if (system__soft_links_E == 0) @{ - system__soft_links___elabb (); - system__soft_links_E++; - @} - system__stack_checking_E = 1; - if (system__secondary_stack_E == 0) @{ - system__secondary_stack___elabb (); - system__secondary_stack_E++; - @} - if (ada__tags_E == 0) @{ - ada__tags___elabs (); - @} - if (ada__tags_E == 0) @{ - ada__tags___elabb (); - ada__tags_E++; - @} - if (ada__streams_E == 0) @{ - ada__streams___elabs (); - ada__streams_E++; - @} - if (system__finalization_root_E == 0) @{ - system__finalization_root___elabs (); - @} - system__finalization_root_E = 1; - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabb (); - ada__exceptions_E++; - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabs (); - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabb (); - system__finalization_implementation_E++; - @} - if (ada__finalization_E == 0) @{ - ada__finalization___elabs (); - @} - ada__finalization_E = 1; - if (ada__finalization__list_controller_E == 0) @{ - ada__finalization__list_controller___elabs (); - @} - ada__finalization__list_controller_E = 1; - if (system__file_control_block_E == 0) @{ - system__file_control_block___elabs (); - system__file_control_block_E++; - @} - if (system__file_io_E == 0) @{ - system__file_io___elabb (); - system__file_io_E++; - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabs (); - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabb (); - ada__text_io_E++; - @} - - __gnat_inside_elab_final_code = 0; - @} - int main (argc, argv, envp) - int argc; - char **argv; - char **envp; - @{ - gnat_argc = argc; - gnat_argv = argv; - gnat_envp = envp; - - __gnat_initialize (); - adainit (); - __gnat_break_start (); - - _ada_hello (); - - system__standard_library__adafinal (); - __gnat_finalize (); - exit (gnat_exit_status); - @} - unsigned helloB = 0x7880BEB3; - unsigned system__standard_libraryB = 0x0D24CBD0; - unsigned system__standard_libraryS = 0x3283DBEB; - unsigned adaS = 0x2359F9ED; - unsigned ada__text_ioB = 0x47C85FC4; - unsigned ada__text_ioS = 0x496FE45C; - unsigned ada__exceptionsB = 0x74F50187; - unsigned ada__exceptionsS = 0x6736945B; - unsigned gnatS = 0x156A40CF; - unsigned gnat__heap_sort_aB = 0x033DABE0; - unsigned gnat__heap_sort_aS = 0x6AB38FEA; - unsigned systemS = 0x0331C6FE; - unsigned system__exceptionsS = 0x20C9ECA4; - unsigned system__exception_tableB = 0x68A22947; - unsigned system__exception_tableS = 0x394BADD5; - unsigned gnat__htableB = 0x08258E1B; - unsigned gnat__htableS = 0x367D5222; - unsigned system__machine_state_operationsB = 0x4F3B7492; - unsigned system__machine_state_operationsS = 0x182F5CF4; - unsigned system__storage_elementsB = 0x2F1EB794; - unsigned system__storage_elementsS = 0x102C83C7; - unsigned system__secondary_stackB = 0x1574B6E9; - unsigned system__secondary_stackS = 0x708E260A; - unsigned system__parametersB = 0x56D770CD; - unsigned system__parametersS = 0x237E39BE; - unsigned system__soft_linksB = 0x08AB6B2C; - unsigned system__soft_linksS = 0x1E2491F3; - unsigned system__stack_checkingB = 0x476457A0; - unsigned system__stack_checkingS = 0x5299FCED; - unsigned system__tracebackB = 0x2971EBDE; - unsigned system__tracebackS = 0x2E9C3122; - unsigned ada__streamsS = 0x7C25DE96; - unsigned ada__tagsB = 0x39ADFFA2; - unsigned ada__tagsS = 0x769A0464; - unsigned system__string_opsB = 0x5EB646AB; - unsigned system__string_opsS = 0x63CED018; - unsigned interfacesS = 0x0357E00A; - unsigned interfaces__c_streamsB = 0x3784FB72; - unsigned interfaces__c_streamsS = 0x2E723019; - unsigned system__file_ioB = 0x623358EA; - unsigned system__file_ioS = 0x31F873E6; - unsigned ada__finalizationB = 0x6843F68A; - unsigned ada__finalizationS = 0x63305874; - unsigned system__finalization_rootB = 0x31E56CE1; - unsigned system__finalization_rootS = 0x23169EF3; - unsigned system__finalization_implementationB = 0x6CCBA70E; - unsigned system__finalization_implementationS = 0x604AA587; - unsigned system__string_ops_concat_3B = 0x572E3F58; - unsigned system__string_ops_concat_3S = 0x01F57876; - unsigned system__stream_attributesB = 0x1D4F93E8; - unsigned system__stream_attributesS = 0x30B2EC3D; - unsigned ada__io_exceptionsS = 0x34054F96; - unsigned system__unsigned_typesS = 0x7B9E7FE3; - unsigned system__file_control_blockS = 0x2FF876A8; - unsigned ada__finalization__list_controllerB = 0x5760634A; - unsigned ada__finalization__list_controllerS = 0x5D851835; - - /* BEGIN ELABORATION ORDER - ada (spec) - gnat (spec) - gnat.heap_sort_a (spec) - gnat.htable (spec) - gnat.htable (body) - interfaces (spec) - system (spec) - system.parameters (spec) - system.standard_library (spec) - ada.exceptions (spec) - system.exceptions (spec) - system.parameters (body) - gnat.heap_sort_a (body) - interfaces.c_streams (spec) - interfaces.c_streams (body) - system.exception_table (spec) - system.exception_table (body) - ada.io_exceptions (spec) - system.storage_elements (spec) - system.storage_elements (body) - system.machine_state_operations (spec) - system.machine_state_operations (body) - system.secondary_stack (spec) - system.stack_checking (spec) - system.soft_links (spec) - system.soft_links (body) - system.stack_checking (body) - system.secondary_stack (body) - system.standard_library (body) - system.string_ops (spec) - system.string_ops (body) - ada.tags (spec) - ada.tags (body) - ada.streams (spec) - system.finalization_root (spec) - system.finalization_root (body) - system.string_ops_concat_3 (spec) - system.string_ops_concat_3 (body) - system.traceback (spec) - system.traceback (body) - ada.exceptions (body) - system.unsigned_types (spec) - system.stream_attributes (spec) - system.stream_attributes (body) - system.finalization_implementation (spec) - system.finalization_implementation (body) - ada.finalization (spec) - ada.finalization (body) - ada.finalization.list_controller (spec) - ada.finalization.list_controller (body) - system.file_control_block (spec) - system.file_io (spec) - system.file_io (body) - ada.text_io (spec) - ada.text_io (body) - hello (body) - END ELABORATION ORDER */ - - /* BEGIN Object file/option list - ./hello.o - -L./ - -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/ - /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a - -lexc - END Object file/option list */ - - @end smallexample - - @noindent - Here again, the C code is exactly what is generated by the binder. The - functions of the various parts of this code correspond in an obvious - manner with the commented Ada code shown in the example in the previous - section. - - @node Consistency-Checking Modes - @section Consistency-Checking Modes - - @noindent - As described in the previous section, by default @code{gnatbind} checks - that object files are consistent with one another and are consistent - with any source files it can locate. The following switches control binder - access to sources. - - @table @code - @item -s - @cindex @code{-s} (@code{gnatbind}) - Require source files to be present. In this mode, the binder must be - able to locate all source files that are referenced, in order to check - their consistency. In normal mode, if a source file cannot be located it - is simply ignored. If you specify this switch, a missing source - file is an error. - - @item -x - @cindex @code{-x} (@code{gnatbind}) - Exclude source files. In this mode, the binder only checks that ALI - files are consistent with one another. Source files are not accessed. - The binder runs faster in this mode, and there is still a guarantee that - the resulting program is self-consistent. - If a source file has been edited since it was last compiled, and you - specify this switch, the binder will not detect that the object - file is out of date with respect to the source file. Note that this is the - mode that is automatically used by @code{gnatmake} because in this - case the checking against sources has already been performed by - @code{gnatmake} in the course of compilation (i.e. before binding). - - @end table - - @node Binder Error Message Control - @section Binder Error Message Control - - @noindent - The following switches provide control over the generation of error - messages from the binder: - - @table @code - @item -v - @cindex @code{-v} (@code{gnatbind}) - Verbose mode. In the normal mode, brief error messages are generated to - @file{stderr}. If this switch is present, a header is written - to @file{stdout} and any error messages are directed to @file{stdout}. - All that is written to @file{stderr} is a brief summary message. - - @item -b - @cindex @code{-b} (@code{gnatbind}) - Generate brief error messages to @file{stderr} even if verbose mode is - specified. This is relevant only when used with the - @code{-v} switch. - - @item -m@var{n} - @cindex @code{-m} (@code{gnatbind}) - Limits the number of error messages to @var{n}, a decimal integer in the - range 1-999. The binder terminates immediately if this limit is reached. - - @item -M@var{xxx} - @cindex @code{-M} (@code{gnatbind}) - Renames the generated main program from @code{main} to @code{xxx}. - This is useful in the case of some cross-building environments, where - the actual main program is separate from the one generated - by @code{gnatbind}. - - @item -ws - @cindex @code{-ws} (@code{gnatbind}) - @cindex Warnings - Suppress all warning messages. - - @item -we - @cindex @code{-we} (@code{gnatbind}) - Treat any warning messages as fatal errors. - - - @item -t - @cindex @code{-t} (@code{gnatbind}) - @cindex Time stamp checks, in binder - @cindex Binder consistency checks - @cindex Consistency checks, in binder - The binder performs a number of consistency checks including: - - @itemize @bullet - @item - Check that time stamps of a given source unit are consistent - @item - Check that checksums of a given source unit are consistent - @item - Check that consistent versions of @code{GNAT} were used for compilation - @item - Check consistency of configuration pragmas as required - @end itemize - - @noindent - Normally failure of such checks, in accordance with the consistency - requirements of the Ada Reference Manual, causes error messages to be - generated which abort the binder and prevent the output of a binder - file and subsequent link to obtain an executable. - - The @code{-t} switch converts these error messages - into warnings, so that - binding and linking can continue to completion even in the presence of such - errors. The result may be a failed link (due to missing symbols), or a - non-functional executable which has undefined semantics. - @emph{This means that - @code{-t} should be used only in unusual situations, - with extreme care.} - @end table - - @node Elaboration Control - @section Elaboration Control - - @noindent - The following switches provide additional control over the elaboration - order. For full details see @xref{Elaboration Order Handling in GNAT}. - - @table @code - @item -p - @cindex @code{-h} (@code{gnatbind}) - Normally the binder attempts to choose an elaboration order that is - likely to minimize the likelihood of an elaboration order error resulting - in raising a @code{Program_Error} exception. This switch reverses the - action of the binder, and requests that it deliberately choose an order - that is likely to maximize the likelihood of an elaboration error. - This is useful in ensuring portability and avoiding dependence on - accidental fortuitous elaboration ordering. - - Normally it only makes sense to use the @code{-p} switch if dynamic - elaboration checking is used (@option{-gnatE} switch used for compilation). - This is because in the default static elaboration mode, all necessary - @code{Elaborate_All} pragmas are implicitly inserted. These implicit - pragmas are still respected by the binder in @code{-p} mode, so a - safe elaboration order is assured. - @end table - - @node Output Control - @section Output Control - - @noindent - The following switches allow additional control over the output - generated by the binder. - - @table @code - - @item -A - @cindex @code{-A} (@code{gnatbind}) - Generate binder program in Ada (default). The binder program is named - @file{b~@var{mainprog}.adb} by default. This can be changed with - @code{-o} @code{gnatbind} option. - - @item -c - @cindex @code{-c} (@code{gnatbind}) - Check only. Do not generate the binder output file. In this mode the - binder performs all error checks but does not generate an output file. - - @item -C - @cindex @code{-C} (@code{gnatbind}) - Generate binder program in C. The binder program is named - @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind} - option. - - @item -e - @cindex @code{-e} (@code{gnatbind}) - Output complete list of elaboration-order dependencies, showing the - reason for each dependency. This output can be rather extensive but may - be useful in diagnosing problems with elaboration order. The output is - written to @file{stdout}. - - @item -h - @cindex @code{-h} (@code{gnatbind}) - Output usage information. The output is written to @file{stdout}. - - @item -K - @cindex @code{-K} (@code{gnatbind}) - Output linker options to @file{stdout}. Includes library search paths, - contents of pragmas Ident and Linker_Options, and libraries added - by @code{gnatbind}. - - @item -l - @cindex @code{-l} (@code{gnatbind}) - Output chosen elaboration order. The output is written to @file{stdout}. - - @item -O - @cindex @code{-O} (@code{gnatbind}) - Output full names of all the object files that must be linked to provide - the Ada component of the program. The output is written to @file{stdout}. - This list includes the files explicitly supplied and referenced by the user - as well as implicitly referenced run-time unit files. The latter are - omitted if the corresponding units reside in shared libraries. The - directory names for the run-time units depend on the system configuration. - - @item -o @var{file} - @cindex @code{-o} (@code{gnatbind}) - Set name of output file to @var{file} instead of the normal - @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada - binder generated body filename. In C mode you would normally give - @var{file} an extension of @file{.c} because it will be a C source program. - Note that if this option is used, then linking must be done manually. - It is not possible to use gnatlink in this case, since it cannot locate - the binder file. - - @item -r - @cindex @code{-r} (@code{gnatbind}) - Generate list of @code{pragma Rerstrictions} that could be applied to - the current unit. This is useful for code audit purposes, and also may - be used to improve code generation in some cases. - - @end table - - @node Binding with Non-Ada Main Programs - @section Binding with Non-Ada Main Programs - - @noindent - In our description so far we have assumed that the main - program is in Ada, and that the task of the binder is to generate a - corresponding function @code{main} that invokes this Ada main - program. GNAT also supports the building of executable programs where - the main program is not in Ada, but some of the called routines are - written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). - The following switch is used in this situation: - - @table @code - @item -n - @cindex @code{-n} (@code{gnatbind}) - No main program. The main program is not in Ada. - @end table - - @noindent - In this case, most of the functions of the binder are still required, - but instead of generating a main program, the binder generates a file - containing the following callable routines: - - @table @code - @item adainit - @findex adainit - You must call this routine to initialize the Ada part of the program by - calling the necessary elaboration routines. A call to @code{adainit} is - required before the first call to an Ada subprogram. - - Note that it is assumed that the basic execution environment must be setup - to be appropriate for Ada execution at the point where the first Ada - subprogram is called. In particular, if the Ada code will do any - floating-point operations, then the FPU must be setup in an appropriate - manner. For the case of the x86, for example, full precision mode is - required. The procedure GNAT.Float_Control.Reset may be used to ensure - that the FPU is in the right state. - - @item adafinal - @findex adafinal - You must call this routine to perform any library-level finalization - required by the Ada subprograms. A call to @code{adafinal} is required - after the last call to an Ada subprogram, and before the program - terminates. - @end table - - @noindent - If the @code{-n} switch - @cindex Binder, multiple input files - is given, more than one ALI file may appear on - the command line for @code{gnatbind}. The normal @dfn{closure} - calculation is performed for each of the specified units. Calculating - the closure means finding out the set of units involved by tracing - @code{with} references. The reason it is necessary to be able to - specify more than one ALI file is that a given program may invoke two or - more quite separate groups of Ada units. - - The binder takes the name of its output file from the last specified ALI - file, unless overridden by the use of the @code{-o file}. - The output is an Ada unit in source form that can - be compiled with GNAT unless the -C switch is used in which case the - output is a C source file, which must be compiled using the C compiler. - This compilation occurs automatically as part of the @code{gnatlink} - processing. - - Currently the GNAT run time requires a FPU using 80 bits mode - precision. Under targets where this is not the default it is required to - call GNAT.Float_Control.Reset before using floating point numbers (this - include float computation, float input and output) in the Ada code. A - side effect is that this could be the wrong mode for the foreign code - where floating point computation could be broken after this call. - - @node Binding Programs with No Main Subprogram - @section Binding Programs with No Main Subprogram - - @noindent - It is possible to have an Ada program which does not have a main - subprogram. This program will call the elaboration routines of all the - packages, then the finalization routines. - - The following switch is used to bind programs organized in this manner: - - @table @code - @item -z - @cindex @code{-z} (@code{gnatbind}) - Normally the binder checks that the unit name given on the command line - corresponds to a suitable main subprogram. When this switch is used, - a list of ALI files can be given, and the execution of the program - consists of elaboration of these units in an appropriate order. - @end table - - @node Summary of Binder Switches - @section Summary of Binder Switches - - @noindent - The following are the switches available with @code{gnatbind}: - - @table @code - @item -aO - Specify directory to be searched for ALI files. - - @item -aI - Specify directory to be searched for source file. - - @item -A - Generate binder program in Ada (default) - - @item -b - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -c - Check only, no generation of binder output file. - - @item -C - Generate binder program in C - - @item -e - Output complete list of elaboration-order dependencies. - - @item -E - Store tracebacks in exception occurrences when the target supports it. - This is the default with the zero cost exception mechanism. - This option is currently supported on the following targets: - all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. - See also the packages @code{GNAT.Traceback} and - @code{GNAT.Traceback.Symbolic} for more information. - Note that on x86 ports, you must not use @code{-fomit-frame-pointer} - @code{gcc} option. - - @item -h - Output usage (help) information - - @item -I - Specify directory to be searched for source and ALI files. - - @item -I- - Do not look for sources in the current directory where @code{gnatbind} was - invoked, and do not look for ALI files in the directory containing the - ALI file named in the @code{gnatbind} command line. - - @item -l - Output chosen elaboration order. - - @item -Lxxx - Binds the units for library building. In this case the adainit and - adafinal procedures (See @pxref{Binding with Non-Ada Main Programs}) - are renamed to xxxinit and xxxfinal. Implies -n. - See @pxref{GNAT and Libraries} for more details. - - @item -Mxyz - Rename generated main program from main to xyz - - @item -m@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item -n - No main program. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatbind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -o @var{file} - Name the output file @var{file} (default is @file{b~@var{xxx}.adb}). - Note that if this option is used, then linking must be done manually, - gnatlink cannot be used. - - @item -O - Output object list. - - @item -p - Pessimistic (worst-case) elaboration order - - @item -s - Require all source files to be present. - - @item -static - Link against a static GNAT run time. - - @item -shared - Link against a shared GNAT run time when available. - - @item -t - Tolerate time stamp and other consistency errors - - @item -T@var{n} - Set the time slice value to n microseconds. A value of zero means no time - slicing and also indicates to the tasking run time to match as close as - possible to the annex D requirements of the RM. - - @item -v - Verbose mode. Write error messages, header, summary output to - @file{stdout}. - - @item -w@var{x} - Warning mode (@var{x}=s/e for suppress/treat as error) - - - @item -x - Exclude source files (check object consistency only). - - - @item -z - No main subprogram. - - @end table - - You may obtain this listing by running the program @code{gnatbind} with - no arguments. - - @node Command-Line Access - @section Command-Line Access - - @noindent - The package @code{Ada.Command_Line} provides access to the command-line - arguments and program name. In order for this interface to operate - correctly, the two variables - - @smallexample - @group - @cartouche - int gnat_argc; - char **gnat_argv; - @end cartouche - @end group - @end smallexample - - @noindent - @findex gnat_argv - @findex gnat_argc - are declared in one of the GNAT library routines. These variables must - be set from the actual @code{argc} and @code{argv} values passed to the - main program. With no @code{n} present, @code{gnatbind} - generates the C main program to automatically set these variables. - If the @code{n} switch is used, there is no automatic way to - set these variables. If they are not set, the procedures in - @code{Ada.Command_Line} will not be available, and any attempt to use - them will raise @code{Constraint_Error}. If command line access is - required, your main program must set @code{gnat_argc} and - @code{gnat_argv} from the @code{argc} and @code{argv} values passed to - it. - - @node Search Paths for gnatbind - @section Search Paths for @code{gnatbind} - - @noindent - The binder takes the name of an ALI file as its argument and needs to - locate source files as well as other ALI files to verify object consistency. - - For source files, it follows exactly the same search rules as @code{gcc} - (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the - directories searched are: - - @enumerate - @item - The directory containing the ALI file named in the command line, unless - the switch @code{-I-} is specified. - - @item - All directories specified by @code{-I} - switches on the @code{gnatbind} - command line, in the order given. - - @item - @findex ADA_OBJECTS_PATH - Each of the directories listed in the value of the - @code{ADA_OBJECTS_PATH} environment variable. - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version - of GNAT). - - @item - The content of the "ada_object_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is - specified. - @ref{Installing an Ada Library} - @end enumerate - - @noindent - In the binder the switch @code{-I} - is used to specify both source and - library file paths. Use @code{-aI} - instead if you want to specify - source paths only, and @code{-aO} - if you want to specify library paths - only. This means that for the binder - @code{-I}@var{dir} is equivalent to - @code{-aI}@var{dir} - @code{-aO}@var{dir}. - The binder generates the bind file (a C language source file) in the - current working directory. - - @findex Ada - @findex System - @findex Interfaces - @findex GNAT - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT Run-Time Library, together with the package - GNAT and its children, which contain a set of useful additional - library functions provided by GNAT. The sources for these units are - needed by the compiler and are kept together in one directory. The ALI - files and object files generated by compiling the RTL are needed by the - binder and the linker and are kept together in one directory, typically - different from the directory containing the sources. In a normal - installation, you need not specify these directory names when compiling - or binding. Either the environment variables or the built-in defaults - cause these files to be found. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Examples of gnatbind Usage - @section Examples of @code{gnatbind} Usage - - @noindent - This section contains a number of examples of using the GNAT binding - utility @code{gnatbind}. - - @table @code - @item gnatbind hello - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{b~hello.adb}. This is the normal, default use of the binder. - - @item gnatbind hello -o mainprog.adb - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{mainprog.adb} with the associated spec in - @file{mainprog.ads}. Note that you must specify the body here not the - spec, in the case where the output is in Ada. Note that if this option - is used, then linking must be done manually, since gnatlink will not - be able to find the generated file. - - @item gnatbind main -C -o mainprog.c -x - The main program @code{Main} (source program in - @file{main.adb}) is bound, excluding source files from the - consistency checking, generating - the file @file{mainprog.c}. - - @item gnatbind -x main_program -C -o mainprog.c - This command is exactly the same as the previous example. Switches may - appear anywhere in the command line, and single letter switches may be - combined into a single switch. - - @item gnatbind -n math dbase -C -o ada-control.c - The main program is in a language other than Ada, but calls to - subprograms in packages @code{Math} and @code{Dbase} appear. This call - to @code{gnatbind} generates the file @file{ada-control.c} containing - the @code{adainit} and @code{adafinal} routines to be called before and - after accessing the Ada units. - @end table - - @node Linking Using gnatlink - @chapter Linking Using @code{gnatlink} - @findex gnatlink - - @noindent - This chapter discusses @code{gnatlink}, a utility program used to link - Ada programs and build an executable file. This is a simple program - that invokes the Unix linker (via the @code{gcc} - command) with a correct list of object files and library references. - @code{gnatlink} automatically determines the list of files and - references for the Ada part of a program. It uses the binder file - generated by the binder to determine this list. - - @menu - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - @end menu - - @node Running gnatlink - @section Running @code{gnatlink} - - @noindent - The form of the @code{gnatlink} command is - - @smallexample - $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}] - [@var{linker options}] - @end smallexample - - @noindent - @file{@var{mainprog}.ali} references the ALI file of the main program. - The @file{.ali} extension of this file can be omitted. From this - reference, @code{gnatlink} locates the corresponding binder file - @file{b~@var{mainprog}.adb} and, using the information in this file along - with the list of non-Ada objects and linker options, constructs a Unix - linker command file to create the executable. - - The arguments following @file{@var{mainprog}.ali} are passed to the - linker uninterpreted. They typically include the names of object files - for units written in other languages than Ada and any library references - required to resolve references in any of these foreign language units, - or in @code{pragma Import} statements in any Ada units. - - @var{linker options} is an optional list of linker specific - switches. The default linker called by gnatlink is @var{gcc} which in - turn calls the appropriate system linker usually called - @var{ld}. Standard options for the linker such as @code{-lmy_lib} or - @code{-Ldir} can be added as is. For options that are not recognized by - @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or - @code{-Wl,} shall be used. Refer to the GCC documentation for - details. Here is an example showing how to generate a linker map - assuming that the underlying linker is GNU ld: - - @smallexample - $ gnatlink my_prog -Wl,-Map,MAPFILE - @end smallexample - - Using @var{linker options} it is possible to set the program stack and - heap size. See @pxref{Setting Stack Size from gnatlink} and - @pxref{Setting Heap Size from gnatlink}. - - @code{gnatlink} determines the list of objects required by the Ada - program and prepends them to the list of objects passed to the linker. - @code{gnatlink} also gathers any arguments set by the use of - @code{pragma Linker_Options} and adds them to the list of arguments - presented to the linker. - - - @node Switches for gnatlink - @section Switches for @code{gnatlink} - - @noindent - The following switches are available with the @code{gnatlink} utility: - - @table @code - - @item -A - @cindex @code{-A} (@code{gnatlink}) - The binder has generated code in Ada. This is the default. - - @item -C - @cindex @code{-C} (@code{gnatlink}) - If instead of generating a file in Ada, the binder has generated one in - C, then the linker needs to know about it. Use this switch to signal - to @code{gnatlink} that the binder has generated C code rather than - Ada code. - - @item -f - @cindex Command line length - @cindex @code{-f} (@code{gnatlink}) - On some targets, the command line length is limited, and @code{gnatlink} - will generate a separate file for the linker if the list of object files - is too long. The @code{-f} flag forces this file to be generated even if - the limit is not exceeded. This is useful in some cases to deal with - special situations where the command line length is exceeded. - - @item -g - @cindex Debugging information, including - @cindex @code{-g} (@code{gnatlink}) - The option to include debugging information causes the Ada bind file (in - other words, @file{b~@var{mainprog}.adb}) to be compiled with - @code{-g}. - In addition, the binder does not delete the @file{b~@var{mainprog}.adb}, - @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files. - Without @code{-g}, the binder removes these files by - default. The same procedure apply if a C bind file was generated using - @code{-C} @code{gnatbind} option, in this case the filenames are - @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}. - - @item -n - @cindex @code{-n} (@code{gnatlink}) - Do not compile the file generated by the binder. This may be used when - a link is rerun with different options, but there is no need to recompile - the binder file. - - @item -v - @cindex @code{-v} (@code{gnatlink}) - Causes additional information to be output, including a full list of the - included object files. This switch option is most useful when you want - to see what set of object files are being used in the link step. - - @item -v -v - @cindex @code{-v -v} (@code{gnatlink}) - Very verbose mode. Requests that the compiler operate in verbose mode when - it compiles the binder file, and that the system linker run in verbose mode. - - @item -o @var{exec-name} - @cindex @code{-o} (@code{gnatlink}) - @var{exec-name} specifies an alternate name for the generated - executable program. If this switch is omitted, the executable has the same - name as the main unit. For example, @code{gnatlink try.ali} creates - an executable called @file{try}. - - @item -b @var{target} - @cindex @code{-b} (@code{gnatlink}) - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gnatlink}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatlink}) - Program used for compiling the binder file. The default is - `@code{gcc}'. You need to use quotes around @var{compiler_name} if - @code{compiler_name} contains spaces or other separator characters. As - an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use - @code{foo -x -y} as your compiler. Note that switch @code{-c} is always - inserted after your command name. Thus in the above example the compiler - command that will be used by @code{gnatlink} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --LINK=@var{name} - @cindex @code{--LINK=} (@code{gnatlink}) - @var{name} is the name of the linker to be invoked. This is especially - useful in mixed language programs since languages such as c++ require - their own linker to be used. When this switch is omitted, the default - name for the linker is (@file{gcc}). When this switch is used, the - specified linker is called instead of (@file{gcc}) with exactly the same - parameters that would have been passed to (@file{gcc}) so if the desired - linker requires different parameters it is necessary to use a wrapper - script that massages the parameters before invoking the real linker. It - may be useful to control the exact invocation by using the verbose - switch. - - - - @end table - - @node Setting Stack Size from gnatlink - @section Setting Stack Size from @code{gnatlink} - - @noindent - It is possible to specify the program stack size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --stack=0x10000,0x1000 - @end smallexample - - This set the stack reserve size to 0x10000 bytes and the stack commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--stack=0x1000000 - @end smallexample - - This set the stack reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the stack commit size - because the coma is a separator for this option. - - @end itemize - - @node Setting Heap Size from gnatlink - @section Setting Heap Size from @code{gnatlink} - - @noindent - It is possible to specify the program heap size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --heap=0x10000,0x1000 - @end smallexample - - This set the heap reserve size to 0x10000 bytes and the heap commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--heap=0x1000000 - @end smallexample - - This set the heap reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the heap commit size - because the coma is a separator for this option. - - @end itemize - - @node The GNAT Make Program gnatmake - @chapter The GNAT Make Program @code{gnatmake} - @findex gnatmake - - @menu - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - @end menu - @noindent - A typical development cycle when working on an Ada program consists of - the following steps: - - @enumerate - @item - Edit some sources to fix bugs. - - @item - Add enhancements. - - @item - Compile all sources affected. - - @item - Rebind and relink. - - @item - Test. - @end enumerate - - @noindent - The third step can be tricky, because not only do the modified files - @cindex Dependency rules - have to be compiled, but any files depending on these files must also be - recompiled. The dependency rules in Ada can be quite complex, especially - in the presence of overloading, @code{use} clauses, generics and inlined - subprograms. - - @code{gnatmake} automatically takes care of the third and fourth steps - of this process. It determines which sources need to be compiled, - compiles them, and binds and links the resulting object files. - - Unlike some other Ada make programs, the dependencies are always - accurately recomputed from the new sources. The source based approach of - the GNAT compilation model makes this possible. This means that if - changes to the source program cause corresponding changes in - dependencies, they will always be tracked exactly correctly by - @code{gnatmake}. - - @node Running gnatmake - @section Running @code{gnatmake} - - @noindent - The usual form of the @code{gnatmake} command is - - @smallexample - $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}] - @end smallexample - - @noindent - The only required argument is one @var{file_name}, which specifies - a compilation unit that is a main program. Several @var{file_names} can be - specified: this will result in several executables being built. - If @code{switches} are present, they can be placed before the first - @var{file_name}, between @var{file_names} or after the last @var{file_name}. - If @var{mode_switches} are present, they must always be placed after - the last @var{file_name} and all @code{switches}. - - If you are using standard file extensions (.adb and .ads), then the - extension may be omitted from the @var{file_name} arguments. However, if - you are using non-standard extensions, then it is required that the - extension be given. A relative or absolute directory path can be - specified in a @var{file_name}, in which case, the input source file will - be searched for in the specified directory only. Otherwise, the input - source file will first be searched in the directory where - @code{gnatmake} was invoked and if it is not found, it will be search on - the source path of the compiler as described in - @ref{Search Paths and the Run-Time Library (RTL)}. - - When several @var{file_names} are specified, if an executable needs to be - rebuilt and relinked, all subsequent executables will be rebuilt and - relinked, even if this would not be absolutely necessary. - - All @code{gnatmake} output (except when you specify - @code{-M}) is to - @file{stderr}. The output produced by the - @code{-M} switch is send to - @file{stdout}. - - @node Switches for gnatmake - @section Switches for @code{gnatmake} - - @noindent - You may specify any of the following switches to @code{gnatmake}: - - @table @code - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatmake}) - Program used for compiling. The default is `@code{gcc}'. You need to use - quotes around @var{compiler_name} if @code{compiler_name} contains - spaces or other separator characters. As an example @code{--GCC="foo -x - -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your - compiler. Note that switch @code{-c} is always inserted after your - command name. Thus in the above example the compiler command that will - be used by @code{gnatmake} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --GNATBIND=@var{binder_name} - @cindex @code{--GNATBIND=binder_name} (@code{gnatmake}) - Program used for binding. The default is `@code{gnatbind}'. You need to - use quotes around @var{binder_name} if @var{binder_name} contains spaces - or other separator characters. As an example @code{--GNATBIND="bar -x - -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your - binder. Binder switches that are normally appended by @code{gnatmake} to - `@code{gnatbind}' are now appended to the end of @code{bar -x -y}. - - @item --GNATLINK=@var{linker_name} - @cindex @code{--GNATLINK=linker_name} (@code{gnatmake}) - Program used for linking. The default is `@code{gnatlink}'. You need to - use quotes around @var{linker_name} if @var{linker_name} contains spaces - or other separator characters. As an example @code{--GNATLINK="lan -x - -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your - linker. Linker switches that are normally appended by @code{gnatmake} to - `@code{gnatlink}' are now appended to the end of @code{lan -x -y}. - - - @item -a - @cindex @code{-a} (@code{gnatmake}) - Consider all files in the make process, even the GNAT internal system - files (for example, the predefined Ada library files), as well as any - locked files. Locked files are files whose ALI file is write-protected. - By default, - @code{gnatmake} does not check these files, - because the assumption is that the GNAT internal files are properly up - to date, and also that any write protected ALI files have been properly - installed. Note that if there is an installation problem, such that one - of these files is not up to date, it will be properly caught by the - binder. - You may have to specify this switch if you are working on GNAT - itself. @code{-a} is also useful in conjunction with - @code{-f} - if you need to recompile an entire application, - including run-time files, using special configuration pragma settings, - such as a non-standard @code{Float_Representation} pragma. - By default - @code{gnatmake -a} compiles all GNAT - internal files with - @code{gcc -c -gnatpg} rather than @code{gcc -c}. - - @item -b - @cindex @code{-b} (@code{gnatmake}) - Bind only. Can be combined with @code{-c} to do compilation - and binding, but no link. Can be combined with @code{-l} - to do binding and linking. When not combined with @code{-c} - all the units in the closure of the main program must have been previously - compiled and must be up to date. The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item -c - @cindex @code{-c} (@code{gnatmake}) - Compile only. Do not perform binding, except when @code{-b} - is also specified. Do not perform linking, except if both - @code{-b} and - @code{-l} are also specified. - If the root unit specified by @var{file_name} is not a main unit, this is the - default. Otherwise @code{gnatmake} will attempt binding and linking - unless all objects are up to date and the executable is more recent than - the objects. - - @item -C - @cindex @code{-C} (@code{gnatmake}) - Use a mapping file. A mapping file is a way to communicate to the compiler - two mappings: from unit names to file names (without any directory information) - and from file names to path names (with full directory information). - These mappings are used by the compiler to short-circuit the path search. - When @code{gnatmake} is invoked with this switch, it will create a mapping - file, initially populated by the project manager, if @code{-P} is used, - otherwise initially empty. Each invocation of the compiler will add the newly - accessed sources to the mapping file. This will improve the source search - during the next invocation of the compiler. - - @item -f - @cindex @code{-f} (@code{gnatmake}) - Force recompilations. Recompile all sources, even though some object - files may be up to date, but don't recompile predefined or GNAT internal - files or locked files (files with a write-protected ALI file), - unless the @code{-a} switch is also specified. - - @item - @item -i - @cindex @code{-i} (@code{gnatmake}) - In normal mode, @code{gnatmake} compiles all object files and ALI files - into the current directory. If the @code{-i} switch is used, - then instead object files and ALI files that already exist are overwritten - in place. This means that once a large project is organized into separate - directories in the desired manner, then @code{gnatmake} will automatically - maintain and update this organization. If no ALI files are found on the - Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), - the new object and ALI files are created in the - directory containing the source being compiled. If another organization - is desired, where objects and sources are kept in different directories, - a useful technique is to create dummy ALI files in the desired directories. - When detecting such a dummy file, @code{gnatmake} will be forced to recompile - the corresponding source file, and it will be put the resulting object - and ALI files in the directory where it found the dummy file. - - @item -j@var{n} - @cindex @code{-j} (@code{gnatmake}) - @cindex Parallel make - Use @var{n} processes to carry out the (re)compilations. On a - multiprocessor machine compilations will occur in parallel. In the - event of compilation errors, messages from various compilations might - get interspersed (but @code{gnatmake} will give you the full ordered - list of failing compiles at the end). If this is problematic, rerun - the make process with n set to 1 to get a clean list of messages. - - @item -k - @cindex @code{-k} (@code{gnatmake}) - Keep going. Continue as much as possible after a compilation error. To - ease the programmer's task in case of compilation errors, the list of - sources for which the compile fails is given when @code{gnatmake} - terminates. - - If @code{gnatmake} is invoked with several @file{file_names} and with this - switch, if there are compilation errors when building an executable, - @code{gnatmake} will not attempt to build the following executables. - - @item -l - @cindex @code{-l} (@code{gnatmake}) - Link only. Can be combined with @code{-b} to binding - and linking. Linking will not be performed if combined with - @code{-c} - but not with @code{-b}. - When not combined with @code{-b} - all the units in the closure of the main program must have been previously - compiled and must be up to date, and the main program need to have been bound. - The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item -m - @cindex @code{-m} (@code{gnatmake}) - Specifies that the minimum necessary amount of recompilations - be performed. In this mode @code{gnatmake} ignores time - stamp differences when the only - modifications to a source file consist in adding/removing comments, - empty lines, spaces or tabs. This means that if you have changed the - comments in a source file or have simply reformatted it, using this - switch will tell gnatmake not to recompile files that depend on it - (provided other sources on which these files depend have undergone no - semantic modifications). Note that the debugging information may be - out of date with respect to the sources if the @code{-m} switch causes - a compilation to be switched, so the use of this switch represents a - trade-off between compilation time and accurate debugging information. - - @item -M - @cindex Dependencies, producing list - @cindex @code{-M} (@code{gnatmake}) - Check if all objects are up to date. If they are, output the object - dependences to @file{stdout} in a form that can be directly exploited in - a @file{Makefile}. By default, each source file is prefixed with its - (relative or absolute) directory name. This name is whatever you - specified in the various @code{-aI} - and @code{-I} switches. If you use - @code{gnatmake -M} - @code{-q} - (see below), only the source file names, - without relative paths, are output. If you just specify the - @code{-M} - switch, dependencies of the GNAT internal system files are omitted. This - is typically what you want. If you also specify - the @code{-a} switch, - dependencies of the GNAT internal files are also listed. Note that - dependencies of the objects in external Ada libraries (see switch - @code{-aL}@var{dir} in the following list) are never reported. - - @item -n - @cindex @code{-n} (@code{gnatmake}) - Don't compile, bind, or link. Checks if all objects are up to date. - If they are not, the full name of the first file that needs to be - recompiled is printed. - Repeated use of this option, followed by compiling the indicated source - file, will eventually result in recompiling all required units. - - @item -o @var{exec_name} - @cindex @code{-o} (@code{gnatmake}) - Output executable name. The name of the final executable program will be - @var{exec_name}. If the @code{-o} switch is omitted the default - name for the executable will be the name of the input file in appropriate form - for an executable file on the host system. - - This switch cannot be used when invoking @code{gnatmake} with several - @file{file_names}. - - @item -q - @cindex @code{-q} (@code{gnatmake}) - Quiet. When this flag is not set, the commands carried out by - @code{gnatmake} are displayed. - - @item -s - @cindex @code{-s} (@code{gnatmake}) - Recompile if compiler switches have changed since last compilation. - All compiler switches but -I and -o are taken into account in the - following way: - orders between different ``first letter'' switches are ignored, but - orders between same switches are taken into account. For example, - @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent - to @code{-O -g}. - - @item -u - @cindex @code{-u} (@code{gnatmake}) - Unique. Recompile at most the main file. It implies -c. Combined with - -f, it is equivalent to calling the compiler directly. - - @item -v - @cindex @code{-v} (@code{gnatmake}) - Verbose. Displays the reason for all recompilations @code{gnatmake} - decides are necessary. - - @item -z - @cindex @code{-z} (@code{gnatmake}) - No main subprogram. Bind and link the program even if the unit name - given on the command line is a package name. The resulting executable - will execute the elaboration routines of the package and its closure, - then the finalization routines. - - @item @code{gcc} @asis{switches} - The switch @code{-g} or any uppercase switch (other than @code{-A}, - @code{-L} or - @code{-S}) or any switch that is more than one character is passed to - @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.) - @end table - - @noindent - Source and library search path switches: - - @table @code - @item -aI@var{dir} - @cindex @code{-aI} (@code{gnatmake}) - When looking for source files also look in directory @var{dir}. - The order in which source files search is undertaken is - described in @ref{Search Paths and the Run-Time Library (RTL)}. - - @item -aL@var{dir} - @cindex @code{-aL} (@code{gnatmake}) - Consider @var{dir} as being an externally provided Ada library. - Instructs @code{gnatmake} to skip compilation units whose @file{.ali} - files have been located in directory @var{dir}. This allows you to have - missing bodies for the units in @var{dir} and to ignore out of date bodies - for the same units. You still need to specify - the location of the specs for these units by using the switches - @code{-aI@var{dir}} - or @code{-I@var{dir}}. - Note: this switch is provided for compatibility with previous versions - of @code{gnatmake}. The easier method of causing standard libraries - to be excluded from consideration is to write-protect the corresponding - ALI files. - - @item -aO@var{dir} - @cindex @code{-aO} (@code{gnatmake}) - When searching for library and object files, look in directory - @var{dir}. The order in which library files are searched is described in - @ref{Search Paths for gnatbind}. - - @item -A@var{dir} - @cindex Search paths, for @code{gnatmake} - @cindex @code{-A} (@code{gnatmake}) - Equivalent to @code{-aL@var{dir} - -aI@var{dir}}. - - @item -I@var{dir} - @cindex @code{-I} (@code{gnatmake}) - Equivalent to @code{-aO@var{dir} - -aI@var{dir}}. - - @item -I- - @cindex @code{-I-} (@code{gnatmake}) - @cindex Source files, suppressing search - Do not look for source files in the directory containing the source - file named in the command line. - Do not look for ALI or object files in the directory - where @code{gnatmake} was invoked. - - @item -L@var{dir} - @cindex @code{-L} (@code{gnatmake}) - @cindex Linker libraries - Add directory @var{dir} to the list of directories in which the linker - will search for libraries. This is equivalent to - @code{-largs -L}@var{dir}. - - @item -nostdinc - @cindex @code{-nostdinc} (@code{gnatmake}) - Do not look for source files in the system default directory. - - @item -nostdlib - @cindex @code{-nostdlib} (@code{gnatmake}) - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatmake}) - Specifies the default location of the runtime library. We look for the runtime - in the following directories, and stop as soon as a valid runtime is found - ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present): - - @itemize @bullet - @item /$rts_path - - @item /$rts_path - - @item /rts-$rts_path - @end itemize - - @noindent - The selected path is handled like a normal RTS path. - - @end table - - @node Mode Switches for gnatmake - @section Mode Switches for @code{gnatmake} - - @noindent - The mode switches (referred to as @code{mode_switches}) allow the - inclusion of switches that are to be passed to the compiler itself, the - binder or the linker. The effect of a mode switch is to cause all - subsequent switches up to the end of the switch list, or up to the next - mode switch, to be interpreted as switches to be passed on to the - designated component of GNAT. - - @table @code - @item -cargs @var{switches} - @cindex @code{-cargs} (@code{gnatmake}) - Compiler switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all compile steps performed by @code{gnatmake}. - - @item -bargs @var{switches} - @cindex @code{-bargs} (@code{gnatmake}) - Binder switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all bind steps performed by @code{gnatmake}. - - @item -largs @var{switches} - @cindex @code{-largs} (@code{gnatmake}) - Linker switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all link steps performed by @code{gnatmake}. - @end table - - @node Notes on the Command Line - @section Notes on the Command Line - - @noindent - This section contains some additional useful notes on the operation - of the @code{gnatmake} command. - - @itemize @bullet - @item - @cindex Recompilation, by @code{gnatmake} - If @code{gnatmake} finds no ALI files, it recompiles the main program - and all other units required by the main program. - This means that @code{gnatmake} - can be used for the initial compile, as well as during subsequent steps of - the development cycle. - - @item - If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb} - is a subunit or body of a generic unit, @code{gnatmake} recompiles - @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a - warning. - - @item - In @code{gnatmake} the switch @code{-I} - is used to specify both source and - library file paths. Use @code{-aI} - instead if you just want to specify - source paths only and @code{-aO} - if you want to specify library paths - only. - - @item - @code{gnatmake} examines both an ALI file and its corresponding object file - for consistency. If an ALI is more recent than its corresponding object, - or if the object file is missing, the corresponding source will be recompiled. - Note that @code{gnatmake} expects an ALI and the corresponding object file - to be in the same directory. - - @item - @code{gnatmake} will ignore any files whose ALI file is write-protected. - This may conveniently be used to exclude standard libraries from - consideration and in particular it means that the use of the - @code{-f} switch will not recompile these files - unless @code{-a} is also specified. - - @item - @code{gnatmake} has been designed to make the use of Ada libraries - particularly convenient. Assume you have an Ada library organized - as follows: @var{obj-dir} contains the objects and ALI files for - of your Ada compilation units, - whereas @var{include-dir} contains the - specs of these units, but no bodies. Then to compile a unit - stored in @code{main.adb}, which uses this Ada library you would just type - - @smallexample - $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main - @end smallexample - - @item - Using @code{gnatmake} along with the - @code{-m (minimal recompilation)} - switch provides a mechanism for avoiding unnecessary rcompilations. Using - this switch, - you can update the comments/format of your - source files without having to recompile everything. Note, however, that - adding or deleting lines in a source files may render its debugging - info obsolete. If the file in question is a spec, the impact is rather - limited, as that debugging info will only be useful during the - elaboration phase of your program. For bodies the impact can be more - significant. In all events, your debugger will warn you if a source file - is more recent than the corresponding object, and alert you to the fact - that the debugging information may be out of date. - @end itemize - - @node How gnatmake Works - @section How @code{gnatmake} Works - - @noindent - Generally @code{gnatmake} automatically performs all necessary - recompilations and you don't need to worry about how it works. However, - it may be useful to have some basic understanding of the @code{gnatmake} - approach and in particular to understand how it uses the results of - previous compilations without incorrectly depending on them. - - First a definition: an object file is considered @dfn{up to date} if the - corresponding ALI file exists and its time stamp predates that of the - object file and if all the source files listed in the - dependency section of this ALI file have time stamps matching those in - the ALI file. This means that neither the source file itself nor any - files that it depends on have been modified, and hence there is no need - to recompile this file. - - @code{gnatmake} works by first checking if the specified main unit is up - to date. If so, no compilations are required for the main unit. If not, - @code{gnatmake} compiles the main program to build a new ALI file that - reflects the latest sources. Then the ALI file of the main unit is - examined to find all the source files on which the main program depends, - and @code{gnatmake} recursively applies the above procedure on all these files. - - This process ensures that @code{gnatmake} only trusts the dependencies - in an existing ALI file if they are known to be correct. Otherwise it - always recompiles to determine a new, guaranteed accurate set of - dependencies. As a result the program is compiled "upside down" from what may - be more familiar as the required order of compilation in some other Ada - systems. In particular, clients are compiled before the units on which - they depend. The ability of GNAT to compile in any order is critical in - allowing an order of compilation to be chosen that guarantees that - @code{gnatmake} will recompute a correct set of new dependencies if - necessary. - - When invoking @code{gnatmake} with several @var{file_names}, if a unit is - imported by several of the executables, it will be recompiled at most once. - - @node Examples of gnatmake Usage - @section Examples of @code{gnatmake} Usage - - @table @code - @item gnatmake hello.adb - Compile all files necessary to bind and link the main program - @file{hello.adb} (containing unit @code{Hello}) and bind and link the - resulting object files to generate an executable file @file{hello}. - - @item gnatmake main1 main2 main3 - Compile all files necessary to bind and link the main programs - @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb} - (containing unit @code{Main2}) and @file{main3.adb} - (containing unit @code{Main3}) and bind and link the resulting object files - to generate three executable files @file{main1}, - @file{main2} - and @file{main3}. - - @item gnatmake -q Main_Unit -cargs -O2 -bargs -l - - Compile all files necessary to bind and link the main program unit - @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will - be done with optimization level 2 and the order of elaboration will be - listed by the binder. @code{gnatmake} will operate in quiet mode, not - displaying commands it is executing. - @end table - - @node Renaming Files Using gnatchop - @chapter Renaming Files Using @code{gnatchop} - @findex gnatchop - - @noindent - This chapter discusses how to handle files with multiple units by using - the @code{gnatchop} utility. This utility is also useful in renaming - files to meet the standard GNAT default file naming conventions. - - @menu - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - @end menu - - @node Handling Files with Multiple Units - @section Handling Files with Multiple Units - - @noindent - The basic compilation model of GNAT requires that a file submitted to the - compiler have only one unit and there be a strict correspondence - between the file name and the unit name. - - The @code{gnatchop} utility allows both of these rules to be relaxed, - allowing GNAT to process files which contain multiple compilation units - and files with arbitrary file names. @code{gnatchop} - reads the specified file and generates one or more output files, - containing one unit per file. The unit and the file name correspond, - as required by GNAT. - - If you want to permanently restructure a set of "foreign" files so that - they match the GNAT rules, and do the remaining development using the - GNAT structure, you can simply use @code{gnatchop} once, generate the - new set of files and work with them from that point on. - - Alternatively, if you want to keep your files in the "foreign" format, - perhaps to maintain compatibility with some other Ada compilation - system, you can set up a procedure where you use @code{gnatchop} each - time you compile, regarding the source files that it writes as temporary - files that you throw away. - - @node Operating gnatchop in Compilation Mode - @section Operating gnatchop in Compilation Mode - - @noindent - The basic function of @code{gnatchop} is to take a file with multiple units - and split it into separate files. The boundary between files is reasonably - clear, except for the issue of comments and pragmas. In default mode, the - rule is that any pragmas between units belong to the previous unit, except - that configuration pragmas always belong to the following unit. Any comments - belong to the following unit. These rules - almost always result in the right choice of - the split point without needing to mark it explicitly and most users will - find this default to be what they want. In this default mode it is incorrect to - submit a file containing only configuration pragmas, or one that ends in - configuration pragmas, to @code{gnatchop}. - - However, using a special option to activate "compilation mode", - @code{gnatchop} - can perform another function, which is to provide exactly the semantics - required by the RM for handling of configuration pragmas in a compilation. - In the absence of configuration pragmas (at the main file level), this - option has no effect, but it causes such configuration pragmas to be handled - in a quite different manner. - - First, in compilation mode, if @code{gnatchop} is given a file that consists of - only configuration pragmas, then this file is appended to the - @file{gnat.adc} file in the current directory. This behavior provides - the required behavior described in the RM for the actions to be taken - on submitting such a file to the compiler, namely that these pragmas - should apply to all subsequent compilations in the same compilation - environment. Using GNAT, the current directory, possibly containing a - @file{gnat.adc} file is the representation - of a compilation environment. For more information on the - @file{gnat.adc} file, see the section on handling of configuration - pragmas @pxref{Handling of Configuration Pragmas}. - - Second, in compilation mode, if @code{gnatchop} - is given a file that starts with - configuration pragmas, and contains one or more units, then these - configuration pragmas are prepended to each of the chopped files. This - behavior provides the required behavior described in the RM for the - actions to be taken on compiling such a file, namely that the pragmas - apply to all units in the compilation, but not to subsequently compiled - units. - - Finally, if configuration pragmas appear between units, they are appended - to the previous unit. This results in the previous unit being illegal, - since the compiler does not accept configuration pragmas that follow - a unit. This provides the required RM behavior that forbids configuration - pragmas other than those preceding the first compilation unit of a - compilation. - - For most purposes, @code{gnatchop} will be used in default mode. The - compilation mode described above is used only if you need exactly - accurate behavior with respect to compilations, and you have files - that contain multiple units and configuration pragmas. In this - circumstance the use of @code{gnatchop} with the compilation mode - switch provides the required behavior, and is for example the mode - in which GNAT processes the ACVC tests. - - @node Command Line for gnatchop - @section Command Line for @code{gnatchop} - - @noindent - The @code{gnatchop} command has the form: - - @smallexample - $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...] - [@var{directory}] - @end smallexample - - @noindent - The only required argument is the file name of the file to be chopped. - There are no restrictions on the form of this file name. The file itself - contains one or more Ada units, in normal GNAT format, concatenated - together. As shown, more than one file may be presented to be chopped. - - When run in default mode, @code{gnatchop} generates one output file in - the current directory for each unit in each of the files. - - @var{directory}, if specified, gives the name of the directory to which - the output files will be written. If it is not specified, all files are - written to the current directory. - - For example, given a - file called @file{hellofiles} containing - - @smallexample - @group - @cartouche - @b{procedure} hello; - - @b{with} Text_IO; @b{use} Text_IO; - @b{procedure} hello @b{is} - @b{begin} - Put_Line ("Hello"); - @b{end} hello; - @end cartouche - @end group - @end smallexample - - @noindent - the command - - @smallexample - $ gnatchop hellofiles - @end smallexample - - @noindent - generates two files in the current directory, one called - @file{hello.ads} containing the single line that is the procedure spec, - and the other called @file{hello.adb} containing the remaining text. The - original file is not affected. The generated files can be compiled in - the normal manner. - - @node Switches for gnatchop - @section Switches for @code{gnatchop} - - @noindent - @code{gnatchop} recognizes the following switches: - - @table @code - - @item -c - @cindex @code{-c} (@code{gnatchop}) - Causes @code{gnatchop} to operate in compilation mode, in which - configuration pragmas are handled according to strict RM rules. See - previous section for a full description of this mode. - - @item -gnatxxx - This passes the given @option{-gnatxxx} switch to @code{gnat} which is - used to parse the given file. Not all @code{xxx} options make sense, - but for example, the use of @option{-gnati2} allows @code{gnatchop} to - process a source file that uses Latin-2 coding for identifiers. - - @item -h - Causes @code{gnatchop} to generate a brief help summary to the standard - output file showing usage information. - - @item -k@var{mm} - @cindex @code{-k} (@code{gnatchop}) - Limit generated file names to the specified number @code{mm} - of characters. - This is useful if the - resulting set of files is required to be interoperable with systems - which limit the length of file names. - No space is allowed between the @code{-k} and the numeric value. The numeric - value may be omitted in which case a default of @code{-k8}, - suitable for use - with DOS-like file systems, is used. If no @code{-k} switch - is present then - there is no limit on the length of file names. - - @item -p - @cindex @code{-p} (@code{gnatchop}) - Causes the file modification time stamp of the input file to be - preserved and used for the time stamp of the output file(s). This may be - useful for preserving coherency of time stamps in an enviroment where - @code{gnatchop} is used as part of a standard build process. - - @item -q - @cindex @code{-q} (@code{gnatchop}) - Causes output of informational messages indicating the set of generated - files to be suppressed. Warnings and error messages are unaffected. - - @item -r - @cindex @code{-r} (@code{gnatchop}) - @findex Source_Reference - Generate @code{Source_Reference} pragmas. Use this switch if the output - files are regarded as temporary and development is to be done in terms - of the original unchopped file. This switch causes - @code{Source_Reference} pragmas to be inserted into each of the - generated files to refers back to the original file name and line number. - The result is that all error messages refer back to the original - unchopped file. - In addition, the debugging information placed into the object file (when - the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also - refers back to this original file so that tools like profilers and - debuggers will give information in terms of the original unchopped file. - - If the original file to be chopped itself contains - a @code{Source_Reference} - pragma referencing a third file, then gnatchop respects - this pragma, and the generated @code{Source_Reference} pragmas - in the chopped file refer to the original file, with appropriate - line numbers. This is particularly useful when @code{gnatchop} - is used in conjunction with @code{gnatprep} to compile files that - contain preprocessing statements and multiple units. - - @item -v - @cindex @code{-v} (@code{gnatchop}) - Causes @code{gnatchop} to operate in verbose mode. The version - number and copyright notice are output, as well as exact copies of - the gnat1 commands spawned to obtain the chop control information. - - @item -w - @cindex @code{-w} (@code{gnatchop}) - Overwrite existing file names. Normally @code{gnatchop} regards it as a - fatal error if there is already a file with the same name as a - file it would otherwise output, in other words if the files to be - chopped contain duplicated units. This switch bypasses this - check, and causes all but the last instance of such duplicated - units to be skipped. - - @item --GCC=xxxx - @cindex @code{--GCC=} (@code{gnatchop}) - Specify the path of the GNAT parser to be used. When this switch is used, - no attempt is made to add the prefix to the GNAT parser executable. - @end table - - @node Examples of gnatchop Usage - @section Examples of @code{gnatchop} Usage - - @table @code - @item gnatchop -w hello_s.ada ichbiah/files - - Chops the source file @file{hello_s.ada}. The output files will be - placed in the directory @file{ichbiah/files}, - overwriting any - files with matching names in that directory (no files in the current - directory are modified). - - @item gnatchop archive - Chops the source file @file{archive} - into the current directory. One - useful application of @code{gnatchop} is in sending sets of sources - around, for example in email messages. The required sources are simply - concatenated (for example, using a Unix @code{cat} - command), and then - @code{gnatchop} is used at the other end to reconstitute the original - file names. - - @item gnatchop file1 file2 file3 direc - Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing - the resulting files in the directory @file{direc}. Note that if any units - occur more than once anywhere within this set of files, an error message - is generated, and no files are written. To override this check, use the - @code{-w} switch, - in which case the last occurrence in the last file will - be the one that is output, and earlier duplicate occurrences for a given - unit will be skipped. - @end table - - @node Configuration Pragmas - @chapter Configuration Pragmas - @cindex Configuration pragmas - @cindex Pragmas, configuration - - @noindent - In Ada 95, configuration pragmas include those pragmas described as - such in the Ada 95 Reference Manual, as well as - implementation-dependent pragmas that are configuration pragmas. See the - individual descriptions of pragmas in the GNAT Reference Manual for - details on these additional GNAT-specific configuration pragmas. Most - notably, the pragma @code{Source_File_Name}, which allows - specifying non-default names for source files, is a configuration - pragma. The following is a complete list of configuration pragmas - recognized by @code{GNAT}: - - @smallexample - Ada_83 - Ada_95 - C_Pass_By_Copy - Component_Alignment - Discard_Names - Elaboration_Checks - Eliminate - Extend_System - Extensions_Allowed - External_Name_Casing - Float_Representation - Initialize_Scalars - License - Locking_Policy - Long_Float - No_Run_Time - Normalize_Scalars - Polling - Propagate_Exceptions - Queuing_Policy - Ravenscar - Restricted_Run_Time - Restrictions - Reviewable - Source_File_Name - Style_Checks - Suppress - Task_Dispatching_Policy - Unsuppress - Use_VADS_Size - Warnings - Validity_Checks - @end smallexample - - @menu - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - @end menu - - @node Handling of Configuration Pragmas - @section Handling of Configuration Pragmas - - Configuration pragmas may either appear at the start of a compilation - unit, in which case they apply only to that unit, or they may apply to - all compilations performed in a given compilation environment. - - GNAT also provides the @code{gnatchop} utility to provide an automatic - way to handle configuration pragmas following the semantics for - compilations (that is, files with multiple units), described in the RM. - See section @pxref{Operating gnatchop in Compilation Mode} for details. - However, for most purposes, it will be more convenient to edit the - @file{gnat.adc} file that contains configuration pragmas directly, - as described in the following section. - - @node The Configuration Pragmas Files - @section The Configuration Pragmas Files - @cindex @file{gnat.adc} - - @noindent - In GNAT a compilation environment is defined by the current - directory at the time that a compile command is given. This current - directory is searched for a file whose name is @file{gnat.adc}. If - this file is present, it is expected to contain one or more - configuration pragmas that will be applied to the current compilation. - However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not - considered. - - Configuration pragmas may be entered into the @file{gnat.adc} file - either by running @code{gnatchop} on a source file that consists only of - configuration pragmas, or more conveniently by - direct editing of the @file{gnat.adc} file, which is a standard format - source file. - - In addition to @file{gnat.adc}, one additional file containing configuration - pragmas may be applied to the current compilation using the switch - @option{-gnatec}@var{path}. @var{path} must designate an existing file that - contains only configuration pragmas. These configuration pragmas are - in addition to those found in @file{gnat.adc} (provided @file{gnat.adc} - is present and switch @option{-gnatA} is not used). - - It is allowed to specify several switches @option{-gnatec}, however only - the last one on the command line will be taken into account. - - - @node Handling Arbitrary File Naming Conventions Using gnatname - @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} - @cindex Arbitrary File Naming Conventions - - @menu - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - @end menu - - @node Arbitrary File Naming Conventions - @section Arbitrary File Naming Conventions - - @noindent - The GNAT compiler must be able to know the source file name of a compilation unit. - When using the standard GNAT default file naming conventions (@code{.ads} for specs, - @code{.adb} for bodies), the GNAT compiler does not need additional information. - - @noindent - When the source file names do not follow the standard GNAT default file naming - conventions, the GNAT compiler must be given additional information through - a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file. - When the non standard file naming conventions are well-defined, a small number of - pragmas @code{Source_File_Name} specifying a naming pattern - (see @ref{Alternative File Naming Schemes}) may be sufficient. However, - if the file naming conventions are irregular or arbitrary, a number - of pragma @code{Source_File_Name} for individual compilation units must be defined. - To help maintain the correspondence between compilation unit names and - source file names within the compiler, - GNAT provides a tool @code{gnatname} to generate the required pragmas for a - set of files. - - @node Running gnatname - @section Running @code{gnatname} - - @noindent - The usual form of the @code{gnatname} command is - - @smallexample - $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}] - @end smallexample - - @noindent - All of the arguments are optional. If invoked without any argument, - @code{gnatname} will display its usage. - - @noindent - When used with at least one naming pattern, @code{gnatname} will attempt to - find all the compilation units in files that follow at least one of the - naming patterns. To find these compilation units, - @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all - regular files. - - @noindent - One or several Naming Patterns may be given as arguments to @code{gnatname}. - Each Naming Pattern is enclosed between double quotes. - A Naming Pattern is a regular expression similar to the wildcard patterns - used in file names by the Unix shells or the DOS prompt. - - @noindent - Examples of Naming Patterns are - - @smallexample - "*.[12].ada" - "*.ad[sb]*" - "body_*" "spec_*" - @end smallexample - - @noindent - For a more complete description of the syntax of Naming Patterns, see the second kind - of regular expressions described in @file{g-regexp.ads} (the "Glob" regular - expressions). - - @noindent - When invoked with no switches, @code{gnatname} will create a configuration - pragmas file @file{gnat.adc} in the current working directory, with pragmas - @code{Source_File_Name} for each file that contains a valid Ada unit. - - @node Switches for gnatname - @section Switches for @code{gnatname} - - @noindent - Switches for @code{gnatname} must precede any specified Naming Pattern. - - @noindent - You may specify any of the following switches to @code{gnatname}: - - @table @code - - @item -c@file{file} - @cindex @code{-c} (@code{gnatname}) - Create a configuration pragmas file @file{file} (instead of the default - @file{gnat.adc}). There may be zero, one or more space between @code{-c} and - @file{file}. @file{file} may include directory information. @file{file} must be - writeable. There may be only one switch @code{-c}. When a switch @code{-c} is - specified, no switch @code{-P} may be specified (see below). - - @item -d@file{dir} - @cindex @code{-d} (@code{gnatname}) - Look for source files in directory @file{dir}. There may be zero, one or more spaces - between @code{-d} and @file{dir}. When a switch @code{-d} is specified, - the current working directory will not be searched for source files, unless it - is explictly - specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be - specified. If @file{dir} is a relative path, it is relative to the directory of - the configuration pragmas file specified with switch @code{-c}, or to the directory - of the project file specified with switch @code{-P} or, if neither switch @code{-c} - nor switch @code{-P} are specified, it is relative to the current working - directory. The directory - specified with switch @code{-c} must exist and be readable. - - @item -D@file{file} - @cindex @code{-D} (@code{gnatname}) - Look for source files in all directories listed in text file @file{file}. There may be - zero, one or more spaces between @code{-d} and @file{dir}. @file{file} - must be an existing, readable text file. Each non empty line in @file{file} must be - a directory. Specifying switch @code{-D} is equivalent to specifying as many switches - @code{-d} as there are non empty lines in @file{file}. - - @item -h - @cindex @code{-h} (@code{gnatname}) - Output usage (help) information. The output is written to @file{stdout}. - - @item -P@file{proj} - @cindex @code{-P} (@code{gnatname}) - Create or update project file @file{proj}. There may be zero, one or more space - between @code{-P} and @file{proj}. @file{proj} may include directory information. - @file{proj} must be writeable. There may be only one switch @code{-P}. - When a switch @code{-P} is specified, no switch @code{-c} may be specified. - - @item -v - @cindex @code{-v} (@code{gnatname}) - Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes - name of the file written, the name of the directories to search and, for each file - in those directories whose name matches at least one of the Naming Patterns, an - indication of whether the file contains a unit, and if so the name of the unit. - - @item -v -v - Very Verbose mode. In addition to the output produced in verbose mode, for each file - in the searched directories whose name matches none of the Naming Patterns, an - indication is given that there is no match. - - @item -x@file{pattern} - Excluded patterns. Using this switch, it is possible to exclude some files - that would match the name patterns. For example, - @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files - with the @file{.ada} extension, except those whose names end with - @file{_nt.ada}. - - @end table - - @node Examples of gnatname Usage - @section Examples of @code{gnatname} Usage - - @smallexample - $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" - @end smallexample - - In this example, the directory @file{/home/me} must already exist and be - writeable. In addition, the directory @file{/home/me/sources} (specified by - @code{-d sources}) must exist and be readable. Note the optional spaces after - @code{-c} and @code{-d}. - - @smallexample - $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" - @end smallexample - - Note that several switches @code{-d} may be used, even in conjunction with one - or several switches @code{-D}. Several Naming Patterns and one excluded pattern - are used in this example. - - - @c ***************************************** - @c * G N A T P r o j e c t M a n a g e r * - @c ***************************************** - @node GNAT Project Manager - @chapter GNAT Project Manager - - @menu - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - @end menu - - - @c **************** - @c * Introduction * - @c **************** - - @node Introduction - @section Introduction - - @noindent - This chapter describes GNAT's @emph{Project Manager}, a facility that - lets you configure various properties for a collection of source files. In - particular, you can specify: - @itemize @bullet - @item - The directory or set of directories containing the source files, and/or the - names of the specific source files themselves - @item - The directory in which the compiler's output - (@file{ALI} files, object files, tree files) will be placed - @item - The directory in which the executable programs will be placed - @item - Switch settings for any of the project-enabled tools (@command{gnatmake}, - compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind}); - you can apply these settings either globally or to individual units - @item - The source files containing the main subprogram(s) to be built - @item - The source programming language(s) (currently Ada and/or C) - @item - Source file naming conventions; you can specify these either globally or for - individual units - @end itemize - - @menu - * Project Files:: - @end menu - - @node Project Files - @subsection Project Files - - @noindent - A @dfn{project} is a specific set of values for these properties. You can - define a project's settings in a @dfn{project file}, a text file with an - Ada-like syntax; a property value is either a string or a list of strings. - Properties that are not explicitly set receive default values. A project - file may interrogate the values of @dfn{external variables} (user-defined - command-line switches or environment variables), and it may specify property - settings conditionally, based on the value of such variables. - - In simple cases, a project's source files depend only on other source files - in the same project, or on the predefined libraries. ("Dependence" is in - the technical sense; for example, one Ada unit "with"ing another.) However, - the Project Manager also allows much more sophisticated arrangements, - with the source files in one project depending on source files in other - projects: - @itemize @bullet - @item - One project can @emph{import} other projects containing needed source files. - @item - You can organize GNAT projects in a hierarchy: a @emph{child} project - can extend a @emph{parent} project, inheriting the parent's source files and - optionally overriding any of them with alternative versions - @end itemize - - @noindent - More generally, the Project Manager lets you structure large development - efforts into hierarchical subsystems, with build decisions deferred to the - subsystem level and thus different compilation environments (switch settings) - used for different subsystems. - - The Project Manager is invoked through the @option{-P@emph{projectfile}} - switch to @command{gnatmake} or to the @command{gnat} front driver. - If you want to define (on the command line) an external variable that is - queried by the project file, additionally use the - @option{-X@emph{vbl}=@emph{value}} switch. - The Project Manager parses and interprets the project file, and drives the - invoked tool based on the project settings. - - The Project Manager supports a wide range of development strategies, - for systems of all sizes. Some typical practices that are easily handled: - @itemize @bullet - @item - Using a common set of source files, but generating object files in different - directories via different switch settings - @item - Using a mostly-shared set of source files, but with different versions of - some unit or units - @end itemize - - @noindent - The destination of an executable can be controlled inside a project file - using the @option{-o} switch. In the absence of such a switch either inside - the project file or on the command line, any executable files generated by - @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified - in the project file. If no @code{Exec_Dir} is specified, they will be placed - in the object directory of the project. - - You can use project files to achieve some of the effects of a source - versioning system (for example, defining separate projects for - the different sets of sources that comprise different releases) but the - Project Manager is independent of any source configuration management tools - that might be used by the developers. - - The next section introduces the main features of GNAT's project facility - through a sequence of examples; subsequent sections will present the syntax - and semantics in more detail. - - - @c ***************************** - @c * Examples of Project Files * - @c ***************************** - - @node Examples of Project Files - @section Examples of Project Files - @noindent - This section illustrates some of the typical uses of project files and - explains their basic structure and behavior. - - @menu - * Common Sources with Different Switches and Different Output Directories:: - * Using External Variables:: - * Importing Other Projects:: - * Extending a Project:: - @end menu - - @node Common Sources with Different Switches and Different Output Directories - @subsection Common Sources with Different Switches and Different Output Directories - - @menu - * Source Files:: - * Specifying the Object Directory:: - * Specifying the Exec Directory:: - * Project File Packages:: - * Specifying Switch Settings:: - * Main Subprograms:: - * Source File Naming Conventions:: - * Source Language(s):: - @end menu - - @noindent - Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and - @file{proc.adb} are in the @file{/common} directory. The file - @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s - package @code{Pack}. We want to compile these source files under two sets - of switches: - @itemize @bullet - @item - When debugging, we want to pass the @option{-g} switch to @command{gnatmake}, - and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the - compiler; the compiler's output is to appear in @file{/common/debug} - @item - When preparing a release version, we want to pass the @option{-O2} switch to - the compiler; the compiler's output is to appear in @file{/common/release} - @end itemize - - @noindent - The GNAT project files shown below, respectively @file{debug.gpr} and - @file{release.gpr} in the @file{/common} directory, achieve these effects. - - Diagrammatically: - @smallexample - @group - /common - debug.gpr - release.gpr - pack.ads - pack.adb - proc.adb - @end group - @group - /common/debug @{-g, -gnata, -gnato, -gnatE@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @group - /common/release @{-O2@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @end smallexample - Here are the project files: - @smallexample - @group - project Debug is - for Object_Dir use "debug"; - for Main use ("proc"); - - package Builder is - for Default_Switches ("Ada") use ("-g"); - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") - use ("-fstack-check", "-gnata", "-gnato", "-gnatE"); - end Compiler; - end Debug; - @end group - @end smallexample - - @smallexample - @group - project Release is - for Object_Dir use "release"; - for Exec_Dir use "."; - for Main use ("proc"); - - package Compiler is - for Default_Switches ("Ada") use ("-O2"); - end Compiler; - end Release; - @end group - @end smallexample - - @noindent - The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case - insensitive), and analogously the project defined by @file{release.gpr} is - @code{"Release"}. For consistency the file should have the same name as the - project, and the project file's extension should be @code{"gpr"}. These - conventions are not required, but a warning is issued if they are not followed. - - If the current directory is @file{/temp}, then the command - @smallexample - gnatmake -P/common/debug.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/debug}, and the @code{proc} - executable also in @file{/common/debug}, using the switch settings defined in - the project file. - - Likewise, the command - @smallexample - gnatmake -P/common/release.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/release}, and the @code{proc} - executable in @file{/common}, using the switch settings from the project file. - - @node Source Files - @unnumberedsubsubsec Source Files - - @noindent - If a project file does not explicitly specify a set of source directories or - a set of source files, then by default the project's source files are the - Ada source files in the project file directory. Thus @file{pack.ads}, - @file{pack.adb}, and @file{proc.adb} are the source files for both projects. - - @node Specifying the Object Directory - @unnumberedsubsubsec Specifying the Object Directory - - @noindent - Several project properties are modeled by Ada-style @emph{attributes}; - you define the property by supplying the equivalent of an Ada attribute - definition clause in the project file. - A project's object directory is such a property; the corresponding - attribute is @code{Object_Dir}, and its value is a string expression. A - directory may be specified either as absolute or as relative; in the latter - case, it is relative to the project file directory. Thus the compiler's - output is directed to @file{/common/debug} (for the @code{Debug} project) - and to @file{/common/release} (for the @code{Release} project). If - @code{Object_Dir} is not specified, then the default is the project file - directory. - - @node Specifying the Exec Directory - @unnumberedsubsubsec Specifying the Exec Directory - - @noindent - A project's exec directory is another property; the corresponding - attribute is @code{Exec_Dir}, and its value is also a string expression, - either specified as relative or absolute. If @code{Exec_Dir} is not specified, - then the default is the object directory (which may also be the project file - directory if attribute @code{Object_Dir} is not specified). Thus the executable - is placed in @file{/common/debug} for the @code{Debug} project (attribute - @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release} - project. - - @node Project File Packages - @unnumberedsubsubsec Project File Packages - - @noindent - A GNAT tool integrated with the Project Manager is modeled by a - corresponding package in the project file. - The @code{Debug} project defines the packages @code{Builder} - (for @command{gnatmake}) and @code{Compiler}; - the @code{Release} project defines only the @code{Compiler} package. - - The Ada package syntax is not to be taken literally. Although packages in - project files bear a surface resemblance to packages in Ada source code, the - notation is simply a way to convey a grouping of properties for a named - entity. Indeed, the package names permitted in project files are restricted - to a predefined set, corresponding to the project-aware tools, and the contents - of packages are limited to a small set of constructs. - The packages in the example above contain attribute definitions. - - - @node Specifying Switch Settings - @unnumberedsubsubsec Specifying Switch Settings - - @noindent - Switch settings for a project-aware tool can be specified through attributes - in the package corresponding to the tool. - The example above illustrates one of the relevant attributes, - @code{Default_Switches}, defined in the packages in both project files. - Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is - known as an @emph{associative array}. When you define this attribute, you must - supply an "index" (a literal string), and the effect of the attribute - definition is to set the value of the "array" at the specified "index". - For the @code{Default_Switches} attribute, the index is a programming - language (in our case, Ada) , and the value specified (after @code{use}) - must be a list of string expressions. - - The attributes permitted in project files are restricted to a predefined set. - Some may appear at project level, others in packages. - For any attribute that is an associate array, the index must always be a - literal string, but the restrictions on this string (e.g., a file name or a - language name) depend on the individual attribute. - Also depending on the attribute, its specified value will need to be either a - string or a string list. - - In the @code{Debug} project, we set the switches for two tools, - @command{gnatmake} and the compiler, and thus we include corresponding - packages, with each package defining the @code{Default_Switches} attribute - with index @code{"Ada"}. - Note that the package corresponding to - @command{gnatmake} is named @code{Builder}. The @code{Release} project is - similar, but with just the @code{Compiler} package. - - In project @code{Debug} above the switches starting with @option{-gnat} that - are specified in package @code{Compiler} could have been placed in package - @code{Builder}, since @command{gnatmake} transmits all such switches to the - compiler. - - @node Main Subprograms - @unnumberedsubsubsec Main Subprograms - - @noindent - One of the properties of a project is its list of main subprograms (actually - a list of names of source files containing main subprograms, with the file - extension optional. This property is captured in the @code{Main} attribute, - whose value is a list of strings. If a project defines the @code{Main} - attribute, then you do not need to identify the main subprogram(s) when - invoking @command{gnatmake} (see @ref{gnatmake and Project Files}). - - @node Source File Naming Conventions - @unnumberedsubsubsec Source File Naming Conventions - - @noindent - Since the project files do not specify any source file naming conventions, - the GNAT defaults are used. The mechanism for defining source file naming - conventions -- a package named @code{Naming} -- will be described below - (@pxref{Naming Schemes}). - - @node Source Language(s) - @unnumberedsubsubsec Source Language(s) - - @noindent - Since the project files do not specify a @code{Languages} attribute, by - default the GNAT tools assume that the language of the project file is Ada. - More generally, a project can comprise source files - in Ada, C, and/or other languages. - - @node Using External Variables - @subsection Using External Variables - - @noindent - Instead of supplying different project files for debug and release, we can - define a single project file that queries an external variable (set either - on the command line or via an environment variable) in order to - conditionally define the appropriate settings. Again, assume that the - source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are - located in directory @file{/common}. The following project file, - @file{build.gpr}, queries the external variable named @code{STYLE} and - defines an object directory and switch settings based on whether the value - is @code{"deb"} (debug) or @code{"rel"} (release), where the default is - @code{"deb"}. - - @smallexample - @group - project Build is - for Main use ("proc"); - - type Style_Type is ("deb", "rel"); - Style : Style_Type := external ("STYLE", "deb"); - - case Style is - when "deb" => - for Object_Dir use "debug"; - - when "rel" => - for Object_Dir use "release"; - for Exec_Dir use "."; - end case; - @end group - - @group - package Builder is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-g"); - end case; - - end Builder; - @end group - - @group - package Compiler is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE"); - - when "rel" => - for Default_Switches ("Ada") use ("-O2"); - end case; - - end Compiler; - - end Build; - @end group - @end smallexample - - @noindent - @code{Style_Type} is an example of a @emph{string type}, which is the project - file analog of an Ada enumeration type but containing string literals rather - than identifiers. @code{Style} is declared as a variable of this type. - - The form @code{external("STYLE", "deb")} is known as an - @emph{external reference}; its first argument is the name of an - @emph{external variable}, and the second argument is a default value to be - used if the external variable doesn't exist. You can define an external - variable on the command line via the @option{-X} switch, or you can use an - environment variable as an external variable. - - Each @code{case} construct is expanded by the Project Manager based on the - value of @code{Style}. Thus the command - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=deb - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{debug.gpr} in the earlier example. So is the command - @smallexample - gnatmake -P/common/build.gpr - @end smallexample - - @noindent - since @code{"deb"} is the default for @code{STYLE}. - - Analogously, - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=rel - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{release.gpr} in the earlier example. - - - @node Importing Other Projects - @subsection Importing Other Projects - - @noindent - A compilation unit in a source file in one project may depend on compilation - units in source files in other projects. To obtain this behavior, the - dependent project must @emph{import} the projects containing the needed source - files. This effect is embodied in syntax similar to an Ada @code{with} clause, - but the "with"ed entities are strings denoting project files. - - As an example, suppose that the two projects @code{GUI_Proj} and - @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and - @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm}, - respectively. Assume that the source files for @code{GUI_Proj} are - @file{gui.ads} and @file{gui.adb}, and that the source files for - @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of - files located in its respective project file directory. Diagrammatically: - - @smallexample - @group - /gui - gui_proj.gpr - gui.ads - gui.adb - @end group - - @group - /comm - comm_proj.gpr - comm.ads - comm.adb - @end group - @end smallexample - - @noindent - We want to develop an application in directory @file{/app} that "with"s the - packages @code{GUI} and @code{Comm}, using the properties of the - corresponding project files (e.g. the switch settings and object directory). - Skeletal code for a main procedure might be something like the following: - - @smallexample - @group - with GUI, Comm; - procedure App_Main is - ... - begin - ... - end App_Main; - @end group - @end smallexample - - @noindent - Here is a project file, @file{app_proj.gpr}, that achieves the desired - effect: - - @smallexample - @group - with "/gui/gui_proj", "/comm/comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Building an executable is achieved through the command: - @smallexample - gnatmake -P/app/app_proj - @end smallexample - @noindent - which will generate the @code{app_main} executable in the directory where - @file{app_proj.gpr} resides. - - If an imported project file uses the standard extension (@code{gpr}) then - (as illustrated above) the @code{with} clause can omit the extension. - - Our example specified an absolute path for each imported project file. - Alternatively, you can omit the directory if either - @itemize @bullet - @item - The imported project file is in the same directory as the importing project - file, or - @item - You have defined an environment variable @code{ADA_PROJECT_PATH} that - includes the directory containing the needed project file. - @end itemize - - @noindent - Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and - @file{/comm}, then our project file @file{app_proj.gpr} could be written as - follows: - - @smallexample - @group - with "gui_proj", "comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Importing other projects raises the possibility of ambiguities. For - example, the same unit might be present in different imported projects, or - it might be present in both the importing project and an imported project. - Both of these conditions are errors. Note that in the current version of - the Project Manager, it is illegal to have an ambiguous unit even if the - unit is never referenced by the importing project. This restriction may be - relaxed in a future release. - - @node Extending a Project - @subsection Extending a Project - - @noindent - A common situation in large software systems is to have multiple - implementations for a common interface; in Ada terms, multiple versions of a - package body for the same specification. For example, one implementation - might be safe for use in tasking programs, while another might only be used - in sequential applications. This can be modeled in GNAT using the concept - of @emph{project extension}. If one project (the "child") @emph{extends} - another project (the "parent") then by default all source files of the - parent project are inherited by the child, but the child project can - override any of the parent's source files with new versions, and can also - add new files. This facility is the project analog of extension in - Object-Oriented Programming. Project hierarchies are permitted (a child - project may be the parent of yet another project), and a project that - inherits one project can also import other projects. - - As an example, suppose that directory @file{/seq} contains the project file - @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb}, - and @file{proc.adb}: - - @smallexample - @group - /seq - pack.ads - pack.adb - proc.adb - seq_proj.gpr - @end group - @end smallexample - - @noindent - Note that the project file can simply be empty (that is, no attribute or - package is defined): - - @smallexample - @group - project Seq_Proj is - end Seq_Proj; - @end group - @end smallexample - - @noindent - implying that its source files are all the Ada source files in the project - directory. - - Suppose we want to supply an alternate version of @file{pack.adb}, in - directory @file{/tasking}, but use the existing versions of @file{pack.ads} - and @file{proc.adb}. We can define a project @code{Tasking_Proj} that - inherits @code{Seq_Proj}: - - @smallexample - @group - /tasking - pack.adb - tasking_proj.gpr - @end group - - @group - project Tasking_Proj extends "/seq/seq_proj" is - end Tasking_Proj; - @end group - @end smallexample - - @noindent - The version of @file{pack.adb} used in a build depends on which project file - is specified. - - Note that we could have designed this using project import rather than - project inheritance; a @code{base} project would contain the sources for - @file{pack.ads} and @file{proc.adb}, a sequential project would import - @code{base} and add @file{pack.adb}, and likewise a tasking project would - import @code{base} and add a different version of @file{pack.adb}. The - choice depends on whether other sources in the original project need to be - overridden. If they do, then project extension is necessary, otherwise, - importing is sufficient. - - - @c *********************** - @c * Project File Syntax * - @c *********************** - - @node Project File Syntax - @section Project File Syntax - - @menu - * Basic Syntax:: - * Packages:: - * Expressions:: - * String Types:: - * Variables:: - * Attributes:: - * Associative Array Attributes:: - * case Constructions:: - @end menu - - @noindent - This section describes the structure of project files. - - A project may be an @emph{independent project}, entirely defined by a single - project file. Any Ada source file in an independent project depends only - on the predefined library and other Ada source files in the same project. - - @noindent - A project may also @dfn{depend on} other projects, in either or both of the following ways: - @itemize @bullet - @item It may import any number of projects - @item It may extend at most one other project - @end itemize - - @noindent - The dependence relation is a directed acyclic graph (the subgraph reflecting - the "extends" relation is a tree). - - A project's @dfn{immediate sources} are the source files directly defined by - that project, either implicitly by residing in the project file's directory, - or explicitly through any of the source-related attributes described below. - More generally, a project @var{proj}'s @dfn{sources} are the immediate sources - of @var{proj} together with the immediate sources (unless overridden) of any - project on which @var{proj} depends (either directly or indirectly). - - @node Basic Syntax - @subsection Basic Syntax - - @noindent - As seen in the earlier examples, project files have an Ada-like syntax. - The minimal project file is: - @smallexample - @group - project Empty is - - end Empty; - @end group - @end smallexample - - @noindent - The identifier @code{Empty} is the name of the project. - This project name must be present after the reserved - word @code{end} at the end of the project file, followed by a semi-colon. - - Any name in a project file, such as the project name or a variable name, - has the same syntax as an Ada identifier. - - The reserved words of project files are the Ada reserved words plus - @code{extends}, @code{external}, and @code{project}. Note that the only Ada - reserved words currently used in project file syntax are: - - @itemize @bullet - @item - @code{case} - @item - @code{end} - @item - @code{for} - @item - @code{is} - @item - @code{others} - @item - @code{package} - @item - @code{renames} - @item - @code{type} - @item - @code{use} - @item - @code{when} - @item - @code{with} - @end itemize - - @noindent - Comments in project files have the same syntax as in Ada, two consecutives - hyphens through the end of the line. - - @node Packages - @subsection Packages - - @noindent - A project file may contain @emph{packages}. The name of a package must be one - of the identifiers (case insensitive) from a predefined list, and a package - with a given name may only appear once in a project file. The predefined list - includes the following packages: - - @itemize @bullet - @item - @code{Naming} - @item - @code{Builder} - @item - @code{Compiler} - @item - @code{Binder} - @item - @code{Linker} - @item - @code{Finder} - @item - @code{Cross_Reference} - @item - @code{gnatls} - @end itemize - - @noindent - (The complete list of the package names and their attributes can be found - in file @file{prj-attr.adb}). - - @noindent - In its simplest form, a package may be empty: - - @smallexample - @group - project Simple is - package Builder is - end Builder; - end Simple; - @end group - @end smallexample - - @noindent - A package may contain @emph{attribute declarations}, - @emph{variable declarations} and @emph{case constructions}, as will be - described below. - - When there is ambiguity between a project name and a package name, - the name always designates the project. To avoid possible confusion, it is - always a good idea to avoid naming a project with one of the - names allowed for packages or any name that starts with @code{gnat}. - - - @node Expressions - @subsection Expressions - - @noindent - An @emph{expression} is either a @emph{string expression} or a - @emph{string list expression}. - - A @emph{string expression} is either a @emph{simple string expression} or a - @emph{compound string expression}. - - A @emph{simple string expression} is one of the following: - @itemize @bullet - @item A literal string; e.g.@code{"comm/my_proj.gpr"} - @item A string-valued variable reference (see @ref{Variables}) - @item A string-valued attribute reference (see @ref{Attributes}) - @item An external reference (see @ref{External References in Project Files}) - @end itemize - - @noindent - A @emph{compound string expression} is a concatenation of string expressions, - using @code{"&"} - @smallexample - Path & "/" & File_Name & ".ads" - @end smallexample - - @noindent - A @emph{string list expression} is either a - @emph{simple string list expression} or a - @emph{compound string list expression}. - - A @emph{simple string list expression} is one of the following: - @itemize @bullet - @item A parenthesized list of zero or more string expressions, separated by commas - @smallexample - File_Names := (File_Name, "gnat.adc", File_Name & ".orig"); - Empty_List := (); - @end smallexample - @item A string list-valued variable reference - @item A string list-valued attribute reference - @end itemize - - @noindent - A @emph{compound string list expression} is the concatenation (using - @code{"&"}) of a simple string list expression and an expression. Note that - each term in a compound string list expression, except the first, may be - either a string expression or a string list expression. - - @smallexample - @group - File_Name_List := () & File_Name; -- One string in this list - Extended_File_Name_List := File_Name_List & (File_Name & ".orig"); - -- Two strings - Big_List := File_Name_List & Extended_File_Name_List; - -- Concatenation of two string lists: three strings - Illegal_List := "gnat.adc" & Extended_File_Name_List; - -- Illegal: must start with a string list - @end group - @end smallexample - - - @node String Types - @subsection String Types - - @noindent - The value of a variable may be restricted to a list of string literals. - The restricted list of string literals is given in a - @emph{string type declaration}. - - Here is an example of a string type declaration: - - @smallexample - type OS is ("NT, "nt", "Unix", "Linux", "other OS"); - @end smallexample - - @noindent - Variables of a string type are called @emph{typed variables}; all other - variables are called @emph{untyped variables}. Typed variables are - particularly useful in @code{case} constructions - (see @ref{case Constructions}). - - A string type declaration starts with the reserved word @code{type}, followed - by the name of the string type (case-insensitive), followed by the reserved - word @code{is}, followed by a parenthesized list of one or more string literals - separated by commas, followed by a semicolon. - - The string literals in the list are case sensitive and must all be different. - They may include any graphic characters allowed in Ada, including spaces. - - A string type may only be declared at the project level, not inside a package. - - A string type may be referenced by its name if it has been declared in the same - project file, or by its project name, followed by a dot, - followed by the string type name. - - - @node Variables - @subsection Variables - - @noindent - A variable may be declared at the project file level, or in a package. - Here are some examples of variable declarations: - - @smallexample - @group - This_OS : OS := external ("OS"); -- a typed variable declaration - That_OS := "Linux"; -- an untyped variable declaration - @end group - @end smallexample - - @noindent - A @emph{typed variable declaration} includes the variable name, followed by a colon, - followed by the name of a string type, followed by @code{:=}, followed by - a simple string expression. - - An @emph{untyped variable declaration} includes the variable name, - followed by @code{:=}, followed by an expression. Note that, despite the - terminology, this form of "declaration" resembles more an assignment - than a declaration in Ada. It is a declaration in several senses: - @itemize @bullet - @item - The variable name does not need to be defined previously - @item - The declaration establishes the @emph{kind} (string versus string list) of the - variable, and later declarations of the same variable need to be consistent - with this - @end itemize - - @noindent - A string variable declaration (typed or untyped) declares a variable - whose value is a string. This variable may be used as a string expression. - @smallexample - File_Name := "readme.txt"; - Saved_File_Name := File_Name & ".saved"; - @end smallexample - - @noindent - A string list variable declaration declares a variable whose value is a list - of strings. The list may contain any number (zero or more) of strings. - - @smallexample - Empty_List := (); - List_With_One_Element := ("-gnaty"); - List_With_Two_Elements := List_With_One_Element & "-gnatg"; - Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada" - "pack2.ada", "util_.ada", "util.ada"); - @end smallexample - - @noindent - The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable. - - The same untyped variable may be declared several times. - In this case, the new value replaces the old one, - and any subsequent reference to the variable uses the new value. - However, as noted above, if a variable has been declared as a string, all subsequent - declarations must give it a string value. Similarly, if a variable has - been declared as a string list, all subsequent declarations - must give it a string list value. - - A @emph{variable reference} may take several forms: - - @itemize @bullet - @item The simple variable name, for a variable in the current package (if any) or in the current project - @item A context name, followed by a dot, followed by the variable name. - @end itemize - - @noindent - A @emph{context} may be one of the following: - - @itemize @bullet - @item The name of an existing package in the current project - @item The name of an imported project of the current project - @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly) - @item An imported/parent project name, followed by a dot, followed by a package name - @end itemize - - @noindent - A variable reference may be used in an expression. - - - @node Attributes - @subsection Attributes - - @noindent - A project (and its packages) may have @emph{attributes} that define the project's properties. - Some attributes have values that are strings; - others have values that are string lists. - - There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays} - (see @ref{Associative Array Attributes}). - - The names of the attributes are restricted; there is a list of project - attributes, and a list of package attributes for each package. - The names are not case sensitive. - - The project attributes are as follows (all are simple attributes): - - @multitable @columnfractions .4 .3 - @item @emph{Attribute Name} - @tab @emph{Value} - @item @code{Source_Files} - @tab string list - @item @code{Source_Dirs} - @tab string list - @item @code{Source_List_File} - @tab string - @item @code{Object_Dir} - @tab string - @item @code{Exec_Dir} - @tab string - @item @code{Main} - @tab string list - @item @code{Languages} - @tab string list - @item @code{Library_Dir} - @tab string - @item @code{Library_Name} - @tab string - @item @code{Library_Kind} - @tab string - @item @code{Library_Elaboration} - @tab string - @item @code{Library_Version} - @tab string - @end multitable - - @noindent - The attributes for package @code{Naming} are as follows - (see @ref{Naming Schemes}): - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Specification_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Implementation_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Separate_Suffix} - @tab simple attribute - @tab n/a - @tab string - @item @code{Casing} - @tab simple attribute - @tab n/a - @tab string - @item @code{Dot_Replacement} - @tab simple attribute - @tab n/a - @tab string - @item @code{Specification} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Implementation} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Specification_Exceptions} - @tab associative array - @tab language name - @tab string list - @item @code{Implementation_Exceptions} - @tab associative array - @tab language name - @tab string list - @end multitable - - @noindent - The attributes for package @code{Builder}, @code{Compiler}, @code{Binder}, - @code{Linker}, @code{Cross_Reference}, and @code{Finder} - are as follows (see @ref{Switches and Project Files}). - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Default_Switches} - @tab associative array - @tab language name - @tab string list - @item @code{Switches} - @tab associative array - @tab file name - @tab string list - @end multitable - - @noindent - In addition, package @code{Builder} has a single string attribute - @code{Local_Configuration_Pragmas} and package @code{Builder} has a single - string attribute @code{Global_Configuration_Pragmas}. - - @noindent - The attribute for package @code{Glide} are not documented: they are for - internal use only. - - @noindent - Each simple attribute has a default value: the empty string (for string-valued - attributes) and the empty list (for string list-valued attributes). - - Similar to variable declarations, an attribute declaration defines a new value - for an attribute. - - Examples of simple attribute declarations: - - @smallexample - for Object_Dir use "objects"; - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - @noindent - A @dfn{simple attribute declaration} starts with the reserved word @code{for}, - followed by the name of the attribute, followed by the reserved word - @code{use}, followed by an expression (whose kind depends on the attribute), - followed by a semicolon. - - Attributes may be referenced in expressions. - The general form for such a reference is @code{'}: - the entity for which the attribute is defined, - followed by an apostrophe, followed by the name of the attribute. - For associative array attributes, a litteral string between parentheses - need to be supplied as index. - - Examples are: - - @smallexample - project'Object_Dir - Naming'Dot_Replacement - Imported_Project'Source_Dirs - Imported_Project.Naming'Casing - Builder'Default_Switches("Ada") - @end smallexample - - @noindent - The entity may be: - @itemize @bullet - @item @code{project} for an attribute of the current project - @item The name of an existing package of the current project - @item The name of an imported project - @item The name of a parent project (extended by the current project) - @item An imported/parent project name, followed by a dot, - followed by a package name - @end itemize - - @noindent - Example: - @smallexample - @group - project Prj is - for Source_Dirs use project'Source_Dirs & "units"; - for Source_Dirs use project'Source_Dirs & "test/drivers" - end Prj; - @end group - @end smallexample - - @noindent - In the first attribute declaration, initially the attribute @code{Source_Dirs} - has the default value: an empty string list. After this declaration, - @code{Source_Dirs} is a string list of one element: "units". - After the second attribute declaration @code{Source_Dirs} is a string list of - two elements: "units" and "test/drivers". - - Note: this example is for illustration only. In practice, - the project file would contain only one attribute declaration: - - @smallexample - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - - @node Associative Array Attributes - @subsection Associative Array Attributes - - @noindent - Some attributes are defined as @emph{associative arrays}. An associative - array may be regarded as a function that takes a string as a parameter - and delivers a string or string list value as its result. - - Here are some examples of associative array attribute declarations: - - @smallexample - for Implementation ("main") use "Main.ada"; - for Switches ("main.ada") use ("-v", "-gnatv"); - for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g"; - @end smallexample - - @noindent - Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the - attribute, replacing the previous setting. - - - @node case Constructions - @subsection @code{case} Constructions - - @noindent - A @code{case} construction is used in a project file to effect conditional - behavior. - Here is a typical example: - - @smallexample - @group - project MyProj is - type OS_Type is ("Linux", "Unix", "NT", "VMS"); - - OS : OS_Type := external ("OS", "Linux"); - @end group - - @group - package Compiler is - case OS is - when "Linux" | "Unix" => - for Default_Switches ("Ada") use ("-gnath"); - when "NT" => - for Default_Switches ("Ada") use ("-gnatP"); - when others => - end case; - end Compiler; - end MyProj; - @end group - @end smallexample - - @noindent - The syntax of a @code{case} construction is based on the Ada case statement - (although there is no @code{null} construction for empty alternatives). - - Following the reserved word @code{case} there is the case variable (a typed - string variable), the reserved word @code{is}, and then a sequence of one or - more alternatives. - Each alternative comprises the reserved word @code{when}, either a list of - literal strings separated by the @code{"|"} character or the reserved word - @code{others}, and the @code{"=>"} token. - Each literal string must belong to the string type that is the type of the - case variable. - An @code{others} alternative, if present, must occur last. - The @code{end case;} sequence terminates the case construction. - - After each @code{=>}, there are zero or more constructions. The only - constructions allowed in a case construction are other case constructions and - attribute declarations. String type declarations, variable declarations and - package declarations are not allowed. - - The value of the case variable is often given by an external reference - (see @ref{External References in Project Files}). - - - @c **************************************** - @c * Objects and Sources in Project Files * - @c **************************************** - - @node Objects and Sources in Project Files - @section Objects and Sources in Project Files - - @menu - * Object Directory:: - * Exec Directory:: - * Source Directories:: - * Source File Names:: - @end menu - - @noindent - Each project has exactly one object directory and one or more source - directories. The source directories must contain at least one source file, - unless the project file explicitly specifies that no source files are present - (see @ref{Source File Names}). - - - @node Object Directory - @subsection Object Directory - - @noindent - The object directory for a project is the directory containing the compiler's - output (such as @file{ALI} files and object files) for the project's immediate - sources. Note that for inherited sources (when extending a parent project) the - parent project's object directory is used. - - The object directory is given by the value of the attribute @code{Object_Dir} - in the project file. - - @smallexample - for Object_Dir use "objects"; - @end smallexample - - @noindent - The attribute @var{Object_Dir} has a string value, the path name of the object - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be readable and writable. - - By default, when the attribute @code{Object_Dir} is not given an explicit value - or when its value is the empty string, the object directory is the same as the - directory containing the project file. - - - @node Exec Directory - @subsection Exec Directory - - @noindent - The exec directory for a project is the directory containing the executables - for the project's main subprograms. - - The exec directory is given by the value of the attribute @code{Exec_Dir} - in the project file. - - @smallexample - for Exec_Dir use "executables"; - @end smallexample - - @noindent - The attribute @var{Exec_Dir} has a string value, the path name of the exec - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be writable. - - By default, when the attribute @code{Exec_Dir} is not given an explicit value - or when its value is the empty string, the exec directory is the same as the - object directory of the project file. - - - @node Source Directories - @subsection Source Directories - - @noindent - The source directories of a project are specified by the project file - attribute @code{Source_Dirs}. - - This attribute's value is a string list. If the attribute is not given an - explicit value, then there is only one source directory, the one where the - project file resides. - - A @code{Source_Dirs} attribute that is explicitly defined to be the empty list, - as in - - @smallexample - for Source_Dirs use (); - @end smallexample - - @noindent - indicates that the project contains no source files. - - Otherwise, each string in the string list designates one or more - source directories. - - @smallexample - for Source_Dirs use ("sources", "test/drivers"); - @end smallexample - - @noindent - If a string in the list ends with @code{"/**"}, then the directory whose path - name precedes the two asterisks, as well as all its subdirectories - (recursively), are source directories. - - @smallexample - for Source_Dirs use ("/system/sources/**"); - @end smallexample - - @noindent - Here the directory @code{/system/sources} and all of its subdirectories - (recursively) are source directories. - - To specify that the source directories are the directory of the project file - and all of its subdirectories, you can declare @code{Source_Dirs} as follows: - @smallexample - for Source_Dirs use ("./**"); - @end smallexample - - @noindent - Each of the source directories must exist and be readable. - - - @node Source File Names - @subsection Source File Names - - @noindent - In a project that contains source files, their names may be specified by the - attributes @code{Source_Files} (a string list) or @code{Source_List_File} - (a string). Source file names never include any directory information. - - If the attribute @code{Source_Files} is given an explicit value, then each - element of the list is a source file name. - - @smallexample - for Source_Files use ("main.adb"); - for Source_Files use ("main.adb", "pack1.ads", "pack2.adb"); - @end smallexample - - @noindent - If the attribute @code{Source_Files} is not given an explicit value, - but the attribute @code{Source_List_File} is given a string value, - then the source file names are contained in the text file whose path name - (absolute or relative to the directory of the project file) is the - value of the attribute @code{Source_List_File}. - - Each line in the file that is not empty or is not a comment - contains a source file name. A comment line starts with two hyphens. - - @smallexample - for Source_List_File use "source_list.txt"; - @end smallexample - - @noindent - By default, if neither the attribute @code{Source_Files} nor the attribute - @code{Source_List_File} is given an explicit value, then each file in the - source directories that conforms to the project's naming scheme - (see @ref{Naming Schemes}) is an immediate source of the project. - - A warning is issued if both attributes @code{Source_Files} and - @code{Source_List_File} are given explicit values. In this case, the attribute - @code{Source_Files} prevails. - - Each source file name must be the name of one and only one existing source file - in one of the source directories. - - A @code{Source_Files} attribute defined with an empty list as its value - indicates that there are no source files in the project. - - Except for projects that are clearly specified as containing no Ada source - files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list, - or @code{Languages} specified without @code{"Ada"} in the list) - @smallexample - for Source_Dirs use (); - for Source_Files use (); - for Languages use ("C", "C++"); - @end smallexample - - @noindent - a project must contain at least one immediate source. - - Projects with no source files are useful as template packages - (see @ref{Packages in Project Files}) for other projects; in particular to - define a package @code{Naming} (see @ref{Naming Schemes}). - - - @c **************************** - @c * Importing Projects * - @c **************************** - - @node Importing Projects - @section Importing Projects - - @noindent - An immediate source of a project P may depend on source files that - are neither immediate sources of P nor in the predefined library. - To get this effect, P must @emph{import} the projects that contain the needed - source files. - - @smallexample - @group - with "project1", "utilities.gpr"; - with "/namings/apex.gpr"; - project Main is - ... - @end group - @end smallexample - - @noindent - As can be seen in this example, the syntax for importing projects is similar - to the syntax for importing compilation units in Ada. However, project files - use literal strings instead of names, and the @code{with} clause identifies - project files rather than packages. - - Each literal string is the file name or path name (absolute or relative) of a - project file. If a string is simply a file name, with no path, then its - location is determined by the @emph{project path}: - - @itemize @bullet - @item - If the environment variable @env{ADA_PROJECT_PATH} exists, then the project - path includes all the directories in this environment variable, plus the - directory of the project file. - - @item - If the environment variable @env{ADA_PROJECT_PATH} does not exist, - then the project path contains only one directory, namely the one where - the project file is located. - @end itemize - - @noindent - If a relative pathname is used as in - - @smallexample - with "tests/proj"; - @end smallexample - - @noindent - then the path is relative to the directory where the importing project file is - located. Any symbolic link will be fully resolved in the directory - of the importing project file before the imported project file is looked up. - - When the @code{with}'ed project file name does not have an extension, - the default is @file{.gpr}. If a file with this extension is not found, then - the file name as specified in the @code{with} clause (no extension) will be - used. In the above example, if a file @code{project1.gpr} is found, then it - will be used; otherwise, if a file @code{project1} exists then it will be used; - if neither file exists, this is an error. - - A warning is issued if the name of the project file does not match the - name of the project; this check is case insensitive. - - Any source file that is an immediate source of the imported project can be - used by the immediate sources of the importing project, and recursively. Thus - if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate - sources of @code{A} may depend on the immediate sources of @code{C}, even if - @code{A} does not import @code{C} explicitly. However, this is not recommended, - because if and when @code{B} ceases to import @code{C}, some sources in - @code{A} will no longer compile. - - A side effect of this capability is that cyclic dependences are not permitted: - if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not - allowed to import @code{A}. - - - @c ********************* - @c * Project Extension * - @c ********************* - - @node Project Extension - @section Project Extension - - @noindent - During development of a large system, it is sometimes necessary to use - modified versions of some of the source files without changing the original - sources. This can be achieved through a facility known as - @emph{project extension}. - - @smallexample - project Modified_Utilities extends "/baseline/utilities.gpr" is ... - @end smallexample - - @noindent - The project file for the project being extended (the @emph{parent}) is - identified by the literal string that follows the reserved word @code{extends}, - which itself follows the name of the extending project (the @emph{child}). - - By default, a child project inherits all the sources of its parent. - However, inherited sources can be overridden: a unit with the same name as one - in the parent will hide the original unit. - Inherited sources are considered to be sources (but not immediate sources) - of the child project; see @ref{Project File Syntax}. - - An inherited source file retains any switches specified in the parent project. - - For example if the project @code{Utilities} contains the specification and the - body of an Ada package @code{Util_IO}, then the project - @code{Modified_Utilities} can contain a new body for package @code{Util_IO}. - The original body of @code{Util_IO} will not be considered in program builds. - However, the package specification will still be found in the project - @code{Utilities}. - - A child project can have only one parent but it may import any number of other - projects. - - A project is not allowed to import directly or indirectly at the same time a - child project and any of its ancestors. - - - @c **************************************** - @c * External References in Project Files * - @c **************************************** - - @node External References in Project Files - @section External References in Project Files - - @noindent - A project file may contain references to external variables; such references - are called @emph{external references}. - - An external variable is either defined as part of the environment (an - environment variable in Unix, for example) or else specified on the command - line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the - command line value is used. - - An external reference is denoted by the built-in function - @code{external}, which returns a string value. This function has two forms: - @itemize @bullet - @item @code{external (external_variable_name)} - @item @code{external (external_variable_name, default_value)} - @end itemize - - @noindent - Each parameter must be a string literal. For example: - - @smallexample - external ("USER") - external ("OS", "Linux") - @end smallexample - - @noindent - In the form with one parameter, the function returns the value of - the external variable given as parameter. If this name is not present in the - environment, then the returned value is an empty string. - - In the form with two string parameters, the second parameter is - the value returned when the variable given as the first parameter is not - present in the environment. In the example above, if @code{"OS"} is not - the name of an environment variable and is not passed on the command line, - then the returned value will be @code{"Linux"}. - - An external reference may be part of a string expression or of a string - list expression, to define variables or attributes. - - @smallexample - @group - type Mode_Type is ("Debug", "Release"); - Mode : Mode_Type := external ("MODE"); - case Mode is - when "Debug" => - ... - @end group - @end smallexample - - - @c ***************************** - @c * Packages in Project Files * - @c ***************************** - - @node Packages in Project Files - @section Packages in Project Files - - @noindent - The @emph{package} is the project file feature that defines the settings for - project-aware tools. - For each such tool you can declare a corresponding package; the names for these - packages are preset (see @ref{Packages}) but are not case sensitive. - A package may contain variable declarations, attribute declarations, and case - constructions. - - @smallexample - @group - project Proj is - package Builder is -- used by gnatmake - for Default_Switches ("Ada") use ("-v", "-g"); - end Builder; - end Proj; - @end group - @end smallexample - - @noindent - A package declaration starts with the reserved word @code{package}, - followed by the package name (case insensitive), followed by the reserved word - @code{is}. It ends with the reserved word @code{end}, followed by the package - name, finally followed by a semi-colon. - - Most of the packages have an attribute @code{Default_Switches}. - This attribute is an associative array, and its value is a string list. - The index of the associative array is the name of a programming language (case - insensitive). This attribute indicates the switch or switches to be used - with the corresponding tool. - - Some packages also have another attribute, @code{Switches}, an associative - array whose value is a string list. The index is the name of a source file. - This attribute indicates the switch or switches to be used by the corresponding - tool when dealing with this specific file. - - Further information on these switch-related attributes is found in - @ref{Switches and Project Files}. - - A package may be declared as a @emph{renaming} of another package; e.g., from - the project file for an imported project. - - @smallexample - @group - with "/global/apex.gpr"; - project Example is - package Naming renames Apex.Naming; - ... - end Example; - @end group - @end smallexample - - @noindent - Packages that are renamed in other project files often come from project files - that have no sources: they are just used as templates. Any modification in the - template will be reflected automatically in all the project files that rename - a package from the template. - - In addition to the tool-oriented packages, you can also declare a package - named @code{Naming} to establish specialized source file naming conventions - (see @ref{Naming Schemes}). - - - @c ************************************ - @c * Variables from Imported Projects * - @c ************************************ - - @node Variables from Imported Projects - @section Variables from Imported Projects - - @noindent - An attribute or variable defined in an imported or parent project can - be used in expressions in the importing / extending project. - Such an attribute or variable is prefixed with the name of the project - and (if relevant) the name of package where it is defined. - - @smallexample - @group - with "imported"; - project Main extends "base" is - Var1 := Imported.Var; - Var2 := Base.Var & ".new"; - @end group - - @group - package Builder is - for Default_Switches ("Ada") use Imported.Builder.Ada_Switches & - "-gnatg" & "-v"; - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") use Base.Compiler.Ada_Switches; - end Compiler; - end Main; - @end group - @end smallexample - - @noindent - In this example: - - @itemize @bullet - @item - @code{Var1} is a copy of the variable @code{Var} defined in the project file - @file{"imported.gpr"} - @item - the value of @code{Var2} is a copy of the value of variable @code{Var} - defined in the project file @file{base.gpr}, concatenated with @code{".new"} - @item - attribute @code{Default_Switches ("Ada")} in package @code{Builder} - is a string list that includes in its value a copy of variable - @code{Ada_Switches} defined in the @code{Builder} package in project file - @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"}; - @item - attribute @code{Default_Switches ("Ada")} in package @code{Compiler} - is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler} - package in project file @file{base.gpr}, the project being extended. - @end itemize - - - @c ****************** - @c * Naming Schemes * - @c ****************** - - @node Naming Schemes - @section Naming Schemes - - @noindent - Sometimes an Ada software system is ported from a foreign compilation - environment to GNAT, with file names that do not use the default GNAT - conventions. Instead of changing all the file names (which for a variety of - reasons might not be possible), you can define the relevant file naming scheme - in the @code{Naming} package in your project file. For example, the following - package models the Apex file naming rules: - - @smallexample - @group - package Naming is - for Casing use "lowercase"; - for Dot_Replacement use "."; - for Specification_Suffix ("Ada") use ".1.ada"; - for Implementation_Suffix ("Ada") use ".2.ada"; - end Naming; - @end group - @end smallexample - - @noindent - You can define the following attributes in package @code{Naming}: - - @table @code - - @item @var{Casing} - This must be a string with one of the three values @code{"lowercase"}, - @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive. - - @noindent - If @var{Casing} is not specified, then the default is @code{"lowercase"}. - - @item @var{Dot_Replacement} - This must be a string whose value satisfies the following conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start or end with an alphanumeric character - @item It cannot be a single underscore - @item It cannot start with an underscore followed by an alphanumeric - @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."} - @end itemize - - @noindent - If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. - - @item @var{Specification_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @end itemize - @noindent - If @code{Specification_Suffix ("Ada")} is not specified, then the default is - @code{".ads"}. - - @item @var{Implementation_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @item It cannot be a suffix of @code{Specification_Suffix} - @end itemize - @noindent - If @code{Implementation_Suffix ("Ada")} is not specified, then the default is - @code{".adb"}. - - @item @var{Separate_Suffix} - This must be a string whose value satisfies the same conditions as - @code{Implementation_Suffix}. - - @noindent - If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same - value as @code{Implementation_Suffix ("Ada")}. - - @item @var{Specification} - @noindent - You can use the @code{Specification} attribute, an associative array, to define - the source file name for an individual Ada compilation unit's spec. The array - index must be a string literal that identifies the Ada unit (case insensitive). - The value of this attribute must be a string that identifies the file that - contains this unit's spec (case sensitive or insensitive depending on the - operating system). - - @smallexample - for Specification ("MyPack.MyChild") use "mypack.mychild.spec"; - @end smallexample - - @item @var{Implementation} - - You can use the @code{Implementation} attribute, an associative array, to - define the source file name for an individual Ada compilation unit's body - (possibly a subunit). The array index must be a string literal that identifies - the Ada unit (case insensitive). The value of this attribute must be a string - that identifies the file that contains this unit's body or subunit (case - sensitive or insensitive depending on the operating system). - - @smallexample - for Implementation ("MyPack.MyChild") use "mypack.mychild.body"; - @end smallexample - @end table - - - @c ******************** - @c * Library Projects * - @c ******************** - - @node Library Projects - @section Library Projects - - @noindent - @emph{Library projects} are projects whose object code is placed in a library. - (Note that this facility is not yet supported on all platforms) - - To create a library project, you need to define in its project file - two project-level attributes: @code{Library_Name} and @code{Library_Dir}. - Additionally, you may define the library-related attributes - @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}. - - The @code{Library_Name} attribute has a string value that must start with a - letter and include only letters and digits. - - The @code{Library_Dir} attribute has a string value that designates the path - (absolute or relative) of the directory where the library will reside. - It must designate an existing directory, and this directory needs to be - different from the project's object directory. It also needs to be writable. - - If both @code{Library_Name} and @code{Library_Dir} are specified and - are legal, then the project file defines a library project. The optional - library-related attributes are checked only for such project files. - - The @code{Library_Kind} attribute has a string value that must be one of the - following (case insensitive): @code{"static"}, @code{"dynamic"} or - @code{"relocatable"}. If this attribute is not specified, the library is a - static library. Otherwise, the library may be dynamic or relocatable. - Depending on the operating system, there may or may not be a distinction - between dynamic and relocatable libraries. For example, on Unix there is no - such distinction. - - The @code{Library_Version} attribute has a string value whose interpretation - is platform dependent. On Unix, it is used only for dynamic/relocatable - libraries as the internal name of the library (the @code{"soname"}). If the - library file name (built from the @code{Library_Name}) is different from the - @code{Library_Version}, then the library file will be a symbolic link to the - actual file whose name will be @code{Library_Version}. - - Example (on Unix): - - @smallexample - @group - project Plib is - - Version := "1"; - - for Library_Dir use "lib_dir"; - for Library_Name use "dummy"; - for Library_Kind use "relocatable"; - for Library_Version use "libdummy.so." & Version; - - end Plib; - @end group - @end smallexample - - @noindent - Directory @file{lib_dir} will contain the internal library file whose name - will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to - @file{libdummy.so.1}. - - When @command{gnatmake} detects that a project file (not the main project file) - is a library project file, it will check all immediate sources of the project - and rebuild the library if any of the sources have been recompiled. - All @file{ALI} files will also be copied from the object directory to the - library directory. To build executables, @command{gnatmake} will use the - library rather than the individual object files. - - - @c ************************************* - @c * Switches Related to Project Files * - @c ************************************* - @node Switches Related to Project Files - @section Switches Related to Project Files - - @noindent - The following switches are used by GNAT tools that support project files: - - @table @code - - @item @option{-P@var{project}} - Indicates the name of a project file. This project file will be parsed with - the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external - references indicated by @option{-X} switches, if any. - - @noindent - There must be only one @option{-P} switch on the command line. - - @noindent - Since the Project Manager parses the project file only after all the switches - on the command line are checked, the order of the switches @option{-P}, - @option{-Vp@emph{x}} or @option{-X} is not significant. - - @item @option{-X@var{name=value}} - Indicates that external variable @var{name} has the value @var{value}. - The Project Manager will use this value for occurrences of - @code{external(name)} when parsing the project file. - - @noindent - If @var{name} or @var{value} includes a space, then @var{name=value} should be - put between quotes. - @smallexample - -XOS=NT - -X"user=John Doe" - @end smallexample - - @noindent - Several @option{-X} switches can be used simultaneously. - If several @option{-X} switches specify the same @var{name}, only the last one - is used. - - @noindent - An external variable specified with a @option{-X} switch takes precedence - over the value of the same name in the environment. - - @item @option{-vP@emph{x}} - Indicates the verbosity of the parsing of GNAT project files. - @option{-vP0} means Default (no output for syntactically correct project - files); - @option{-vP1} means Medium; - @option{-vP2} means High. - @noindent - The default is Default. - @noindent - If several @option{-vP@emph{x}} switches are present, only the last one is - used. - - @end table - - - @c ********************************** - @c * Tools Supporting Project Files * - @c ********************************** - - @node Tools Supporting Project Files - @section Tools Supporting Project Files - - @menu - * gnatmake and Project Files:: - * The GNAT Driver and Project Files:: - * Glide and Project Files:: - @end menu - - @node gnatmake and Project Files - @subsection gnatmake and Project Files - - @noindent - This section covers two topics related to @command{gnatmake} and project files: - defining switches for @command{gnatmake} and for the tools that it invokes; - and the use of the @code{Main} attribute. - - @menu - * Switches and Project Files:: - * Project Files and Main Subprograms:: - @end menu - - @node Switches and Project Files - @subsubsection Switches and Project Files - - @noindent - For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and - @code{Linker}, you can specify a @code{Default_Switches} attribute, a - @code{Switches} attribute, or both; as their names imply, these switch-related - attributes affect which switches are used for which files when - @command{gnatmake} is invoked. As will be explained below, these - package-contributed switches precede the switches passed on the - @command{gnatmake} command line. - - The @code{Default_Switches} attribute is an associative array indexed by - language name (case insensitive) and returning a string list. For example: - - @smallexample - @group - package Compiler is - for Default_Switches ("Ada") use ("-gnaty", "-v"); - end Compiler; - @end group - @end smallexample - - @noindent - The @code{Switches} attribute is also an associative array, indexed by a file - name (which may or may not be case sensitive, depending on the operating - system) and returning a string list. For example: - - @smallexample - @group - package Builder is - for Switches ("main1.adb") use ("-O2"); - for Switches ("main2.adb") use ("-g"); - end Builder; - @end group - @end smallexample - - @noindent - For the @code{Builder} package, the file names should designate source files - for main subprograms. For the @code{Binder} and @code{Linker} packages, the - file names should designate @file{ALI} or source files for main subprograms. - In each case just the file name (without explicit extension) is acceptable. - - For each tool used in a program build (@command{gnatmake}, the compiler, the - binder, and the linker), its corresponding package @dfn{contributes} a set of - switches for each file on which the tool is invoked, based on the - switch-related attributes defined in the package. In particular, the switches - that each of these packages contributes for a given file @var{f} comprise: - - @itemize @bullet - @item - the value of attribute @code{Switches (@var{f})}, if it is specified in the - package for the given file, - @item - otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in - the package. - @end itemize - - @noindent - If neither of these attributes is defined in the package, then the package does - not contribute any switches for the given file. - - When @command{gnatmake} is invoked on a file, the switches comprise two sets, - in the following order: those contributed for the file by the @code{Builder} - package; and the switches passed on the command line. - - When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file, - the switches passed to the tool comprise three sets, in the following order: - - @enumerate - @item - the applicable switches contributed for the file by the @code{Builder} package - in the project file supplied on the command line; - - @item - those contributed for the file by the package (in the relevant project file -- - see below) corresponding to the tool; and - - @item - the applicable switches passed on the command line. - @end enumerate - - @noindent - The term @emph{applicable switches} reflects the fact that @command{gnatmake} - switches may or may not be passed to individual tools, depending on the - individual switch. - - @command{gnatmake} may invoke the compiler on source files from different - projects. The Project Manager will use the appropriate project file to - determine the @code{Compiler} package for each source file being compiled. - Likewise for the @code{Binder} and @code{Linker} packages. - - As an example, consider the following package in a project file: - - @smallexample - @group - project Proj1 is - package Compiler is - for Default_Switches ("Ada") use ("-g"); - for Switches ("a.adb") use ("-O1"); - for Switches ("b.adb") use ("-O2", "-gnaty"); - end Compiler; - end Proj1; - @end group - @end smallexample - - @noindent - If @command{gnatmake} is invoked with this project file, and it needs to - compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then - @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb} - with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with - @option{-g}. - - Another example illustrates the ordering of the switches contributed by - different packages: - - @smallexample - @group - project Proj2 is - package Builder is - for Switches ("main.adb") use ("-g", "-O1", "-f"); - end Builder; - @end group - - @group - package Compiler is - for Switches ("main.adb") use ("-O2"); - end Compiler; - end Proj2; - @end group - @end smallexample - - @noindent - If you issue the command: - - @smallexample - gnatmake -PProj2 -O0 main - @end smallexample - - @noindent - then the compiler will be invoked on @file{main.adb} with the following sequence of switches - - @smallexample - -g -O1 -O2 -O0 - @end smallexample - - with the last @option{-O} switch having precedence over the earlier ones; - several other switches (such as @option{-c}) are added implicitly. - - The switches @option{-g} and @option{-O1} are contributed by package - @code{Builder}, @option{-O2} is contributed by the package @code{Compiler} - and @option{-O0} comes from the command line. - - The @option{-g} switch will also be passed in the invocation of - @command{gnatlink.} - - A final example illustrates switch contributions from packages in different - project files: - - @smallexample - @group - project Proj3 is - for Source_Files use ("pack.ads", "pack.adb"); - package Compiler is - for Default_Switches ("Ada") use ("-gnata"); - end Compiler; - end Proj3; - @end group - - @group - with "Proj3"; - project Proj4 is - for Source_Files use ("foo_main.adb", "bar_main.adb"); - package Builder is - for Switches ("foo_main.adb") use ("-s", "-g"); - end Builder; - end Proj4; - @end group - - @group - -- Ada source file: - with Pack; - procedure Foo_Main is - ... - end Foo_Main; - @end group - @end smallexample - - If the command is - @smallexample - gnatmake -PProj4 foo_main.adb -cargs -gnato - @end smallexample - - @noindent - then the switches passed to the compiler for @file{foo_main.adb} are - @option{-g} (contributed by the package @code{Proj4.Builder}) and - @option{-gnato} (passed on the command line). - When the imported package @code{Pack} is compiled, the switches used are - @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from - package @code{Proj3.Compiler}, and @option{-gnato} from the command line. - - - @node Project Files and Main Subprograms - @subsubsection Project Files and Main Subprograms - - @noindent - When using a project file, you can invoke @command{gnatmake} - with several main subprograms, by specifying their source files on the command - line. Each of these needs to be an immediate source file of the project. - - @smallexample - gnatmake -Pprj main1 main2 main3 - @end smallexample - - @noindent - When using a project file, you can also invoke @command{gnatmake} without - explicitly specifying any main, and the effect depends on whether you have - defined the @code{Main} attribute. This attribute has a string list value, - where each element in the list is the name of a source file (the file - extension is optional) containing a main subprogram. - - If the @code{Main} attribute is defined in a project file as a non-empty - string list and the switch @option{-u} is not used on the command line, then - invoking @command{gnatmake} with this project file but without any main on the - command line is equivalent to invoking @command{gnatmake} with all the file - names in the @code{Main} attribute on the command line. - - Example: - @smallexample - @group - project Prj is - for Main use ("main1", "main2", "main3"); - end Prj; - @end group - @end smallexample - - @noindent - With this project file, @code{"gnatmake -Pprj"} is equivalent to - @code{"gnatmake -Pprj main1 main2 main3"}. - - When the project attribute @code{Main} is not specified, or is specified - as an empty string list, or when the switch @option{-u} is used on the command - line, then invoking @command{gnatmake} with no main on the command line will - result in all immediate sources of the project file being checked, and - potentially recompiled. Depending on the presence of the switch @option{-u}, - sources from other project files on which the immediate sources of the main - project file depend are also checked and potentially recompiled. In other - words, the @option{-u} switch is applied to all of the immediate sources of themain project file. - - - @node The GNAT Driver and Project Files - @subsection The GNAT Driver and Project Files - - @noindent - A number of GNAT tools, other than @command{gnatmake} are project-aware: - @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls} - and @command{gnatxref}. However, none of these tools can be invoked directly - with a project file switch (@code{-P}). They need to be invoke through the - @command{gnat} driver. - - The @command{gnat} driver is a front-end that accepts a number of commands and - call the corresponding tool. It has been designed initially for VMS to convert - VMS style qualifiers to Unix style switches, but it is now available to all - the GNAT supported platforms. - - On non VMS platforms, the @command{gnat} driver accepts the following commands - (case insensitive): - - @itemize @bullet - @item - BIND to invoke @command{gnatbind} - @item - CHOP to invoke @command{gnatchop} - @item - COMP or COMPILE to invoke the compiler - @item - ELIM to invoke @command{gnatelim} - @item - FIND to invoke @command{gnatfind} - @item - KR or KRUNCH to invoke @command{gnatkr} - @item - LINK to invoke @command{gnatlink} - @item - LS or LIST to invoke @command{gnatls} - @item - MAKE to invoke @command{gnatmake} - @item - NAME to invoke @command{gnatname} - @item - PREP or PREPROCESS to invoke @command{gnatprep} - @item - PSTA or STANDARD to invoke @command{gnatpsta} - @item - STUB to invoke @command{gnatstub} - @item - XREF to invoke @command{gnatxref} - @end itemize - - @noindent - Note that the compiler is invoked using the command @command{gnatmake -f -u}. - - @noindent - Following the command, you may put switches and arguments for the invoked - tool. - - @smallexample - gnat bind -C main.ali - gnat ls -a main - gnat chop foo.txt - @end smallexample - - @noindent - In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project - file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in - addition to the switches of the invoking tool. - - @noindent - For each of these command, there is possibly a package in the main project that - corresponds to the invoked tool. - - @itemize @bullet - @item - package @code{Binder} for command BIND (invoking @code{gnatbind}) - - @item - package @code{Finder} for command FIND (invoking @code{gnatfind}) - - @item - package @code{Gnatls} for command LS or LIST (invoking @code{gnatls}) - - @item - package @code{Linker} for command LINK (invoking @code{gnatlink}) - - @item - package @code{Cross_Reference} for command XREF (invoking @code{gnatlink}) - - @end itemize - - @noindent - Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable - with a string list value. It contains switches for the invocation of - @code{gnatls}. - - @smallexample - @group - project Proj1 is - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - end Proj1; - @end group - @end smallexample - - @noindent - All other packages contains a switch @code{Default_Switches}, an associative - array, indexed by the programming language (case insensitive) and having a - string list value. @code{Default_Switches ("Ada")} contains the switches for - the invocation of the tool corresponding to the package. - - @smallexample - @group - project Proj is - - for Source_Dirs use ("./**"); - - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - @end group - @group - - package Binder is - for Default_Switches ("Ada") use ("-C", "-e"); - end Binder; - @end group - @group - - package Linker is - for Default_Switches ("Ada") use ("-C"); - end Linker; - @end group - @group - - package Finder is - for Default_Switches ("Ada") use ("-a", "-f"); - end Finder; - @end group - @group - - package Cross_Reference is - for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u"); - end Cross_Reference; - end Proj; - @end group - @end smallexample - - @noindent - With the above project file, commands such as - - @smallexample - gnat ls -Pproj main - gnat xref -Pproj main - gnat bind -Pproj main.ali - @end smallexample - - @noindent - will set up the environment properly and invoke the tool with the switches - found in the package corresponding to the tool. - - - @node Glide and Project Files - @subsection Glide and Project Files - - @noindent - Glide will automatically recognize the @file{.gpr} extension for - project files, and will - convert them to its own internal format automatically. However, it - doesn't provide a syntax-oriented editor for modifying these - files. - The project file will be loaded as text when you select the menu item - @code{Ada} @result{} @code{Project} @result{} @code{Edit}. - You can edit this text and save the @file{gpr} file; - when you next select this project file in Glide it - will be automatically reloaded. - - - - @node An Extended Example - @section An Extended Example - - @noindent - Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources - in the respective directories. We would like to build them with a single - @command{gnatmake} command, and we would like to place their object files into - @file{.build} subdirectories of the source directories. Furthermore, we would - like to have to have two separate subdirectories in @file{.build} -- - @file{release} and @file{debug} -- which will contain the object files compiled with - different set of compilation flags. - - In other words, we have the following structure: - - @smallexample - @group - main - |- prog1 - | |- .build - | | debug - | | release - |- prog2 - |- .build - | debug - | release - @end group - @end smallexample - - @noindent - Here are the project files that we need to create in a directory @file{main} - to maintain this structure: - - @enumerate - - @item We create a @code{Common} project with a package @code{Compiler} that - specifies the compilation switches: - - @smallexample - File "common.gpr": - @group - @b{project} Common @b{is} - - @b{for} Source_Dirs @b{use} (); -- No source files - @end group - - @group - @b{type} Build_Type @b{is} ("release", "debug"); - Build : Build_Type := External ("BUILD", "debug"); - @end group - @group - @b{package} Compiler @b{is} - @b{case} Build @b{is} - @b{when} "release" => - @b{for} Default_Switches ("Ada") @b{use} ("-O2"); - @b{when} "debug" => - @b{for} Default_Switches ("Ada") @b{use} ("-g"); - @b{end case}; - @b{end} Compiler; - - @b{end} Common; - @end group - @end smallexample - - @item We create separate projects for the two programs: - - @smallexample - @group - File "prog1.gpr": - - @b{with} "common"; - @b{project} Prog1 @b{is} - - @b{for} Source_Dirs @b{use} ("prog1"); - @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Prog1; - @end group - @end smallexample - - @smallexample - @group - File "prog2.gpr": - - @b{with} "common"; - @b{project} Prog2 @b{is} - - @b{for} Source_Dirs @b{use} ("prog2"); - @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @end group - @b{end} Prog2; - @end smallexample - - @item We create a wrapping project @var{Main}: - - @smallexample - @group - File "main.gpr": - - @b{with} "common"; - @b{with} "prog1"; - @b{with} "prog2"; - @b{project} Main @b{is} - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Main; - @end group - @end smallexample - - @item Finally we need to create a dummy procedure that @code{with}s (either - explicitly or implicitly) all the sources of our two programs. - - @end enumerate - - @noindent - Now we can build the programs using the command - - @smallexample - gnatmake -Pmain dummy - @end smallexample - - @noindent - for the Debug mode, or - - @smallexample - gnatmake -Pmain -XBUILD=release - @end smallexample - - @noindent - for the Release mode. - - - @c ******************************** - @c * Project File Complete Syntax * - @c ******************************** - - @node Project File Complete Syntax - @section Project File Complete Syntax - - @smallexample - project ::= - context_clause project_declaration - - context_clause ::= - @{with_clause@} - - with_clause ::= - @b{with} literal_string @{ , literal_string @} ; - - project_declaration ::= - @b{project} simple_name [ @b{extends} literal_string ] @b{is} - @{declarative_item@} - @b{end} simple_name; - - declarative_item ::= - package_declaration | - typed_string_declaration | - other_declarative_item - - package_declaration ::= - @b{package} simple_name package_completion - - package_completion ::= - package_body | package_renaming - - package body ::= - @b{is} - @{other_declarative_item@} - @b{end} simple_name ; - - package_renaming ::== - @b{renames} simple_name.simple_name ; - - typed_string_declaration ::= - @b{type} _simple_name @b{is} - ( literal_string @{, literal_string@} ); - - other_declarative_item ::= - attribute_declaration | - typed_variable_declaration | - variable_declaration | - case_construction - - attribute_declaration ::= - @b{for} attribute @b{use} expression ; - - attribute ::= - simple_name | - simple_name ( literal_string ) - - typed_variable_declaration ::= - simple_name : name := string_expression ; - - variable_declaration ::= - simple_name := expression; - - expression ::= - term @{& term@} - - term ::= - literal_string | - string_list | - name | - external_value | - attribute_reference - - literal_string ::= - (same as Ada) - - string_list ::= - ( expression @{ , expression @} ) - - external_value ::= - @b{external} ( literal_string [, literal_string] ) - - attribute_reference ::= - attribute_parent ' simple_name [ ( literal_string ) ] - - attribute_parent ::= - @b{project} | - simple_name | - simple_name . simple_name - - case_construction ::= - @b{case} name @b{is} - @{case_item@} - @b{end case} ; - - case_item ::= - @b{when} discrete_choice_list => @{case_construction | attribute_declaration@} - - discrete_choice_list ::= - literal_string @{| literal_string@} - - name ::= - simple_name @{. simple_name@} - - simple_name ::= - identifier (same as Ada) - - @end smallexample - - - @node Elaboration Order Handling in GNAT - @chapter Elaboration Order Handling in GNAT - @cindex Order of elaboration - @cindex Elaboration control - - @menu - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - @end menu - - @noindent - This chapter describes the handling of elaboration code in Ada 95 and - in GNAT, and discusses how the order of elaboration of program units can - be controlled in GNAT, either automatically or with explicit programming - features. - - @node Elaboration Code in Ada 95 - @section Elaboration Code in Ada 95 - - @noindent - Ada 95 provides rather general mechanisms for executing code at elaboration - time, that is to say before the main program starts executing. Such code arises - in three contexts: - - @table @asis - @item Initializers for variables. - Variables declared at the library level, in package specs or bodies, can - require initialization that is performed at elaboration time, as in: - @smallexample - @cartouche - Sqrt_Half : Float := Sqrt (0.5); - @end cartouche - @end smallexample - - @item Package initialization code - Code in a @code{BEGIN-END} section at the outer level of a package body is - executed as part of the package body elaboration code. - - @item Library level task allocators - Tasks that are declared using task allocators at the library level - start executing immediately and hence can execute at elaboration time. - @end table - - @noindent - Subprogram calls are possible in any of these contexts, which means that - any arbitrary part of the program may be executed as part of the elaboration - code. It is even possible to write a program which does all its work at - elaboration time, with a null main program, although stylistically this - would usually be considered an inappropriate way to structure - a program. - - An important concern arises in the context of elaboration code: - we have to be sure that it is executed in an appropriate order. What we - have is a series of elaboration code sections, potentially one section - for each unit in the program. It is important that these execute - in the correct order. Correctness here means that, taking the above - example of the declaration of @code{Sqrt_Half}, - if some other piece of - elaboration code references @code{Sqrt_Half}, - then it must run after the - section of elaboration code that contains the declaration of - @code{Sqrt_Half}. - - There would never be any order of elaboration problem if we made a rule - that whenever you @code{with} a unit, you must elaborate both the spec and body - of that unit before elaborating the unit doing the @code{with}'ing: - - @smallexample - @group - @cartouche - @b{with} Unit_1; - @b{package} Unit_2 @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - would require that both the body and spec of @code{Unit_1} be elaborated - before the spec of @code{Unit_2}. However, a rule like that would be far too - restrictive. In particular, it would make it impossible to have routines - in separate packages that were mutually recursive. - - You might think that a clever enough compiler could look at the actual - elaboration code and determine an appropriate correct order of elaboration, - but in the general case, this is not possible. Consider the following - example. - - In the body of @code{Unit_1}, we have a procedure @code{Func_1} - that references - the variable @code{Sqrt_1}, which is declared in the elaboration code - of the body of @code{Unit_1}: - - @smallexample - @cartouche - Sqrt_1 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_1} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_1 = 1 @b{then} - Q := Unit_2.Func_2; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - @code{Unit_2} is exactly parallel, - it has a procedure @code{Func_2} that references - the variable @code{Sqrt_2}, which is declared in the elaboration code of - the body @code{Unit_2}: - - @smallexample - @cartouche - Sqrt_2 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_2} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_2 = 2 @b{then} - Q := Unit_1.Func_1; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the question is, which of the following orders of elaboration is - acceptable: - - @smallexample - @group - Spec of Unit_1 - Spec of Unit_2 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - or - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_2 - Body of Unit_1 - @end group - @end smallexample - - @noindent - If you carefully analyze the flow here, you will see that you cannot tell - at compile time the answer to this question. - If @code{expression_1} is not equal to 1, - and @code{expression_2} is not equal to 2, - then either order is acceptable, because neither of the function calls is - executed. If both tests evaluate to true, then neither order is acceptable - and in fact there is no correct order. - - If one of the two expressions is true, and the other is false, then one - of the above orders is correct, and the other is incorrect. For example, - if @code{expression_1} = 1 and @code{expression_2} /= 2, - then the call to @code{Func_2} - will occur, but not the call to @code{Func_1.} - This means that it is essential - to elaborate the body of @code{Unit_1} before - the body of @code{Unit_2}, so the first - order of elaboration is correct and the second is wrong. - - By making @code{expression_1} and @code{expression_2} - depend on input data, or perhaps - the time of day, we can make it impossible for the compiler or binder - to figure out which of these expressions will be true, and hence it - is impossible to guarantee a safe order of elaboration at run time. - - @node Checking the Elaboration Order in Ada 95 - @section Checking the Elaboration Order in Ada 95 - - @noindent - In some languages that involve the same kind of elaboration problems, - e.g. Java and C++, the programmer is expected to worry about these - ordering problems himself, and it is common to - write a program in which an incorrect elaboration order gives - surprising results, because it references variables before they - are initialized. - Ada 95 is designed to be a safe language, and a programmer-beware approach is - clearly not sufficient. Consequently, the language provides three lines - of defense: - - @table @asis - @item Standard rules - Some standard rules restrict the possible choice of elaboration - order. In particular, if you @code{with} a unit, then its spec is always - elaborated before the unit doing the @code{with}. Similarly, a parent - spec is always elaborated before the child spec, and finally - a spec is always elaborated before its corresponding body. - - @item Dynamic elaboration checks - @cindex Elaboration checks - @cindex Checks, elaboration - Dynamic checks are made at run time, so that if some entity is accessed - before it is elaborated (typically by means of a subprogram call) - then the exception (@code{Program_Error}) is raised. - - @item Elaboration control - Facilities are provided for the programmer to specify the desired order - of elaboration. - @end table - - Let's look at these facilities in more detail. First, the rules for - dynamic checking. One possible rule would be simply to say that the - exception is raised if you access a variable which has not yet been - elaborated. The trouble with this approach is that it could require - expensive checks on every variable reference. Instead Ada 95 has two - rules which are a little more restrictive, but easier to check, and - easier to state: - - @table @asis - @item Restrictions on calls - A subprogram can only be called at elaboration time if its body - has been elaborated. The rules for elaboration given above guarantee - that the spec of the subprogram has been elaborated before the - call, but not the body. If this rule is violated, then the - exception @code{Program_Error} is raised. - - @item Restrictions on instantiations - A generic unit can only be instantiated if the body of the generic - unit has been elaborated. Again, the rules for elaboration given above - guarantee that the spec of the generic unit has been elaborated - before the instantiation, but not the body. If this rule is - violated, then the exception @code{Program_Error} is raised. - @end table - - @noindent - The idea is that if the body has been elaborated, then any variables - it references must have been elaborated; by checking for the body being - elaborated we guarantee that none of its references causes any - trouble. As we noted above, this is a little too restrictive, because a - subprogram that has no non-local references in its body may in fact be safe - to call. However, it really would be unsafe to rely on this, because - it would mean that the caller was aware of details of the implementation - in the body. This goes against the basic tenets of Ada. - - A plausible implementation can be described as follows. - A Boolean variable is associated with each subprogram - and each generic unit. This variable is initialized to False, and is set to - True at the point body is elaborated. Every call or instantiation checks the - variable, and raises @code{Program_Error} if the variable is False. - - Note that one might think that it would be good enough to have one Boolean - variable for each package, but that would not deal with cases of trying - to call a body in the same package as the call - that has not been elaborated yet. - Of course a compiler may be able to do enough analysis to optimize away - some of the Boolean variables as unnecessary, and @code{GNAT} indeed - does such optimizations, but still the easiest conceptual model is to - think of there being one variable per subprogram. - - @node Controlling the Elaboration Order in Ada 95 - @section Controlling the Elaboration Order in Ada 95 - - @noindent - In the previous section we discussed the rules in Ada 95 which ensure - that @code{Program_Error} is raised if an incorrect elaboration order is - chosen. This prevents erroneous executions, but we need mechanisms to - specify a correct execution and avoid the exception altogether. - To achieve this, Ada 95 provides a number of features for controlling - the order of elaboration. We discuss these features in this section. - - First, there are several ways of indicating to the compiler that a given - unit has no elaboration problems: - - @table @asis - @item packages that do not require a body - In Ada 95, a library package that does not require a body does not permit - a body. This means that if we have a such a package, as in: - - @smallexample - @group - @cartouche - @b{package} Definitions @b{is} - @b{generic} - @b{type} m @b{is new} integer; - @b{package} Subp @b{is} - @b{type} a @b{is array} (1 .. 10) @b{of} m; - @b{type} b @b{is array} (1 .. 20) @b{of} m; - @b{end} Subp; - @b{end} Definitions; - @end cartouche - @end group - @end smallexample - - @noindent - A package that @code{with}'s @code{Definitions} may safely instantiate - @code{Definitions.Subp} because the compiler can determine that there - definitely is no package body to worry about in this case - - @item pragma Pure - @cindex pragma Pure - @findex Pure - Places sufficient restrictions on a unit to guarantee that - no call to any subprogram in the unit can result in an - elaboration problem. This means that the compiler does not need - to worry about the point of elaboration of such units, and in - particular, does not need to check any calls to any subprograms - in this unit. - - @item pragma Preelaborate - @findex Preelaborate - @cindex pragma Preelaborate - This pragma places slightly less stringent restrictions on a unit than - does pragma Pure, - but these restrictions are still sufficient to ensure that there - are no elaboration problems with any calls to the unit. - - @item pragma Elaborate_Body - @findex Elaborate_Body - @cindex pragma Elaborate_Body - This pragma requires that the body of a unit be elaborated immediately - after its spec. Suppose a unit @code{A} has such a pragma, - and unit @code{B} does - a @code{with} of unit @code{A}. Recall that the standard rules require - the spec of unit @code{A} - to be elaborated before the @code{with}'ing unit; given the pragma in - @code{A}, we also know that the body of @code{A} - will be elaborated before @code{B}, so - that calls to @code{A} are safe and do not need a check. - @end table - - @noindent - Note that, - unlike pragma @code{Pure} and pragma @code{Preelaborate}, - the use of - @code{Elaborate_Body} does not guarantee that the program is - free of elaboration problems, because it may not be possible - to satisfy the requested elaboration order. - Let's go back to the example with @code{Unit_1} and @code{Unit_2}. - If a programmer - marks @code{Unit_1} as @code{Elaborate_Body}, - and not @code{Unit_2,} then the order of - elaboration will be: - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - Now that means that the call to @code{Func_1} in @code{Unit_2} - need not be checked, - it must be safe. But the call to @code{Func_2} in - @code{Unit_1} may still fail if - @code{Expression_1} is equal to 1, - and the programmer must still take - responsibility for this not being the case. - - If all units carry a pragma @code{Elaborate_Body}, then all problems are - eliminated, except for calls entirely within a body, which are - in any case fully under programmer control. However, using the pragma - everywhere is not always possible. - In particular, for our @code{Unit_1}/@code{Unit_2} example, if - we marked both of them as having pragma @code{Elaborate_Body}, then - clearly there would be no possible elaboration order. - - The above pragmas allow a server to guarantee safe use by clients, and - clearly this is the preferable approach. Consequently a good rule in - Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible, - and if this is not possible, - mark them as @code{Elaborate_Body} if possible. - As we have seen, there are situations where neither of these - three pragmas can be used. - So we also provide methods for clients to control the - order of elaboration of the servers on which they depend: - - @table @asis - @item pragma Elaborate (unit) - @findex Elaborate - @cindex pragma Elaborate - This pragma is placed in the context clause, after a @code{with} clause, - and it requires that the body of the named unit be elaborated before - the unit in which the pragma occurs. The idea is to use this pragma - if the current unit calls at elaboration time, directly or indirectly, - some subprogram in the named unit. - - @item pragma Elaborate_All (unit) - @findex Elaborate_All - @cindex pragma Elaborate_All - This is a stronger version of the Elaborate pragma. Consider the - following example: - - @smallexample - Unit A @code{with}'s unit B and calls B.Func in elab code - Unit B @code{with}'s unit C, and B.Func calls C.Func - @end smallexample - - @noindent - Now if we put a pragma @code{Elaborate (B)} - in unit @code{A}, this ensures that the - body of @code{B} is elaborated before the call, but not the - body of @code{C}, so - the call to @code{C.Func} could still cause @code{Program_Error} to - be raised. - - The effect of a pragma @code{Elaborate_All} is stronger, it requires - not only that the body of the named unit be elaborated before the - unit doing the @code{with}, but also the bodies of all units that the - named unit uses, following @code{with} links transitively. For example, - if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, - then it requires - not only that the body of @code{B} be elaborated before @code{A}, - but also the - body of @code{C}, because @code{B} @code{with}'s @code{C}. - @end table - - @noindent - We are now in a position to give a usage rule in Ada 95 for avoiding - elaboration problems, at least if dynamic dispatching and access to - subprogram values are not used. We will handle these cases separately - later. - - The rule is simple. If a unit has elaboration code that can directly or - indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate - a generic unit in a @code{with}'ed unit, - then if the @code{with}'ed unit does not have - pragma @code{Pure} or @code{Preelaborate}, then the client should have - a pragma @code{Elaborate_All} - for the @code{with}'ed unit. By following this rule a client is - assured that calls can be made without risk of an exception. - If this rule is not followed, then a program may be in one of four - states: - - @table @asis - @item No order exists - No order of elaboration exists which follows the rules, taking into - account any @code{Elaborate}, @code{Elaborate_All}, - or @code{Elaborate_Body} pragmas. In - this case, an Ada 95 compiler must diagnose the situation at bind - time, and refuse to build an executable program. - - @item One or more orders exist, all incorrect - One or more acceptable elaboration orders exists, and all of them - generate an elaboration order problem. In this case, the binder - can build an executable program, but @code{Program_Error} will be raised - when the program is run. - - @item Several orders exist, some right, some incorrect - One or more acceptable elaboration orders exists, and some of them - work, and some do not. The programmer has not controlled - the order of elaboration, so the binder may or may not pick one of - the correct orders, and the program may or may not raise an - exception when it is run. This is the worst case, because it means - that the program may fail when moved to another compiler, or even - another version of the same compiler. - - @item One or more orders exists, all correct - One ore more acceptable elaboration orders exist, and all of them - work. In this case the program runs successfully. This state of - affairs can be guaranteed by following the rule we gave above, but - may be true even if the rule is not followed. - @end table - - @noindent - Note that one additional advantage of following our Elaborate_All rule - is that the program continues to stay in the ideal (all orders OK) state - even if maintenance - changes some bodies of some subprograms. Conversely, if a program that does - not follow this rule happens to be safe at some point, this state of affairs - may deteriorate silently as a result of maintenance changes. - - You may have noticed that the above discussion did not mention - the use of @code{Elaborate_Body}. This was a deliberate omission. If you - @code{with} an @code{Elaborate_Body} unit, it still may be the case that - code in the body makes calls to some other unit, so it is still necessary - to use @code{Elaborate_All} on such units. - - @node Controlling Elaboration in GNAT - Internal Calls - @section Controlling Elaboration in GNAT - Internal Calls - - @noindent - In the case of internal calls, i.e. calls within a single package, the - programmer has full control over the order of elaboration, and it is up - to the programmer to elaborate declarations in an appropriate order. For - example writing: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - Q : Float := One; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - @end cartouche - @end group - @end smallexample - - @noindent - will obviously raise @code{Program_Error} at run time, because function - One will be called before its body is elaborated. In this case GNAT will - generate a warning that the call will raise @code{Program_Error}: - - @smallexample - @group - @cartouche - 1. procedure y is - 2. function One return Float; - 3. - 4. Q : Float := One; - | - >>> warning: cannot call "One" before body is elaborated - >>> warning: Program_Error will be raised at run time - - 5. - 6. function One return Float is - 7. begin - 8. return 1.0; - 9. end One; - 10. - 11. begin - 12. null; - 13. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that in this particular case, it is likely that the call is safe, because - the function @code{One} does not access any global variables. - Nevertheless in Ada 95, we do not want the validity of the check to depend on - the contents of the body (think about the separate compilation case), so this - is still wrong, as we discussed in the previous sections. - - The error is easily corrected by rearranging the declarations so that the - body of One appears before the declaration containing the call - (note that in Ada 95, - declarations can appear in any order, so there is no restriction that - would prevent this reordering, and if we write: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - - Q : Float := One; - @end cartouche - @end group - @end smallexample - - @noindent - then all is well, no warning is generated, and no - @code{Program_Error} exception - will be raised. - Things are more complicated when a chain of subprograms is executed: - - @smallexample - @group - @cartouche - @b{function} A @b{return} Integer; - @b{function} B @b{return} Integer; - @b{function} C @b{return} Integer; - - @b{function} B @b{return} Integer @b{is begin return} A; @b{end}; - @b{function} C @b{return} Integer @b{is begin return} B; @b{end}; - - X : Integer := C; - - @b{function} A @b{return} Integer @b{is begin return} 1; @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the call to @code{C} - at elaboration time in the declaration of @code{X} is correct, because - the body of @code{C} is already elaborated, - and the call to @code{B} within the body of - @code{C} is correct, but the call - to @code{A} within the body of @code{B} is incorrect, because the body - of @code{A} has not been elaborated, so @code{Program_Error} - will be raised on the call to @code{A}. - In this case GNAT will generate a - warning that @code{Program_Error} may be - raised at the point of the call. Let's look at the warning: - - @smallexample - @group - @cartouche - 1. procedure x is - 2. function A return Integer; - 3. function B return Integer; - 4. function C return Integer; - 5. - 6. function B return Integer is begin return A; end; - | - >>> warning: call to "A" before body is elaborated may - raise Program_Error - >>> warning: "B" called at line 7 - >>> warning: "C" called at line 9 - - 7. function C return Integer is begin return B; end; - 8. - 9. X : Integer := C; - 10. - 11. function A return Integer is begin return 1; end; - 12. - 13. begin - 14. null; - 15. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that the message here says "may raise", instead of the direct case, - where the message says "will be raised". That's because whether - @code{A} is - actually called depends in general on run-time flow of control. - For example, if the body of @code{B} said - - @smallexample - @group - @cartouche - @b{function} B @b{return} Integer @b{is} - @b{begin} - @b{if} some-condition-depending-on-input-data @b{then} - @b{return} A; - @b{else} - @b{return} 1; - @b{end if}; - @b{end} B; - @end cartouche - @end group - @end smallexample - - @noindent - then we could not know until run time whether the incorrect call to A would - actually occur, so @code{Program_Error} might - or might not be raised. It is possible for a compiler to - do a better job of analyzing bodies, to - determine whether or not @code{Program_Error} - might be raised, but it certainly - couldn't do a perfect job (that would require solving the halting problem - and is provably impossible), and because this is a warning anyway, it does - not seem worth the effort to do the analysis. Cases in which it - would be relevant are rare. - - In practice, warnings of either of the forms given - above will usually correspond to - real errors, and should be examined carefully and eliminated. - In the rare case where a warning is bogus, it can be suppressed by any of - the following methods: - - @itemize @bullet - @item - Compile with the @option{-gnatws} switch set - - @item - Suppress @code{Elaboration_Checks} for the called subprogram - - @item - Use pragma @code{Warnings_Off} to turn warnings off for the call - @end itemize - - @noindent - For the internal elaboration check case, - GNAT by default generates the - necessary run-time checks to ensure - that @code{Program_Error} is raised if any - call fails an elaboration check. Of course this can only happen if a - warning has been issued as described above. The use of pragma - @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress - some of these checks, meaning that it may be possible (but is not - guaranteed) for a program to be able to call a subprogram whose body - is not yet elaborated, without raising a @code{Program_Error} exception. - - @node Controlling Elaboration in GNAT - External Calls - @section Controlling Elaboration in GNAT - External Calls - - @noindent - The previous section discussed the case in which the execution of a - particular thread of elaboration code occurred entirely within a - single unit. This is the easy case to handle, because a programmer - has direct and total control over the order of elaboration, and - furthermore, checks need only be generated in cases which are rare - and which the compiler can easily detect. - The situation is more complex when separate compilation is taken into account. - Consider the following: - - @smallexample - @cartouche - @group - @b{package} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float; - @b{end} Math; - - @b{package body} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float @b{is} - @b{begin} - ... - @b{end} Sqrt; - @b{end} Math; - @end group - @group - @b{with} Math; - @b{package} Stuff @b{is} - X : Float := Math.Sqrt (0.5); - @b{end} Stuff; - - @b{with} Stuff; - @b{procedure} Main @b{is} - @b{begin} - ... - @b{end} Main; - @end group - @end cartouche - @end smallexample - - @noindent - where @code{Main} is the main program. When this program is executed, the - elaboration code must first be executed, and one of the jobs of the - binder is to determine the order in which the units of a program are - to be elaborated. In this case we have four units: the spec and body - of @code{Math}, - the spec of @code{Stuff} and the body of @code{Main}). - In what order should the four separate sections of elaboration code - be executed? - - There are some restrictions in the order of elaboration that the binder - can choose. In particular, if unit U has a @code{with} - for a package @code{X}, then you - are assured that the spec of @code{X} - is elaborated before U , but you are - not assured that the body of @code{X} - is elaborated before U. - This means that in the above case, the binder is allowed to choose the - order: - - @smallexample - spec of Math - spec of Stuff - body of Math - body of Main - @end smallexample - - @noindent - but that's not good, because now the call to @code{Math.Sqrt} - that happens during - the elaboration of the @code{Stuff} - spec happens before the body of @code{Math.Sqrt} is - elaborated, and hence causes @code{Program_Error} exception to be raised. - At first glance, one might say that the binder is misbehaving, because - obviously you want to elaborate the body of something you @code{with} - first, but - that is not a general rule that can be followed in all cases. Consider - - @smallexample - @group - @cartouche - @b{package} X @b{is} ... - - @b{package} Y @b{is} ... - - @b{with} X; - @b{package body} Y @b{is} ... - - @b{with} Y; - @b{package body} X @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - This is a common arrangement, and, apart from the order of elaboration - problems that might arise in connection with elaboration code, this works fine. - A rule that says that you must first elaborate the body of anything you - @code{with} cannot work in this case: - the body of @code{X} @code{with}'s @code{Y}, - which means you would have to - elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, - which means - you have to elaborate the body of @code{X} first, but ... and we have a - loop that cannot be broken. - - It is true that the binder can in many cases guess an order of elaboration - that is unlikely to cause a @code{Program_Error} - exception to be raised, and it tries to do so (in the - above example of @code{Math/Stuff/Spec}, the GNAT binder will - by default - elaborate the body of @code{Math} right after its spec, so all will be well). - - However, a program that blindly relies on the binder to be helpful can - get into trouble, as we discussed in the previous sections, so - GNAT - provides a number of facilities for assisting the programmer in - developing programs that are robust with respect to elaboration order. - - @node Default Behavior in GNAT - Ensuring Safety - @section Default Behavior in GNAT - Ensuring Safety - - @noindent - The default behavior in GNAT ensures elaboration safety. In its - default mode GNAT implements the - rule we previously described as the right approach. Let's restate it: - - @itemize - @item - @emph{If a unit has elaboration code that can directly or indirectly make a - call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit - in a @code{with}'ed unit, then if the @code{with}'ed unit - does not have pragma @code{Pure} or - @code{Preelaborate}, then the client should have an - @code{Elaborate_All} for the @code{with}'ed unit.} - @end itemize - - @noindent - By following this rule a client - is assured that calls and instantiations can be made without risk of an exception. - - In this mode GNAT traces all calls that are potentially made from - elaboration code, and puts in any missing implicit @code{Elaborate_All} - pragmas. - The advantage of this approach is that no elaboration problems - are possible if the binder can find an elaboration order that is - consistent with these implicit @code{Elaborate_All} pragmas. The - disadvantage of this approach is that no such order may exist. - - If the binder does not generate any diagnostics, then it means that it - has found an elaboration order that is guaranteed to be safe. However, - the binder may still be relying on implicitly generated - @code{Elaborate_All} pragmas so portability to other compilers than - GNAT is not guaranteed. - - If it is important to guarantee portability, then the compilations should - use the - @option{-gnatwl} - (warn on elaboration problems) switch. This will cause warning messages - to be generated indicating the missing @code{Elaborate_All} pragmas. - Consider the following source program: - - @smallexample - @group - @cartouche - @b{with} k; - @b{package} j @b{is} - m : integer := k.r; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - where it is clear that there - should be a pragma @code{Elaborate_All} - for unit @code{k}. An implicit pragma will be generated, and it is - likely that the binder will be able to honor it. However, - it is safer to include the pragma explicitly in the source. If this - unit is compiled with the - @option{-gnatwl} - switch, then the compiler outputs a warning: - - @smallexample - @group - @cartouche - 1. with k; - 2. package j is - 3. m : integer := k.r; - | - >>> warning: call to "r" may raise Program_Error - >>> warning: missing pragma Elaborate_All for "k" - - 4. end; - @end cartouche - @end group - @end smallexample - - @noindent - and these warnings can be used as a guide for supplying manually - the missing pragmas. - - This default mode is more restrictive than the Ada Reference - Manual, and it is possible to construct programs which will compile - using the dynamic model described there, but will run into a - circularity using the safer static model we have described. - - Of course any Ada compiler must be able to operate in a mode - consistent with the requirements of the Ada Reference Manual, - and in particular must have the capability of implementing the - standard dynamic model of elaboration with run-time checks. - - In GNAT, this standard mode can be achieved either by the use of - the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake}) - command, or by the use of the configuration pragma: - - @smallexample - pragma Elaboration_Checks (RM); - @end smallexample - - @noindent - Either approach will cause the unit affected to be compiled using the - standard dynamic run-time elaboration checks described in the Ada - Reference Manual. The static model is generally preferable, since it - is clearly safer to rely on compile and link time checks rather than - run-time checks. However, in the case of legacy code, it may be - difficult to meet the requirements of the static model. This - issue is further discussed in - @ref{What to Do If the Default Elaboration Behavior Fails}. - - Note that the static model provides a strict subset of the allowed - behavior and programs of the Ada Reference Manual, so if you do - adhere to the static model and no circularities exist, - then you are assured that your program will - work using the dynamic model. - - @node Elaboration Issues for Library Tasks - @section Elaboration Issues for Library Tasks - @cindex Library tasks, elaboration issues - @cindex Elaboration of library tasks - - @noindent - In this section we examine special elaboration issues that arise for - programs that declare library level tasks. - - Generally the model of execution of an Ada program is that all units are - elaborated, and then execution of the program starts. However, the - declaration of library tasks definitely does not fit this model. The - reason for this is that library tasks start as soon as they are declared - (more precisely, as soon as the statement part of the enclosing package - body is reached), that is to say before elaboration - of the program is complete. This means that if such a task calls a - subprogram, or an entry in another task, the callee may or may not be - elaborated yet, and in the standard - Reference Manual model of dynamic elaboration checks, you can even - get timing dependent Program_Error exceptions, since there can be - a race between the elaboration code and the task code. - - The static model of elaboration in GNAT seeks to avoid all such - dynamic behavior, by being conservative, and the conservative - approach in this particular case is to assume that all the code - in a task body is potentially executed at elaboration time if - a task is declared at the library level. - - This can definitely result in unexpected circularities. Consider - the following example - - @smallexample - package Decls is - task Lib_Task is - entry Start; - end Lib_Task; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - procedure Main is - begin - Decls.Lib_Task.Start; - end; - @end smallexample - - @noindent - If the above example is compiled in the default static elaboration - mode, then a circularity occurs. The circularity comes from the call - @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since - this call occurs in elaboration code, we need an implicit pragma - @code{Elaborate_All} for @code{Utils}. This means that not only must - the spec and body of @code{Utils} be elaborated before the body - of @code{Decls}, but also the spec and body of any unit that is - @code{with'ed} by the body of @code{Utils} must also be elaborated before - the body of @code{Decls}. This is the transitive implication of - pragma @code{Elaborate_All} and it makes sense, because in general - the body of @code{Put_Val} might have a call to something in a - @code{with'ed} unit. - - In this case, the body of Utils (actually its spec) @code{with's} - @code{Decls}. Unfortunately this means that the body of @code{Decls} - must be elaborated before itself, in case there is a call from the - body of @code{Utils}. - - Here is the exact chain of events we are worrying about: - - @enumerate - @item - In the body of @code{Decls} a call is made from within the body of a library - task to a subprogram in the package @code{Utils}. Since this call may - occur at elaboration time (given that the task is activated at elaboration - time), we have to assume the worst, i.e. that the - call does happen at elaboration time. - - @item - This means that the body and spec of @code{Util} must be elaborated before - the body of @code{Decls} so that this call does not cause an access before - elaboration. - - @item - Within the body of @code{Util}, specifically within the body of - @code{Util.Put_Val} there may be calls to any unit @code{with}'ed - by this package. - - @item - One such @code{with}'ed package is package @code{Decls}, so there - might be a call to a subprogram in @code{Decls} in @code{Put_Val}. - In fact there is such a call in this example, but we would have to - assume that there was such a call even if it were not there, since - we are not supposed to write the body of @code{Decls} knowing what - is in the body of @code{Utils}; certainly in the case of the - static elaboration model, the compiler does not know what is in - other bodies and must assume the worst. - - @item - This means that the spec and body of @code{Decls} must also be - elaborated before we elaborate the unit containing the call, but - that unit is @code{Decls}! This means that the body of @code{Decls} - must be elaborated before itself, and that's a circularity. - @end enumerate - - @noindent - Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in - the body of @code{Decls} you will get a true Ada Reference Manual - circularity that makes the program illegal. - - In practice, we have found that problems with the static model of - elaboration in existing code often arise from library tasks, so - we must address this particular situation. - - Note that if we compile and run the program above, using the dynamic model of - elaboration (that is to say use the @option{-gnatE} switch), - then it compiles, binds, - links, and runs, printing the expected result of 2. Therefore in some sense - the circularity here is only apparent, and we need to capture - the properties of this program that distinguish it from other library-level - tasks that have real elaboration problems. - - We have four possible answers to this question: - - @itemize @bullet - - @item - Use the dynamic model of elaboration. - - If we use the @option{-gnatE} switch, then as noted above, the program works. - Why is this? If we examine the task body, it is apparent that the task cannot - proceed past the - @code{accept} statement until after elaboration has been completed, because - the corresponding entry call comes from the main program, not earlier. - This is why the dynamic model works here. But that's really giving - up on a precise analysis, and we prefer to take this approach only if we cannot - solve the - problem in any other manner. So let us examine two ways to reorganize - the program to avoid the potential elaboration problem. - - @item - Split library tasks into separate packages. - - Write separate packages, so that library tasks are isolated from - other declarations as much as possible. Let us look at a variation on - the above program. - - @smallexample - package Decls1 is - task Lib_Task is - entry Start; - end Lib_Task; - end Decls1; - - with Utils; - package body Decls1 is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - end Decls1; - - package Decls2 is - type My_Int is new Integer; - function Ident (M : My_Int) return My_Int; - end Decls2; - - with Utils; - package body Decls2 is - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls2; - - with Decls2; - package Utils is - procedure Put_Val (Arg : Decls2.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls2.My_Int) is - begin - Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls1; - procedure Main is - begin - Decls1.Lib_Task.Start; - end; - @end smallexample - - @noindent - All we have done is to split @code{Decls} into two packages, one - containing the library task, and one containing everything else. Now - there is no cycle, and the program compiles, binds, links and executes - using the default static model of elaboration. - - @item - Declare separate task types. - - A significant part of the problem arises because of the use of the - single task declaration form. This means that the elaboration of - the task type, and the elaboration of the task itself (i.e. the - creation of the task) happen at the same time. A good rule - of style in Ada 95 is to always create explicit task types. By - following the additional step of placing task objects in separate - packages from the task type declaration, many elaboration problems - are avoided. Here is another modified example of the example program: - - @smallexample - package Decls is - task type Lib_Task_Type is - entry Start; - end Lib_Task_Type; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task_Type is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task_Type; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - package Declst is - Lib_Task : Decls.Lib_Task_Type; - end Declst; - - with Declst; - procedure Main is - begin - Declst.Lib_Task.Start; - end; - @end smallexample - - @noindent - What we have done here is to replace the @code{task} declaration in - package @code{Decls} with a @code{task type} declaration. Then we - introduce a separate package @code{Declst} to contain the actual - task object. This separates the elaboration issues for - the @code{task type} - declaration, which causes no trouble, from the elaboration issues - of the task object, which is also unproblematic, since it is now independent - of the elaboration of @code{Utils}. - This separation of concerns also corresponds to - a generally sound engineering principle of separating declarations - from instances. This version of the program also compiles, binds, links, - and executes, generating the expected output. - - @item - Use No_Entry_Calls_In_Elaboration_Code restriction. - @cindex No_Entry_Calls_In_Elaboration_Code - - The previous two approaches described how a program can be restructured - to avoid the special problems caused by library task bodies. in practice, - however, such restructuring may be difficult to apply to existing legacy code, - so we must consider solutions that do not require massive rewriting. - - Let us consider more carefully why our original sample program works - under the dynamic model of elaboration. The reason is that the code - in the task body blocks immediately on the @code{accept} - statement. Now of course there is nothing to prohibit elaboration - code from making entry calls (for example from another library level task), - so we cannot tell in isolation that - the task will not execute the accept statement during elaboration. - - However, in practice it is very unusual to see elaboration code - make any entry calls, and the pattern of tasks starting - at elaboration time and then immediately blocking on @code{accept} or - @code{select} statements is very common. What this means is that - the compiler is being too pessimistic when it analyzes the - whole package body as though it might be executed at elaboration - time. - - If we know that the elaboration code contains no entry calls, (a very safe - assumption most of the time, that could almost be made the default - behavior), then we can compile all units of the program under control - of the following configuration pragma: - - @smallexample - pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); - @end smallexample - - @noindent - This pragma can be placed in the @file{gnat.adc} file in the usual - manner. If we take our original unmodified program and compile it - in the presence of a @file{gnat.adc} containing the above pragma, - then once again, we can compile, bind, link, and execute, obtaining - the expected result. In the presence of this pragma, the compiler does - not trace calls in a task body, that appear after the first @code{accept} - or @code{select} statement, and therefore does not report a potential - circularity in the original program. - - The compiler will check to the extent it can that the above - restriction is not violated, but it is not always possible to do a - complete check at compile time, so it is important to use this - pragma only if the stated restriction is in fact met, that is to say - no task receives an entry call before elaboration of all units is completed. - - @end itemize - - @node Mixing Elaboration Models - @section Mixing Elaboration Models - @noindent - So far, we have assumed that the entire program is either compiled - using the dynamic model or static model, ensuring consistency. It - is possible to mix the two models, but rules have to be followed - if this mixing is done to ensure that elaboration checks are not - omitted. - - The basic rule is that @emph{a unit compiled with the static model cannot - be @code{with'ed} by a unit compiled with the dynamic model}. The - reason for this is that in the static model, a unit assumes that - its clients guarantee to use (the equivalent of) pragma - @code{Elaborate_All} so that no elaboration checks are required - in inner subprograms, and this assumption is violated if the - client is compiled with dynamic checks. - - The precise rule is as follows. A unit that is compiled with dynamic - checks can only @code{with} a unit that meets at least one of the - following criteria: - - @itemize @bullet - - @item - The @code{with'ed} unit is itself compiled with dynamic elaboration - checks (that is with the @option{-gnatE} switch. - - @item - The @code{with'ed} unit is an internal GNAT implementation unit from - the System, Interfaces, Ada, or GNAT hierarchies. - - @item - The @code{with'ed} unit has pragma Preelaborate or pragma Pure. - - @item - The @code{with'ing} unit (that is the client) has an explicit pragma - @code{Elaborate_All} for the @code{with'ed} unit. - - @end itemize - - @noindent - If this rule is violated, that is if a unit with dynamic elaboration - checks @code{with's} a unit that does not meet one of the above four - criteria, then the binder (@code{gnatbind}) will issue a warning - similar to that in the following example: - - @smallexample - warning: "x.ads" has dynamic elaboration checks and with's - warning: "y.ads" which has static elaboration checks - @end smallexample - - @noindent - These warnings indicate that the rule has been violated, and that as a result - elaboration checks may be missed in the resulting executable file. - This warning may be suppressed using the @code{-ws} binder switch - in the usual manner. - - One useful application of this mixing rule is in the case of a subsystem - which does not itself @code{with} units from the remainder of the - application. In this case, the entire subsystem can be compiled with - dynamic checks to resolve a circularity in the subsystem, while - allowing the main application that uses this subsystem to be compiled - using the more reliable default static model. - - @node What to Do If the Default Elaboration Behavior Fails - @section What to Do If the Default Elaboration Behavior Fails - - @noindent - If the binder cannot find an acceptable order, it outputs detailed - diagnostics. For example: - @smallexample - @group - @iftex - @leftskip=0cm - @end iftex - error: elaboration circularity detected - info: "proc (body)" must be elaborated before "pack (body)" - info: reason: Elaborate_All probably needed in unit "pack (body)" - info: recompile "pack (body)" with -gnatwl - info: for full details - info: "proc (body)" - info: is needed by its spec: - info: "proc (spec)" - info: which is withed by: - info: "pack (body)" - info: "pack (body)" must be elaborated before "proc (body)" - info: reason: pragma Elaborate in unit "proc (body)" - @end group - - @end smallexample - - @noindent - In this case we have a cycle that the binder cannot break. On the one - hand, there is an explicit pragma Elaborate in @code{proc} for - @code{pack}. This means that the body of @code{pack} must be elaborated - before the body of @code{proc}. On the other hand, there is elaboration - code in @code{pack} that calls a subprogram in @code{proc}. This means - that for maximum safety, there should really be a pragma - Elaborate_All in @code{pack} for @code{proc} which would require that - the body of @code{proc} be elaborated before the body of - @code{pack}. Clearly both requirements cannot be satisfied. - Faced with a circularity of this kind, you have three different options. - - @table @asis - @item Fix the program - The most desirable option from the point of view of long-term maintenance - is to rearrange the program so that the elaboration problems are avoided. - One useful technique is to place the elaboration code into separate - child packages. Another is to move some of the initialization code to - explicitly called subprograms, where the program controls the order - of initialization explicitly. Although this is the most desirable option, - it may be impractical and involve too much modification, especially in - the case of complex legacy code. - - @item Perform dynamic checks - If the compilations are done using the - @option{-gnatE} - (dynamic elaboration check) switch, then GNAT behaves in - a quite different manner. Dynamic checks are generated for all calls - that could possibly result in raising an exception. With this switch, - the compiler does not generate implicit @code{Elaborate_All} pragmas. - The behavior then is exactly as specified in the Ada 95 Reference Manual. - The binder will generate an executable program that may or may not - raise @code{Program_Error}, and then it is the programmer's job to ensure - that it does not raise an exception. Note that it is important to - compile all units with the switch, it cannot be used selectively. - - @item Suppress checks - The drawback of dynamic checks is that they generate a - significant overhead at run time, both in space and time. If you - are absolutely sure that your program cannot raise any elaboration - exceptions, and you still want to use the dynamic elaboration model, - then you can use the configuration pragma - @code{Suppress (Elaboration_Checks)} to suppress all such checks. For - example this pragma could be placed in the @file{gnat.adc} file. - - @item Suppress checks selectively - When you know that certain calls in elaboration code cannot possibly - lead to an elaboration error, and the binder nevertheless generates warnings - on those calls and inserts Elaborate_All pragmas that lead to elaboration - circularities, it is possible to remove those warnings locally and obtain - a program that will bind. Clearly this can be unsafe, and it is the - responsibility of the programmer to make sure that the resulting program has - no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can - be used with different granularity to suppress warnings and break - elaboration circularities: - - @itemize @bullet - @item - Place the pragma that names the called subprogram in the declarative part - that contains the call. - - @item - Place the pragma in the declarative part, without naming an entity. This - disables warnings on all calls in the corresponding declarative region. - - @item - Place the pragma in the package spec that declares the called subprogram, - and name the subprogram. This disables warnings on all elaboration calls to - that subprogram. - - @item - Place the pragma in the package spec that declares the called subprogram, - without naming any entity. This disables warnings on all elaboration calls to - all subprograms declared in this spec. - @end itemize - - @noindent - These four cases are listed in order of decreasing safety, and therefore - require increasing programmer care in their application. Consider the - following program: - @smallexample - - package Pack1 is - function F1 return Integer; - X1 : Integer; - end Pack1; - - package Pack2 is - function F2 return Integer; - function Pure (x : integer) return integer; - -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) - -- pragma Suppress (Elaboration_Check); -- (4) - end Pack2; - - with Pack2; - package body Pack1 is - function F1 return Integer is - begin - return 100; - end F1; - Val : integer := Pack2.Pure (11); -- Elab. call (1) - begin - declare - -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) - -- pragma Suppress(Elaboration_Check); -- (2) - begin - X1 := Pack2.F2 + 1; -- Elab. call (2) - end; - end Pack1; - - with Pack1; - package body Pack2 is - function F2 return Integer is - begin - return Pack1.F1; - end F2; - function Pure (x : integer) return integer is - begin - return x ** 3 - 3 * x; - end; - end Pack2; - - with Pack1, Ada.Text_IO; - procedure Proc3 is - begin - Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 - end Proc3; - @end smallexample - In the absence of any pragmas, an attempt to bind this program produces - the following diagnostics: - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - error: elaboration circularity detected - info: "pack1 (body)" must be elaborated before "pack1 (body)" - info: reason: Elaborate_All probably needed in unit "pack1 (body)" - info: recompile "pack1 (body)" with -gnatwl for full details - info: "pack1 (body)" - info: must be elaborated along with its spec: - info: "pack1 (spec)" - info: which is withed by: - info: "pack2 (body)" - info: which must be elaborated along with its spec: - info: "pack2 (spec)" - info: which is withed by: - info: "pack1 (body)" - @end group - @end smallexample - The sources of the circularity are the two calls to @code{Pack2.Pure} and - @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to - F2 is safe, even though F2 calls F1, because the call appears after the - elaboration of the body of F1. Therefore the pragma (1) is safe, and will - remove the warning on the call. It is also possible to use pragma (2) - because there are no other potentially unsafe calls in the block. - - @noindent - The call to @code{Pure} is safe because this function does not depend on the - state of @code{Pack2}. Therefore any call to this function is safe, and it - is correct to place pragma (3) in the corresponding package spec. - - @noindent - Finally, we could place pragma (4) in the spec of @code{Pack2} to disable - warnings on all calls to functions declared therein. Note that this is not - necessarily safe, and requires more detailed examination of the subprogram - bodies involved. In particular, a call to @code{F2} requires that @code{F1} - be already elaborated. - @end table - - @noindent - It is hard to generalize on which of these four approaches should be - taken. Obviously if it is possible to fix the program so that the default - treatment works, this is preferable, but this may not always be practical. - It is certainly simple enough to use - @option{-gnatE} - but the danger in this case is that, even if the GNAT binder - finds a correct elaboration order, it may not always do so, - and certainly a binder from another Ada compiler might not. A - combination of testing and analysis (for which the warnings generated - with the - @option{-gnatwl} - switch can be useful) must be used to ensure that the program is free - of errors. One switch that is useful in this testing is the - @code{-p (pessimistic elaboration order)} - switch for - @code{gnatbind}. - Normally the binder tries to find an order that has the best chance of - of avoiding elaboration problems. With this switch, the binder - plays a devil's advocate role, and tries to choose the order that - has the best chance of failing. If your program works even with this - switch, then it has a better chance of being error free, but this is still - not a guarantee. - - For an example of this approach in action, consider the C-tests (executable - tests) from the ACVC suite. If these are compiled and run with the default - treatment, then all but one of them succeed without generating any error - diagnostics from the binder. However, there is one test that fails, and - this is not surprising, because the whole point of this test is to ensure - that the compiler can handle cases where it is impossible to determine - a correct order statically, and it checks that an exception is indeed - raised at run time. - - This one test must be compiled and run using the - @option{-gnatE} - switch, and then it passes. Alternatively, the entire suite can - be run using this switch. It is never wrong to run with the dynamic - elaboration switch if your code is correct, and we assume that the - C-tests are indeed correct (it is less efficient, but efficiency is - not a factor in running the ACVC tests.) - - @node Elaboration for Access-to-Subprogram Values - @section Elaboration for Access-to-Subprogram Values - @cindex Access-to-subprogram - - @noindent - The introduction of access-to-subprogram types in Ada 95 complicates - the handling of elaboration. The trouble is that it becomes - impossible to tell at compile time which procedure - is being called. This means that it is not possible for the binder - to analyze the elaboration requirements in this case. - - If at the point at which the access value is created - (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}), - the body of the subprogram is - known to have been elaborated, then the access value is safe, and its use - does not require a check. This may be achieved by appropriate arrangement - of the order of declarations if the subprogram is in the current unit, - or, if the subprogram is in another unit, by using pragma - @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body} - on the referenced unit. - - If the referenced body is not known to have been elaborated at the point - the access value is created, then any use of the access value must do a - dynamic check, and this dynamic check will fail and raise a - @code{Program_Error} exception if the body has not been elaborated yet. - GNAT will generate the necessary checks, and in addition, if the - @option{-gnatwl} - switch is set, will generate warnings that such checks are required. - - The use of dynamic dispatching for tagged types similarly generates - a requirement for dynamic checks, and premature calls to any primitive - operation of a tagged type before the body of the operation has been elaborated, - will result in the raising of @code{Program_Error}. - - @node Summary of Procedures for Elaboration Control - @section Summary of Procedures for Elaboration Control - @cindex Elaboration control - - @noindent - First, compile your program with the default options, using none of - the special elaboration control switches. If the binder successfully - binds your program, then you can be confident that, apart from issues - raised by the use of access-to-subprogram types and dynamic dispatching, - the program is free of elaboration errors. If it is important that the - program be portable, then use the - @option{-gnatwl} - switch to generate warnings about missing @code{Elaborate_All} - pragmas, and supply the missing pragmas. - - If the program fails to bind using the default static elaboration - handling, then you can fix the program to eliminate the binder - message, or recompile the entire program with the - @option{-gnatE} switch to generate dynamic elaboration checks, - and, if you are sure there really are no elaboration problems, - use a global pragma @code{Suppress (Elaboration_Checks)}. - - @node Other Elaboration Order Considerations - @section Other Elaboration Order Considerations - @noindent - This section has been entirely concerned with the issue of finding a valid - elaboration order, as defined by the Ada Reference Manual. In a case - where several elaboration orders are valid, the task is to find one - of the possible valid elaboration orders (and the static model in GNAT - will ensure that this is achieved). - - The purpose of the elaboration rules in the Ada Reference Manual is to - make sure that no entity is accessed before it has been elaborated. For - a subprogram, this means that the spec and body must have been elaborated - before the subprogram is called. For an object, this means that the object - must have been elaborated before its value is read or written. A violation - of either of these two requirements is an access before elaboration order, - and this section has been all about avoiding such errors. - - In the case where more than one order of elaboration is possible, in the - sense that access before elaboration errors are avoided, then any one of - the orders is "correct" in the sense that it meets the requirements of - the Ada Reference Manual, and no such error occurs. - - However, it may be the case for a given program, that there are - constraints on the order of elaboration that come not from consideration - of avoiding elaboration errors, but rather from extra-lingual logic - requirements. Consider this example: - - @smallexample - with Init_Constants; - package Constants is - X : Integer := 0; - Y : Integer := 0; - end Constants; - - package Init_Constants is - procedure Calc; - end Init_Constants; - - with Constants; - package body Init_Constants is - procedure Calc is begin null; end; - begin - Constants.X := 3; - Constants.Y := 4; - end Init_Constants; - - with Constants; - package Calc is - Z : Integer := Constants.X + Constants.Y; - end Calc; - - with Calc; - with Text_IO; use Text_IO; - procedure Main is - begin - Put_Line (Calc.Z'Img); - end Main; - @end smallexample - - @noindent - In this example, there is more than one valid order of elaboration. For - example both the following are correct orders: - - @smallexample - Init_Constants spec - Constants spec - Calc spec - Main body - Init_Constants body - - and - - Init_Constants spec - Init_Constants body - Constants spec - Calc spec - Main body - @end smallexample - - @noindent - There is no language rule to prefer one or the other, both are correct - from an order of elaboration point of view. But the programmatic effects - of the two orders are very different. In the first, the elaboration routine - of @code{Calc} initializes @code{Z} to zero, and then the main program - runs with this value of zero. But in the second order, the elaboration - routine of @code{Calc} runs after the body of Init_Constants has set - @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} - runs. - - One could perhaps by applying pretty clever non-artificial intelligence - to the situation guess that it is more likely that the second order of - elaboration is the one desired, but there is no formal linguistic reason - to prefer one over the other. In fact in this particular case, GNAT will - prefer the second order, because of the rule that bodies are elaborated - as soon as possible, but it's just luck that this is what was wanted - (if indeed the second order was preferred). - - If the program cares about the order of elaboration routines in a case like - this, it is important to specify the order required. In this particular - case, that could have been achieved by adding to the spec of Calc: - - @smallexample - pragma Elaborate_All (Constants); - @end smallexample - - @noindent - which requires that the body (if any) and spec of @code{Constants}, - as well as the body and spec of any unit @code{with}'ed by - @code{Constants} be elaborated before @code{Calc} is elaborated. - - Clearly no automatic method can always guess which alternative you require, - and if you are working with legacy code that had constraints of this kind - which were not properly specified by adding @code{Elaborate} or - @code{Elaborate_All} pragmas, then indeed it is possible that two different - compilers can choose different orders. - - The @code{gnatbind} - @code{-p} switch may be useful in smoking - out problems. This switch causes bodies to be elaborated as late as possible - instead of as early as possible. In the example above, it would have forced - the choice of the first elaboration order. If you get different results - when using this switch, and particularly if one set of results is right, - and one is wrong as far as you are concerned, it shows that you have some - missing @code{Elaborate} pragmas. For the example above, we have the - following output: - - @smallexample - gnatmake -f -q main - main - 7 - gnatmake -f -q main -bargs -p - main - 0 - @end smallexample - - @noindent - It is of course quite unlikely that both these results are correct, so - it is up to you in a case like this to investigate the source of the - difference, by looking at the two elaboration orders that are chosen, - and figuring out which is correct, and then adding the necessary - @code{Elaborate_All} pragmas to ensure the desired order. - - @node The Cross-Referencing Tools gnatxref and gnatfind - @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind} - @findex gnatxref - @findex gnatfind - - @noindent - The compiler generates cross-referencing information (unless - you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files. - This information indicates where in the source each entity is declared and - referenced. Note that entities in package Standard are not included, but - entities in all other predefined units are included in the output. - - Before using any of these two tools, you need to compile successfully your - application, so that GNAT gets a chance to generate the cross-referencing - information. - - The two tools @code{gnatxref} and @code{gnatfind} take advantage of this - information to provide the user with the capability to easily locate the - declaration and references to an entity. These tools are quite similar, - the difference being that @code{gnatfind} is intended for locating - definitions and/or references to a specified entity or entities, whereas - @code{gnatxref} is oriented to generating a full report of all - cross-references. - - To use these tools, you must not compile your application using the - @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The - GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing - information will not be generated. - - @menu - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - @end menu - - @node gnatxref Switches - @section @code{gnatxref} Switches - - @noindent - The command lines for @code{gnatxref} is: - @smallexample - $ gnatxref [switches] sourcefile1 [sourcefile2 ...] - @end smallexample - - @noindent - where - - @table @code - @item sourcefile1, sourcefile2 - identifies the source files for which a report is to be generated. The - 'with'ed units will be processed too. You must provide at least one file. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - @end table - - @noindent - The switches can be : - @table @code - @item -a - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatxref}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set @code{gnatxref} will output the parent type - reference for each matching derived types. - - @item -f - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item -g - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file to use @xref{Project Files}. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{-aI} - and @samp{-aO}. - @item -u - Output only unused symbols. This may be really useful if you give your - main compilation unit on the command line, as @code{gnatxref} will then - display every unused entity and 'with'ed package. - - @item -v - Instead of producing the default output, @code{gnatxref} will generate a - @file{tags} file that can be used by vi. For examples how to use this - feature, see @xref{Examples of gnatxref Usage}. The tags file is output - to the standard output, thus you will have to redirect it to a file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref -ag} instead of - @samp{gnatxref -a -g}. - - @node gnatfind Switches - @section @code{gnatfind} Switches - - @noindent - The command line for @code{gnatfind} is: - - @smallexample - $ gnatfind [switches] pattern[:sourcefile[:line[:column]]] - [file1 file2 ...] - @end smallexample - - @noindent - where - - @table @code - @item pattern - An entity will be output only if it matches the regular expression found - in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}. - - Omitting the pattern is equivalent to specifying @samp{*}, which - will match any entity. Note that if you do not provide a pattern, you - have to provide both a sourcefile and a line. - - Entity names are given in Latin-1, with uppercase/lowercase equivalence - for matching purposes. At the current time there is no support for - 8-bit codes other than Latin-1, or for wide characters in identifiers. - - @item sourcefile - @code{gnatfind} will look for references, bodies or declarations - of symbols referenced in @file{sourcefile}, at line @samp{line} - and column @samp{column}. See @pxref{Examples of gnatfind Usage} - for syntax examples. - - @item line - is a decimal integer identifying the line number containing - the reference to the entity (or entities) to be located. - - @item column - is a decimal integer identifying the exact location on the - line of the first character of the identifier for the - entity reference. Columns are numbered from 1. - - @item file1 file2 ... - The search will be restricted to these files. If none are given, then - the search will be done for every library file in the search path. - These file must appear only after the pattern or sourcefile. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - Not that if you specify at least one file in this part, @code{gnatfind} may - sometimes not be able to find the body of the subprograms... - - @end table - - At least one of 'sourcefile' or 'pattern' has to be present on - the command line. - - The following switches are available: - @table @code - - @item -a - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatfind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set, then @code{gnatfind} will output the parent type - reference for each matching derived types. - - @item -e - By default, @code{gnatfind} accept the simple regular expression set for - @samp{pattern}. If this switch is set, then the pattern will be - considered as full Unix-style regular expression. - - @item -f - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item -g - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file (@pxref{Project Files}) to use. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{-aI} and - @samp{-aO}. - - @item -r - By default, @code{gnatfind} will output only the information about the - declaration, body or type completion of the entities. If this switch is - set, the @code{gnatfind} will locate every reference to the entities in - the files specified on the command line (or in every file in the search - path if no file is given on the command line). - - @item -s - If this switch is set, then @code{gnatfind} will output the content - of the Ada source file lines were the entity was found. - - @item -t - If this switch is set, then @code{gnatfind} will output the type hierarchy for - the specified type. It act like -d option but recursively from parent - type to parent type. When this switch is set it is not possible to - specify more than one file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref -ag} instead of - @samp{gnatxref -a -g}. - - As stated previously, gnatfind will search in every directory in the - search path. You can force it to look only in the current directory if - you specify @code{*} at the end of the command line. - - - @node Project Files for gnatxref and gnatfind - @section Project Files for @command{gnatxref} and @command{gnatfind} - - @noindent - Project files allow a programmer to specify how to compile its - application, where to find sources,... These files are used primarily by - the Glide Ada mode, but they can also be used by the two tools - @code{gnatxref} and @code{gnatfind}. - - A project file name must end with @file{.adp}. If a single one is - present in the current directory, then @code{gnatxref} and @code{gnatfind} will - extract the information from it. If multiple project files are found, none of - them is read, and you have to use the @samp{-p} switch to specify the one - you want to use. - - The following lines can be included, even though most of them have default - values which can be used in most cases. - The lines can be entered in any order in the file. - Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of - each line. If you have multiple instances, only the last one is taken into - account. - - @table @code - @item src_dir=DIR [default: "./"] - specifies a directory where to look for source files. Multiple src_dir lines - can be specified and they will be searched in the order they - are specified. - - @item obj_dir=DIR [default: "./"] - specifies a directory where to look for object and library files. Multiple - obj_dir lines can be specified and they will be searched in the order they - are specified - - @item comp_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{comp_opt@}} notation. This is intended to store the default - switches given to @file{gnatmake} and @file{gcc}. - - @item bind_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{bind_opt@}} notation. This is intended to store the default - switches given to @file{gnatbind}. - - @item link_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{link_opt@}} notation. This is intended to store the default - switches given to @file{gnatlink}. - - @item main=EXECUTABLE [default: ""] - specifies the name of the executable for the application. This variable can - be referred to in the following lines by using the @samp{$@{main@}} notation. - - @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"] - specifies the command used to compile a single file in the application. - - @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"] - specifies the command used to recompile the whole application. - - @item run_cmd=COMMAND [default: "$@{main@}"] - specifies the command used to run the application. - - @item debug_cmd=COMMAND [default: "gdb $@{main@}"] - specifies the command used to debug the application - - @end table - - @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir} - and @samp{obj_dir} lines, and ignore the others. - - @node Regular Expressions in gnatfind and gnatxref - @section Regular Expressions in @code{gnatfind} and @code{gnatxref} - - @noindent - As specified in the section about @code{gnatfind}, the pattern can be a - regular expression. Actually, there are to set of regular expressions - which are recognized by the program : - - @table @code - @item globbing patterns - These are the most usual regular expression. They are the same that you - generally used in a Unix shell command line, or in a DOS session. - - Here is a more formal grammar : - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - regexp ::= term - term ::= elmt -- matches elmt - term ::= elmt elmt -- concatenation (elmt then elmt) - term ::= * -- any string of 0 or more characters - term ::= ? -- matches any character - term ::= [char @{char@}] -- matches any character listed - term ::= [char - char] -- matches any character in range - @end group - @end smallexample - - @item full regular expression - The second set of regular expressions is much more powerful. This is the - type of regular expressions recognized by utilities such a @file{grep}. - - The following is the form of a regular expression, expressed in Ada - reference manual style BNF is as follows - - @smallexample - @iftex - @leftskip=.5cm - @end iftex - @group - regexp ::= term @{| term@} -- alternation (term or term ...) - - term ::= item @{item@} -- concatenation (item then item) - - item ::= elmt -- match elmt - item ::= elmt * -- zero or more elmt's - item ::= elmt + -- one or more elmt's - item ::= elmt ? -- matches elmt or nothing - @end group - @group - elmt ::= nschar -- matches given character - elmt ::= [nschar @{nschar@}] -- matches any character listed - elmt ::= [^ nschar @{nschar@}] -- matches any character not listed - elmt ::= [char - char] -- matches chars in given range - elmt ::= \ char -- matches given character - elmt ::= . -- matches any single character - elmt ::= ( regexp ) -- parens used for grouping - - char ::= any character, including special characters - nschar ::= any character except ()[].*+?^ - @end group - @end smallexample - - Following are a few examples : - - @table @samp - @item abcde|fghi - will match any of the two strings 'abcde' and 'fghi'. - - @item abc*d - will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on - - @item [a-z]+ - will match any string which has only lowercase characters in it (and at - least one character - - @end table - @end table - - @node Examples of gnatxref Usage - @section Examples of @code{gnatxref} Usage - - @subsection General Usage - - @noindent - For the following examples, we will consider the following units : - - @smallexample - @group - @cartouche - main.ads: - 1: @b{with} Bar; - 2: @b{package} Main @b{is} - 3: @b{procedure} Foo (B : @b{in} Integer); - 4: C : Integer; - 5: @b{private} - 6: D : Integer; - 7: @b{end} Main; - - main.adb: - 1: @b{package body} Main @b{is} - 2: @b{procedure} Foo (B : @b{in} Integer) @b{is} - 3: @b{begin} - 4: C := B; - 5: D := B; - 6: Bar.Print (B); - 7: Bar.Print (C); - 8: @b{end} Foo; - 9: @b{end} Main; - - bar.ads: - 1: @b{package} Bar @b{is} - 2: @b{procedure} Print (B : Integer); - 3: @b{end} bar; - @end cartouche - @end group - @end smallexample - - @table @code - - @noindent - The first thing to do is to recompile your application (for instance, in - that case just by doing a @samp{gnatmake main}, so that GNAT generates - the cross-referencing information. - You can then issue any of the following commands: - - @item gnatxref main.adb - @code{gnatxref} generates cross-reference information for main.adb - and every unit 'with'ed by main.adb. - - The output would be: - @smallexample - @iftex - @leftskip=0cm - @end iftex - B Type: Integer - Decl: bar.ads 2:22 - B Type: Integer - Decl: main.ads 3:20 - Body: main.adb 2:20 - Ref: main.adb 4:13 5:13 6:19 - Bar Type: Unit - Decl: bar.ads 1:9 - Ref: main.adb 6:8 7:8 - main.ads 1:6 - C Type: Integer - Decl: main.ads 4:5 - Modi: main.adb 4:8 - Ref: main.adb 7:19 - D Type: Integer - Decl: main.ads 6:5 - Modi: main.adb 5:8 - Foo Type: Unit - Decl: main.ads 3:15 - Body: main.adb 2:15 - Main Type: Unit - Decl: main.ads 2:9 - Body: main.adb 1:14 - Print Type: Unit - Decl: bar.ads 2:15 - Ref: main.adb 6:12 7:12 - @end smallexample - - @noindent - that is the entity @code{Main} is declared in main.ads, line 2, column 9, - its body is in main.adb, line 1, column 14 and is not referenced any where. - - The entity @code{Print} is declared in bar.ads, line 2, column 15 and it - it referenced in main.adb, line 6 column 12 and line 7 column 12. - - @item gnatxref package1.adb package2.ads - @code{gnatxref} will generates cross-reference information for - package1.adb, package2.ads and any other package 'with'ed by any - of these. - - @end table - - @subsection Using gnatxref with vi - - @code{gnatxref} can generate a tags file output, which can be used - directly from @file{vi}. Note that the standard version of @file{vi} - will not work properly with overloaded symbols. Consider using another - free implementation of @file{vi}, such as @file{vim}. - - @smallexample - $ gnatxref -v gnatfind.adb > tags - @end smallexample - - @noindent - will generate the tags file for @code{gnatfind} itself (if the sources - are in the search path!). - - From @file{vi}, you can then use the command @samp{:tag @i{entity}} - (replacing @i{entity} by whatever you are looking for), and vi will - display a new file with the corresponding declaration of entity. - - @node Examples of gnatfind Usage - @section Examples of @code{gnatfind} Usage - - @table @code - - @item gnatfind -f xyz:main.adb - Find declarations for all entities xyz referenced at least once in - main.adb. The references are search in every library file in the search - path. - - The directories will be printed as well (as the @samp{-f} - switch is set) - - The output will look like: - @smallexample - directory/main.ads:106:14: xyz <= declaration - directory/main.adb:24:10: xyz <= body - directory/foo.ads:45:23: xyz <= declaration - @end smallexample - - @noindent - that is to say, one of the entities xyz found in main.adb is declared at - line 12 of main.ads (and its body is in main.adb), and another one is - declared at line 45 of foo.ads - - @item gnatfind -fs xyz:main.adb - This is the same command as the previous one, instead @code{gnatfind} will - display the content of the Ada source file lines. - - The output will look like: - - @smallexample - directory/main.ads:106:14: xyz <= declaration - procedure xyz; - directory/main.adb:24:10: xyz <= body - procedure xyz is - directory/foo.ads:45:23: xyz <= declaration - xyz : Integer; - @end smallexample - - @noindent - This can make it easier to find exactly the location your are looking - for. - - @item gnatfind -r "*x*":main.ads:123 foo.adb - Find references to all entities containing an x that are - referenced on line 123 of main.ads. - The references will be searched only in main.adb and foo.adb. - - @item gnatfind main.ads:123 - Find declarations and bodies for all entities that are referenced on - line 123 of main.ads. - - This is the same as @code{gnatfind "*":main.adb:123}. - - @item gnatfind mydir/main.adb:123:45 - Find the declaration for the entity referenced at column 45 in - line 123 of file main.adb in directory mydir. Note that it - is usual to omit the identifier name when the column is given, - since the column position identifies a unique reference. - - The column has to be the beginning of the identifier, and should not - point to any character in the middle of the identifier. - - @end table - - @node File Name Krunching Using gnatkr - @chapter File Name Krunching Using @code{gnatkr} - @findex gnatkr - - @noindent - This chapter discusses the method used by the compiler to shorten - the default file names chosen for Ada units so that they do not - exceed the maximum length permitted. It also describes the - @code{gnatkr} utility that can be used to determine the result of - applying this shortening. - @menu - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - @end menu - - @node About gnatkr - @section About @code{gnatkr} - - @noindent - The default file naming rule in GNAT - is that the file name must be derived from - the unit name. The exact default rule is as follows: - @itemize @bullet - @item - Take the unit name and replace all dots by hyphens. - @item - If such a replacement occurs in the - second character position of a name, and the first character is - a, g, s, or i then replace the dot by the character - ~ (tilde) - instead of a minus. - @end itemize - The reason for this exception is to avoid clashes - with the standard names for children of System, Ada, Interfaces, - and GNAT, which use the prefixes s- a- i- and g- - respectively. - - The @code{-gnatk@var{nn}} - switch of the compiler activates a "krunching" - circuit that limits file names to nn characters (where nn is a decimal - integer). For example, using OpenVMS, - where the maximum file name length is - 39, the value of nn is usually set to 39, but if you want to generate - a set of files that would be usable if ported to a system with some - different maximum file length, then a different value can be specified. - The default value of 39 for OpenVMS need not be specified. - - The @code{gnatkr} utility can be used to determine the krunched name for - a given file, when krunched to a specified maximum length. - - @node Using gnatkr - @section Using @code{gnatkr} - - @noindent - The @code{gnatkr} command has the form - - @smallexample - $ gnatkr @var{name} [@var{length}] - @end smallexample - - - @noindent - @var{name} can be an Ada name with dots or the GNAT name of the unit, - where the dots representing child units or subunit are replaced by - hyphens. The only confusion arises if a name ends in @code{.ads} or - @code{.adb}. @code{gnatkr} takes this to be an extension if there are - no other dots in the name and the whole name is in lowercase. - - @var{length} represents the length of the krunched name. The default - when no argument is given is 8 characters. A length of zero stands for - unlimited, in other words do not chop except for system files which are - always 8. - - @noindent - The output is the krunched name. The output has an extension only if the - original argument was a file name with an extension. - - @node Krunching Method - @section Krunching Method - - @noindent - The initial file name is determined by the name of the unit that the file - contains. The name is formed by taking the full expanded name of the - unit and replacing the separating dots with hyphens and - using lowercase - for all letters, except that a hyphen in the second character position is - replaced by a tilde if the first character is - a, i, g, or s. - The extension is @code{.ads} for a - specification and @code{.adb} for a body. - Krunching does not affect the extension, but the file name is shortened to - the specified length by following these rules: - - @itemize @bullet - @item - The name is divided into segments separated by hyphens, tildes or - underscores and all hyphens, tildes, and underscores are - eliminated. If this leaves the name short enough, we are done. - - @item - If the name is too long, the longest segment is located (left-most if there are two - of equal length), and shortened by dropping its last character. This is - repeated until the name is short enough. - - As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb} - to fit the name into 8 characters as required by some operating systems. - - @smallexample - our-strings-wide_fixed 22 - our strings wide fixed 19 - our string wide fixed 18 - our strin wide fixed 17 - our stri wide fixed 16 - our stri wide fixe 15 - our str wide fixe 14 - our str wid fixe 13 - our str wid fix 12 - ou str wid fix 11 - ou st wid fix 10 - ou st wi fix 9 - ou st wi fi 8 - Final file name: oustwifi.adb - @end smallexample - - @item - The file names for all predefined units are always krunched to eight - characters. The krunching of these predefined units uses the following - special prefix replacements: - - @table @file - @item ada- - replaced by @file{a-} - - @item gnat- - replaced by @file{g-} - - @item interfaces- - replaced by @file{i-} - - @item system- - replaced by @file{s-} - @end table - - These system files have a hyphen in the second character position. That - is why normal user files replace such a character with a - tilde, to - avoid confusion with system file names. - - As an example of this special rule, consider - @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows: - - @smallexample - ada-strings-wide_fixed 22 - a- strings wide fixed 18 - a- string wide fixed 17 - a- strin wide fixed 16 - a- stri wide fixed 15 - a- stri wide fixe 14 - a- str wide fixe 13 - a- str wid fixe 12 - a- str wid fix 11 - a- st wid fix 10 - a- st wi fix 9 - a- st wi fi 8 - Final file name: a-stwifi.adb - @end smallexample - @end itemize - - Of course no file shortening algorithm can guarantee uniqueness over all - possible unit names, and if file name krunching is used then it is your - responsibility to ensure that no name clashes occur. The utility - program @code{gnatkr} is supplied for conveniently determining the - krunched name of a file. - - @node Examples of gnatkr Usage - @section Examples of @code{gnatkr} Usage - - @smallexample - @iftex - @leftskip=0cm - @end iftex - $ gnatkr very_long_unit_name.ads --> velounna.ads - $ gnatkr grandparent-parent-child.ads --> grparchi.ads - $ gnatkr Grandparent.Parent.Child --> grparchi - $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads - $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads - @end smallexample - - @node Preprocessing Using gnatprep - @chapter Preprocessing Using @code{gnatprep} - @findex gnatprep - - @noindent - The @code{gnatprep} utility provides - a simple preprocessing capability for Ada programs. - It is designed for use with GNAT, but is not dependent on any special - features of GNAT. - - @menu - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - @end menu - - @node Using gnatprep - @section Using @code{gnatprep} - - @noindent - To call @code{gnatprep} use - - @smallexample - $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile] - @end smallexample - - @noindent - where - @table @code - @item infile - is the full name of the input file, which is an Ada source - file containing preprocessor directives. - - @item outfile - is the full name of the output file, which is an Ada source - in standard Ada form. When used with GNAT, this file name will - normally have an ads or adb suffix. - - @item deffile - is the full name of a text file containing definitions of - symbols to be referenced by the preprocessor. This argument is - optional, and can be replaced by the use of the @code{-D} switch. - - @item switches - is an optional sequence of switches as described in the next section. - @end table - - @node Switches for gnatprep - @section Switches for @code{gnatprep} - - @table @code - - @item -b - Causes both preprocessor lines and the lines deleted by - preprocessing to be replaced by blank lines in the output source file, - preserving line numbers in the output file. - - @item -c - Causes both preprocessor lines and the lines deleted - by preprocessing to be retained in the output source as comments marked - with the special string "--! ". This option will result in line numbers - being preserved in the output file. - - @item -Dsymbol=value - Defines a new symbol, associated with value. If no value is given on the - command line, then symbol is considered to be @code{True}. This switch - can be used in place of a definition file. - - - @item -r - Causes a @code{Source_Reference} pragma to be generated that - references the original input file, so that error messages will use - the file name of this original file. The use of this switch implies - that preprocessor lines are not to be removed from the file, so its - use will force @code{-b} mode if - @code{-c} - has not been specified explicitly. - - Note that if the file to be preprocessed contains multiple units, then - it will be necessary to @code{gnatchop} the output file from - @code{gnatprep}. If a @code{Source_Reference} pragma is present - in the preprocessed file, it will be respected by - @code{gnatchop -r} - so that the final chopped files will correctly refer to the original - input source file for @code{gnatprep}. - - @item -s - Causes a sorted list of symbol names and values to be - listed on the standard output file. - - @item -u - Causes undefined symbols to be treated as having the value FALSE in the context - of a preprocessor test. In the absence of this option, an undefined symbol in - a @code{#if} or @code{#elsif} test will be treated as an error. - - @end table - - @noindent - Note: if neither @code{-b} nor @code{-c} is present, - then preprocessor lines and - deleted lines are completely removed from the output, unless -r is - specified, in which case -b is assumed. - - @node Form of Definitions File - @section Form of Definitions File - - @noindent - The definitions file contains lines of the form - - @smallexample - symbol := value - @end smallexample - - @noindent - where symbol is an identifier, following normal Ada (case-insensitive) - rules for its syntax, and value is one of the following: - - @itemize @bullet - @item - Empty, corresponding to a null substitution - @item - A string literal using normal Ada syntax - @item - Any sequence of characters from the set - (letters, digits, period, underline). - @end itemize - - @noindent - Comment lines may also appear in the definitions file, starting with - the usual @code{--}, - and comments may be added to the definitions lines. - - @node Form of Input Text for gnatprep - @section Form of Input Text for @code{gnatprep} - - @noindent - The input text may contain preprocessor conditional inclusion lines, - as well as general symbol substitution sequences. - - The preprocessor conditional inclusion commands have the form - - @smallexample - @group - @cartouche - #if @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - ... - #else - lines - #end if; - @end cartouche - @end group - @end smallexample - - @noindent - In this example, @i{expression} is defined by the following grammar: - @smallexample - @i{expression} ::= - @i{expression} ::= = "" - @i{expression} ::= = - @i{expression} ::= 'Defined - @i{expression} ::= not @i{expression} - @i{expression} ::= @i{expression} and @i{expression} - @i{expression} ::= @i{expression} or @i{expression} - @i{expression} ::= @i{expression} and then @i{expression} - @i{expression} ::= @i{expression} or else @i{expression} - @i{expression} ::= ( @i{expression} ) - @end smallexample - - @noindent - For the first test (@i{expression} ::= ) the symbol must have - either the value true or false, that is to say the right-hand of the - symbol definition must be one of the (case-insensitive) literals - @code{True} or @code{False}. If the value is true, then the - corresponding lines are included, and if the value is false, they are - excluded. - - The test (@i{expression} ::= @code{'Defined}) is true only if - the symbol has been defined in the definition file or by a @code{-D} - switch on the command line. Otherwise, the test is false. - - The equality tests are case insensitive, as are all the preprocessor lines. - - If the symbol referenced is not defined in the symbol definitions file, - then the effect depends on whether or not switch @code{-u} - is specified. If so, then the symbol is treated as if it had the value - false and the test fails. If this switch is not specified, then - it is an error to reference an undefined symbol. It is also an error to - reference a symbol that is defined with a value other than @code{True} - or @code{False}. - - The use of the @code{not} operator inverts the sense of this logical test, so - that the lines are included only if the symbol is not defined. - The @code{then} keyword is optional as shown - - The @code{#} must be the first non-blank character on a line, but - otherwise the format is free form. Spaces or tabs may appear between - the @code{#} and the keyword. The keywords and the symbols are case - insensitive as in normal Ada code. Comments may be used on a - preprocessor line, but other than that, no other tokens may appear on a - preprocessor line. Any number of @code{elsif} clauses can be present, - including none at all. The @code{else} is optional, as in Ada. - - The @code{#} marking the start of a preprocessor line must be the first - non-blank character on the line, i.e. it must be preceded only by - spaces or horizontal tabs. - - Symbol substitution outside of preprocessor lines is obtained by using - the sequence - - @smallexample - $symbol - @end smallexample - - @noindent - anywhere within a source line, except in a comment or within a - string literal. The identifier - following the @code{$} must match one of the symbols defined in the symbol - definition file, and the result is to substitute the value of the - symbol in place of @code{$symbol} in the output file. - - Note that although the substitution of strings within a string literal - is not possible, it is possible to have a symbol whose defined value is - a string literal. So instead of setting XYZ to @code{hello} and writing: - - @smallexample - Header : String := "$XYZ"; - @end smallexample - - @noindent - you should set XYZ to @code{"hello"} and write: - - @smallexample - Header : String := $XYZ; - @end smallexample - - @noindent - and then the substitution will occur as desired. - - - @node The GNAT Library Browser gnatls - @chapter The GNAT Library Browser @code{gnatls} - @findex gnatls - @cindex Library browser - - @noindent - @code{gnatls} is a tool that outputs information about compiled - units. It gives the relationship between objects, unit names and source - files. It can also be used to check the source dependencies of a unit - as well as various characteristics. - - @menu - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - @end menu - - @node Running gnatls - @section Running @code{gnatls} - - @noindent - The @code{gnatls} command has the form - - @smallexample - $ gnatls switches @var{object_or_ali_file} - @end smallexample - - @noindent - The main argument is the list of object or @file{ali} files - (@pxref{The Ada Library Information Files}) - for which information is requested. - - In normal mode, without additional option, @code{gnatls} produces a - four-column listing. Each line represents information for a specific - object. The first column gives the full path of the object, the second - column gives the name of the principal unit in this object, the third - column gives the status of the source and the fourth column gives the - full path of the source representing this unit. - Here is a simple example of use: - - @smallexample - $ gnatls *.o - ./demo1.o demo1 DIF demo1.adb - ./demo2.o demo2 OK demo2.adb - ./hello.o h1 OK hello.adb - ./instr-child.o instr.child MOK instr-child.adb - ./instr.o instr OK instr.adb - ./tef.o tef DIF tef.adb - ./text_io_example.o text_io_example OK text_io_example.adb - ./tgef.o tgef DIF tgef.adb - @end smallexample - - @noindent - The first line can be interpreted as follows: the main unit which is - contained in - object file @file{demo1.o} is demo1, whose main source is in - @file{demo1.adb}. Furthermore, the version of the source used for the - compilation of demo1 has been modified (DIF). Each source file has a status - qualifier which can be: - - @table @code - @item OK (unchanged) - The version of the source file used for the compilation of the - specified unit corresponds exactly to the actual source file. - - @item MOK (slightly modified) - The version of the source file used for the compilation of the - specified unit differs from the actual source file but not enough to - require recompilation. If you use gnatmake with the qualifier - @code{-m (minimal recompilation)}, a file marked - MOK will not be recompiled. - - @item DIF (modified) - No version of the source found on the path corresponds to the source - used to build this object. - - @item ??? (file not found) - No source file was found for this unit. - - @item HID (hidden, unchanged version not first on PATH) - The version of the source that corresponds exactly to the source used - for compilation has been found on the path but it is hidden by another - version of the same source that has been modified. - - @end table - - @node Switches for gnatls - @section Switches for @code{gnatls} - - @noindent - @code{gnatls} recognizes the following switches: - - @table @code - @item -a - @cindex @code{-a} (@code{gnatls}) - Consider all units, including those of the predefined Ada library. - Especially useful with @code{-d}. - - @item -d - @cindex @code{-d} (@code{gnatls}) - List sources from which specified units depend on. - - @item -h - @cindex @code{-h} (@code{gnatls}) - Output the list of options. - - @item -o - @cindex @code{-o} (@code{gnatls}) - Only output information about object files. - - @item -s - @cindex @code{-s} (@code{gnatls}) - Only output information about source files. - - @item -u - @cindex @code{-u} (@code{gnatls}) - Only output information about compilation units. - - @item -aO@var{dir} - @itemx -aI@var{dir} - @itemx -I@var{dir} - @itemx -I- - @itemx -nostdinc - Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags - (see @ref{Switches for gnatmake}). - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatls}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -v - @cindex @code{-s} (@code{gnatls}) - Verbose mode. Output the complete source and object paths. Do not use - the default column layout but instead use long format giving as much as - information possible on each requested units, including special - characteristics such as: - - @table @code - @item Preelaborable - The unit is preelaborable in the Ada 95 sense. - - @item No_Elab_Code - No elaboration code has been produced by the compiler for this unit. - - @item Pure - The unit is pure in the Ada 95 sense. - - @item Elaborate_Body - The unit contains a pragma Elaborate_Body. - - @item Remote_Types - The unit contains a pragma Remote_Types. - - @item Shared_Passive - The unit contains a pragma Shared_Passive. - - @item Predefined - This unit is part of the predefined environment and cannot be modified - by the user. - - @item Remote_Call_Interface - The unit contains a pragma Remote_Call_Interface. - - @end table - - @end table - - @node Examples of gnatls Usage - @section Example of @code{gnatls} Usage - - @noindent - Example of using the verbose switch. Note how the source and - object paths are affected by the -I switch. - - @smallexample - $ gnatls -v -I.. demo1.o - - GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc. - - Source Search Path: - - ../ - /home/comar/local/adainclude/ - - Object Search Path: - - ../ - /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/ - - ./demo1.o - Unit => - Name => demo1 - Kind => subprogram body - Flags => No_Elab_Code - Source => demo1.adb modified - @end smallexample - - @noindent - The following is an example of use of the dependency list. - Note the use of the -s switch - which gives a straight list of source files. This can be useful for - building specialized scripts. - - @smallexample - $ gnatls -d demo2.o - ./demo2.o demo2 OK demo2.adb - OK gen_list.ads - OK gen_list.adb - OK instr.ads - OK instr-child.ads - - $ gnatls -d -s -a demo1.o - demo1.adb - /home/comar/local/adainclude/ada.ads - /home/comar/local/adainclude/a-finali.ads - /home/comar/local/adainclude/a-filico.ads - /home/comar/local/adainclude/a-stream.ads - /home/comar/local/adainclude/a-tags.ads - gen_list.ads - gen_list.adb - /home/comar/local/adainclude/gnat.ads - /home/comar/local/adainclude/g-io.ads - instr.ads - /home/comar/local/adainclude/system.ads - /home/comar/local/adainclude/s-exctab.ads - /home/comar/local/adainclude/s-finimp.ads - /home/comar/local/adainclude/s-finroo.ads - /home/comar/local/adainclude/s-secsta.ads - /home/comar/local/adainclude/s-stalib.ads - /home/comar/local/adainclude/s-stoele.ads - /home/comar/local/adainclude/s-stratt.ads - /home/comar/local/adainclude/s-tasoli.ads - /home/comar/local/adainclude/s-unstyp.ads - /home/comar/local/adainclude/unchconv.ads - @end smallexample - - - @node GNAT and Libraries - @chapter GNAT and Libraries - @cindex Library, building, installing - - @noindent - This chapter addresses some of the issues related to building and using - a library with GNAT. It also shows how the GNAT run-time library can be - recompiled. - - @menu - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - @end menu - - @node Creating an Ada Library - @section Creating an Ada Library - - @noindent - In the GNAT environment, a library has two components: - @itemize @bullet - @item - Source files. - @item - Compiled code and Ali files. See @ref{The Ada Library Information Files}. - @end itemize - - @noindent - In order to use other packages @ref{The GNAT Compilation Model} - requires a certain number of sources to be available to the compiler. - The minimal set of - sources required includes the specs of all the packages that make up the - visible part of the library as well as all the sources upon which they - depend. The bodies of all visible generic units must also be provided. - @noindent - Although it is not strictly mandatory, it is recommended that all sources - needed to recompile the library be provided, so that the user can make - full use of inter-unit inlining and source-level debugging. This can also - make the situation easier for users that need to upgrade their compilation - toolchain and thus need to recompile the library from sources. - - @noindent - The compiled code can be provided in different ways. The simplest way is - to provide directly the set of objects produced by the compiler during - the compilation of the library. It is also possible to group the objects - into an archive using whatever commands are provided by the operating - system. Finally, it is also possible to create a shared library (see - option -shared in the GCC manual). - - @noindent - There are various possibilities for compiling the units that make up the - library: for example with a Makefile @ref{Using the GNU make Utility}, - or with a conventional script. - For simple libraries, it is also possible to create a - dummy main program which depends upon all the packages that comprise the - interface of the library. This dummy main program can then be given to - gnatmake, in order to build all the necessary objects. Here is an example - of such a dummy program and the generic commands used to build an - archive or a shared library. - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - @b{with} My_Lib.Service1; - @b{with} My_Lib.Service2; - @b{with} My_Lib.Service3; - @b{procedure} My_Lib_Dummy @b{is} - @b{begin} - @b{null}; - @b{end}; - - # compiling the library - $ gnatmake -c my_lib_dummy.adb - - # we don't need the dummy object itself - $ rm my_lib_dummy.o my_lib_dummy.ali - - # create an archive with the remaining objects - $ ar rc libmy_lib.a *.o - # some systems may require "ranlib" to be run as well - - # or create a shared library - $ gcc -shared -o libmy_lib.so *.o - # some systems may require the code to have been compiled with -fPIC - @end smallexample - - @noindent - When the objects are grouped in an archive or a shared library, the user - needs to specify the desired library at link time, unless a pragma - linker_options has been used in one of the sources: - @smallexample - @b{pragma} Linker_Options ("-lmy_lib"); - @end smallexample - - @node Installing an Ada Library - @section Installing an Ada Library - - @noindent - In the GNAT model, installing a library consists in copying into a specific - location the files that make up this library. It is possible to install - the sources in a different directory from the other files (ALI, objects, - archives) since the source path and the object path can easily be - specified separately. - - @noindent - For general purpose libraries, it is possible for the system - administrator to put those libraries in the default compiler paths. To - achieve this, he must specify their location in the configuration files - "ada_source_path" and "ada_object_path" that must be located in the GNAT - installation tree at the same place as the gcc spec file. The location of - the gcc spec file can be determined as follows: - @smallexample - $ gcc -v - @end smallexample - - @noindent - The configuration files mentioned above have simple format: each line in them - must contain one unique - directory name. Those names are added to the corresponding path - in their order of appearance in the file. The names can be either absolute - or relative, in the latter case, they are relative to where theses files - are located. - - @noindent - "ada_source_path" and "ada_object_path" might actually not be present in a - GNAT installation, in which case, GNAT will look for its run-time library in - the directories "adainclude" for the sources and "adalib" for the - objects and ALI files. When the files exist, the compiler does not - look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file - must contain the location for the GNAT run-time sources (which can simply - be "adainclude"). In the same way, the "ada_object_path" file must contain - the location for the GNAT run-time objects (which can simply - be "adalib"). - - @noindent - You can also specify a new default path to the runtime library at compilation - time with the switch "--RTS=@var{rts-path}". You can easily choose and change - the runtime you want your program to be compiled with. This switch is - recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref. - - @noindent - It is possible to install a library before or after the standard GNAT - library, by reordering the lines in the configuration files. In general, a - library must be installed before the GNAT library if it redefines any part of it. - - @node Using an Ada Library - @section Using an Ada Library - - @noindent - In order to use a Ada library, you need to make sure that this - library is on both your source and object path - @ref{Search Paths and the Run-Time Library (RTL)} - and @ref{Search Paths for gnatbind}. For - instance, you can use the library "mylib" installed in "/dir/my_lib_src" - and "/dir/my_lib_obj" with the following commands: - - @smallexample - $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \ - -largs -lmy_lib - @end smallexample - - @noindent - This can be simplified down to the following: - @smallexample - $ gnatmake my_appl - @end smallexample - when the following conditions are met: - @itemize @bullet - @item - "/dir/my_lib_src" has been added by the user to the environment - variable "ADA_INCLUDE_PATH", or by the administrator to the file - "ada_source_path" - @item - "/dir/my_lib_obj" has been added by the user to the environment - variable "ADA_OBJECTS_PATH", or by the administrator to the file - "ada_object_path" - @item - a pragma linker_options, as mentioned in @ref{Creating an Ada Library} - as been added to the sources. - @end itemize - @noindent - - @node Creating an Ada Library to be Used in a Non-Ada Context - @section Creating an Ada Library to be Used in a Non-Ada Context - - @noindent - The previous sections detailed how to create and install a library that - was usable from an Ada main program. Using this library in a non-Ada - context is not possible, because the elaboration of the library is - automatically done as part of the main program elaboration. - - GNAT also provides the ability to build libraries that can be used both - in an Ada and non-Ada context. This section describes how to build such - a library, and then how to use it from a C program. The method for - interfacing with the library from other languages such as Fortran for - instance remains the same. - - @subsection Creating the Library - - @itemize @bullet - @item Identify the units representing the interface of the library. - - Here is an example of simple library interface: - - @smallexample - package Interface is - - procedure Do_Something; - - procedure Do_Something_Else; - - end Interface; - @end smallexample - - @item Use @code{pragma Export} or @code{pragma Convention} for the - exported entities. - - Our package @code{Interface} is then updated as follow: - @smallexample - package Interface is - - procedure Do_Something; - pragma Export (C, Do_Something, "do_something"); - - procedure Do_Something_Else; - pragma Export (C, Do_Something_Else, "do_something_else"); - - end Interface; - @end smallexample - - @item Compile all the units composing the library. - - @item Bind the library objects. - - This step is performed by invoking gnatbind with the @code{-L} - switch. @code{gnatbind} will then generate the library elaboration - procedure (named @code{init}) and the run-time finalization - procedure (named @code{final}). - - @smallexample - # generate the binder file in Ada - $ gnatbind -Lmylib interface - - # generate the binder file in C - $ gnatbind -C -Lmylib interface - @end smallexample - - @item Compile the files generated by the binder - - @smallexample - $ gcc -c b~interface.adb - @end smallexample - - @item Create the library; - - The procedure is identical to the procedure explained in - @ref{Creating an Ada Library}, - except that @file{b~interface.o} needs to be added to - the list of objects. - - @smallexample - # create an archive file - $ ar cr libmylib.a b~interface.o - - # create a shared library - $ gcc -shared -o libmylib.so b~interface.o - @end smallexample - - @item Provide a "foreign" view of the library interface; - - The example below shows the content of @code{mylib_interface.h} (note - that there is no rule for the naming of this file, any name can be used) - @smallexample - /* the library elaboration procedure */ - extern void mylibinit (void); - - /* the library finalization procedure */ - extern void mylibfinal (void); - - /* the interface exported by the library */ - extern void do_something (void); - extern void do_something_else (void); - @end smallexample - @end itemize - - @subsection Using the Library - - @noindent - Libraries built as explained above can be used from any program, provided - that the elaboration procedures (named @code{mylibinit} in the previous - example) are called before the library services are used. Any number of - libraries can be used simultaneously, as long as the elaboration - procedure of each library is called. - - Below is an example of C program that uses our @code{mylib} library. - - @smallexample - #include "mylib_interface.h" - - int - main (void) - @{ - /* First, elaborate the library before using it */ - mylibinit (); - - /* Main program, using the library exported entities */ - do_something (); - do_something_else (); - - /* Library finalization at the end of the program */ - mylibfinal (); - return 0; - @} - @end smallexample - - @noindent - Note that this same library can be used from an equivalent Ada main - program. In addition, if the libraries are installed as detailed in - @ref{Installing an Ada Library}, it is not necessary to invoke the - library elaboration and finalization routines. The binder will ensure - that this is done as part of the main program elaboration and - finalization phases. - - @subsection The Finalization Phase - - @noindent - Invoking any library finalization procedure generated by @code{gnatbind} - shuts down the Ada run time permanently. Consequently, the finalization - of all Ada libraries must be performed at the end of the program. No - call to these libraries nor the Ada run time should be made past the - finalization phase. - - @subsection Restrictions in Libraries - - @noindent - The pragmas listed below should be used with caution inside libraries, - as they can create incompatibilities with other Ada libraries: - @itemize @bullet - @item pragma @code{Locking_Policy} - @item pragma @code{Queuing_Policy} - @item pragma @code{Task_Dispatching_Policy} - @item pragma @code{Unreserve_All_Interrupts} - @end itemize - When using a library that contains such pragmas, the user must make sure - that all libraries use the same pragmas with the same values. Otherwise, - a @code{Program_Error} will - be raised during the elaboration of the conflicting - libraries. The usage of these pragmas and its consequences for the user - should therefore be well documented. - - Similarly, the traceback in exception occurrences mechanism should be - enabled or disabled in a consistent manner across all libraries. - Otherwise, a Program_Error will be raised during the elaboration of the - conflicting libraries. - - If the @code{'Version} and @code{'Body_Version} - attributes are used inside a library, then it is necessary to - perform a @code{gnatbind} step that mentions all ali files in all - libraries, so that version identifiers can be properly computed. - In practice these attributes are rarely used, so this is unlikely - to be a consideration. - - @node Rebuilding the GNAT Run-Time Library - @section Rebuilding the GNAT Run-Time Library - - @noindent - It may be useful to recompile the GNAT library in various contexts, the - most important one being the use of partition-wide configuration pragmas - such as Normalize_Scalar. A special Makefile called - @code{Makefile.adalib} is provided to that effect and can be found in - the directory containing the GNAT library. The location of this - directory depends on the way the GNAT environment has been installed and can - be determined by means of the command: - - @smallexample - $ gnatls -v - @end smallexample - - @noindent - The last entry in the object search path usually contains the - gnat library. This Makefile contains its own documentation and in - particular the set of instructions needed to rebuild a new library and - to use it. - - @node Using the GNU make Utility - @chapter Using the GNU @code{make} Utility - @findex make - - @noindent - This chapter offers some examples of makefiles that solve specific - problems. It does not explain how to write a makefile (see the GNU make - documentation), nor does it try to replace the @code{gnatmake} utility - (@pxref{The GNAT Make Program gnatmake}). - - All the examples in this section are specific to the GNU version of - make. Although @code{make} is a standard utility, and the basic language - is the same, these examples use some advanced features found only in - @code{GNU make}. - - @menu - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - @end menu - - @node Using gnatmake in a Makefile - @section Using gnatmake in a Makefile - @findex makefile - @cindex GNU make - - @noindent - Complex project organizations can be handled in a very powerful way by - using GNU make combined with gnatmake. For instance, here is a Makefile - which allows you to build each subsystem of a big project into a separate - shared library. Such a makefile allows you to significantly reduce the link - time of very big applications while maintaining full coherence at - each step of the build process. - - The list of dependencies are handled automatically by - @code{gnatmake}. The Makefile is simply used to call gnatmake in each of - the appropriate directories. - - Note that you should also read the example on how to automatically - create the list of directories (@pxref{Automatically Creating a List of Directories}) - which might help you in case your project has a lot of - subdirectories. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - ## This Makefile is intended to be used with the following directory - ## configuration: - ## - The sources are split into a series of csc (computer software components) - ## Each of these csc is put in its own directory. - ## Their name are referenced by the directory names. - ## They will be compiled into shared library (although this would also work - ## with static libraries - ## - The main program (and possibly other packages that do not belong to any - ## csc is put in the top level directory (where the Makefile is). - ## toplevel_dir __ first_csc (sources) __ lib (will contain the library) - ## \_ second_csc (sources) __ lib (will contain the library) - ## \_ ... - ## Although this Makefile is build for shared library, it is easy to modify - ## to build partial link objects instead (modify the lines with -shared and - ## gnatlink below) - ## - ## With this makefile, you can change any file in the system or add any new - ## file, and everything will be recompiled correctly (only the relevant shared - ## objects will be recompiled, and the main program will be re-linked). - - # The list of computer software component for your project. This might be - # generated automatically. - CSC_LIST=aa bb cc - - # Name of the main program (no extension) - MAIN=main - - # If we need to build objects with -fPIC, uncomment the following line - #NEED_FPIC=-fPIC - - # The following variable should give the directory containing libgnat.so - # You can get this directory through 'gnatls -v'. This is usually the last - # directory in the Object_Path. - GLIB=... - - # The directories for the libraries - # (This macro expands the list of CSC to the list of shared libraries, you - # could simply use the expanded form : - # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so - LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@} - - $@{MAIN@}: objects $@{LIB_DIR@} - gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared - gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@} - - objects:: - # recompile the sources - gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@} - - # Note: In a future version of GNAT, the following commands will be simplified - # by a new tool, gnatmlib - $@{LIB_DIR@}: - mkdir -p $@{dir $@@ @} - cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat - cd $@{dir $@@ @}; cp -f ../*.ali . - - # The dependencies for the modules - # Note that we have to force the expansion of *.o, since in some cases make won't - # be able to do it itself. - aa/lib/libaa.so: $@{wildcard aa/*.o@} - bb/lib/libbb.so: $@{wildcard bb/*.o@} - cc/lib/libcc.so: $@{wildcard cc/*.o@} - - # Make sure all of the shared libraries are in the path before starting the - # program - run:: - LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@} - - clean:: - $@{RM@} -rf $@{CSC_LIST:%=%/lib@} - $@{RM@} $@{CSC_LIST:%=%/*.ali@} - $@{RM@} $@{CSC_LIST:%=%/*.o@} - $@{RM@} *.o *.ali $@{MAIN@} - @end smallexample - - @node Automatically Creating a List of Directories - @section Automatically Creating a List of Directories - - @noindent - In most makefiles, you will have to specify a list of directories, and - store it in a variable. For small projects, it is often easier to - specify each of them by hand, since you then have full control over what - is the proper order for these directories, which ones should be - included... - - However, in larger projects, which might involve hundreds of - subdirectories, it might be more convenient to generate this list - automatically. - - The example below presents two methods. The first one, although less - general, gives you more control over the list. It involves wildcard - characters, that are automatically expanded by @code{make}. Its - shortcoming is that you need to explicitly specify some of the - organization of your project, such as for instance the directory tree - depth, whether some directories are found in a separate tree,... - - The second method is the most general one. It requires an external - program, called @code{find}, which is standard on all Unix systems. All - the directories found under a given root directory will be added to the - list. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # The examples below are based on the following directory hierarchy: - # All the directories can contain any number of files - # ROOT_DIRECTORY -> a -> aa -> aaa - # -> ab - # -> ac - # -> b -> ba -> baa - # -> bb - # -> bc - # This Makefile creates a variable called DIRS, that can be reused any time - # you need this list (see the other examples in this section) - - # The root of your project's directory hierarchy - ROOT_DIRECTORY=. - - #### - # First method: specify explicitly the list of directories - # This allows you to specify any subset of all the directories you need. - #### - - DIRS := a/aa/ a/ab/ b/ba/ - - #### - # Second method: use wildcards - # Note that the argument(s) to wildcard below should end with a '/'. - # Since wildcards also return file names, we have to filter them out - # to avoid duplicate directory names. - # We thus use make's @code{dir} and @code{sort} functions. - # It sets DIRs to the following value (note that the directories aaa and baa - # are not given, unless you change the arguments to wildcard). - # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/ - #### - - DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@} - - #### - # Third method: use an external program - # This command is much faster if run on local disks, avoiding NFS slowdowns. - # This is the most complete command: it sets DIRs to the following value: - # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc - #### - - DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@} - - @end smallexample - - @node Generating the Command Line Switches - @section Generating the Command Line Switches - - @noindent - Once you have created the list of directories as explained in the - previous section (@pxref{Automatically Creating a List of Directories}), - you can easily generate the command line arguments to pass to gnatmake. - - For the sake of completeness, this example assumes that the source path - is not the same as the object path, and that you have two separate lists - of directories. - - @smallexample - # see "Automatically creating a list of directories" to create - # these variables - SOURCE_DIRS= - OBJECT_DIRS= - - GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@} - GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@} - - all: - gnatmake $@{GNATMAKE_SWITCHES@} main_unit - @end smallexample - - @node Overcoming Command Line Length Limits - @section Overcoming Command Line Length Limits - - @noindent - One problem that might be encountered on big projects is that many - operating systems limit the length of the command line. It is thus hard to give - gnatmake the list of source and object directories. - - This example shows how you can set up environment variables, which will - make @code{gnatmake} behave exactly as if the directories had been - specified on the command line, but have a much higher length limit (or - even none on most systems). - - It assumes that you have created a list of directories in your Makefile, - using one of the methods presented in - @ref{Automatically Creating a List of Directories}. - For the sake of completeness, we assume that the object - path (where the ALI files are found) is different from the sources patch. - - Note a small trick in the Makefile below: for efficiency reasons, we - create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are - expanded immediately by @code{make}. This way we overcome the standard - make behavior which is to expand the variables only when they are - actually used. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH. - # This is the same thing as putting the -I arguments on the command line. - # (the equivalent of using -aI on the command line would be to define - # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH). - # You can of course have different values for these variables. - # - # Note also that we need to keep the previous values of these variables, since - # they might have been set before running 'make' to specify where the GNAT - # library is installed. - - # see "Automatically creating a list of directories" to create these - # variables - SOURCE_DIRS= - OBJECT_DIRS= - - empty:= - space:=$@{empty@} $@{empty@} - SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@} - OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@} - ADA_INCLUDE_PATH += $@{SOURCE_LIST@} - ADA_OBJECT_PATH += $@{OBJECT_LIST@} - export ADA_INCLUDE_PATH - export ADA_OBJECT_PATH - - all: - gnatmake main_unit - @end smallexample - - @node Finding Memory Problems with gnatmem - @chapter Finding Memory Problems with @code{gnatmem} - @findex gnatmem - - @noindent - @code{gnatmem}, is a tool that monitors dynamic allocation and - deallocation activity in a program, and displays information about - incorrect deallocations and possible sources of memory leaks. Gnatmem - provides three type of information: - @itemize @bullet - @item - General information concerning memory management, such as the total - number of allocations and deallocations, the amount of allocated - memory and the high water mark, i.e. the largest amount of allocated - memory in the course of program execution. - - @item - Backtraces for all incorrect deallocations, that is to say deallocations - which do not correspond to a valid allocation. - - @item - Information on each allocation that is potentially the origin of a memory - leak. - @end itemize - - The @code{gnatmem} command has two modes. It can be used with @code{gdb} - or with instrumented allocation and deallocation routines. The later - mode is called the @code{GMEM} mode. Both modes produce the very same - output. - - @menu - * Running gnatmem (GDB Mode):: - * Running gnatmem (GMEM Mode):: - * Switches for gnatmem:: - * Examples of gnatmem Usage:: - * GDB and GMEM Modes:: - * Implementation Note:: - @end menu - - @node Running gnatmem (GDB Mode) - @section Running @code{gnatmem} (GDB Mode) - - @noindent - The @code{gnatmem} command has the form - - @smallexample - $ gnatmem [-q] [n] [-o file] user_program [program_arg]* - or - $ gnatmem [-q] [n] -i file - @end smallexample - - @noindent - Gnatmem must be supplied with the executable to examine, followed by its - run-time inputs. For example, if a program is executed with the command: - @smallexample - $ my_program arg1 arg2 - @end smallexample - then it can be run under @code{gnatmem} control using the command: - @smallexample - $ gnatmem my_program arg1 arg2 - @end smallexample - - The program is transparently executed under the control of the debugger - @ref{The GNAT Debugger GDB}. This does not affect the behavior - of the program, except for sensitive real-time programs. When the program - has completed execution, @code{gnatmem} outputs a report containing general - allocation/deallocation information and potential memory leak. - For better results, the user program should be compiled with - debugging options @ref{Switches for gcc}. - - Here is a simple example of use: - - *************** debut cc - @smallexample - $ gnatmem test_gm - - Global information - ------------------ - Total number of allocations : 45 - Total number of deallocations : 6 - Final Water Mark (non freed mem) : 11.29 Kilobytes - High Water Mark : 11.40 Kilobytes - - . - . - . - Allocation Root # 2 - ------------------- - Number of non freed allocations : 11 - Final Water Mark (non freed mem) : 1.16 Kilobytes - High Water Mark : 1.27 Kilobytes - Backtrace : - test_gm.adb:23 test_gm.alloc - . - . - . - @end smallexample - - The first block of output give general information. In this case, the - Ada construct "@b{new}" was executed 45 times, and only 6 calls to an - unchecked deallocation routine occurred. - - Subsequent paragraphs display information on all allocation roots. - An allocation root is a specific point in the execution of the program - that generates some dynamic allocation, such as a "@b{new}" construct. This - root is represented by an execution backtrace (or subprogram call - stack). By default the backtrace depth for allocations roots is 1, so - that a root corresponds exactly to a source location. The backtrace can - be made deeper, to make the root more specific. - - @node Running gnatmem (GMEM Mode) - @section Running @code{gnatmem} (GMEM Mode) - @cindex @code{GMEM} (@code{gnatmem}) - - @noindent - The @code{gnatmem} command has the form - - @smallexample - $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]* - @end smallexample - - The program must have been linked with the instrumented version of the - allocation and deallocation routines. This is done with linking with the - @file{libgmem.a} library. For better results, the user program should be - compiled with debugging options @ref{Switches for gcc}. For example to - build @file{my_program}: - - @smallexample - $ gnatmake -g my_program -largs -lgmem - @end smallexample - - @noindent - When running @file{my_program} the file @file{gmem.out} is produced. This file - contains information about all allocations and deallocations done by the - program. It is produced by the instrumented allocations and - deallocations routines and will be used by @code{gnatmem}. - - @noindent - Gnatmem must be supplied with the @file{gmem.out} file and the executable to - examine followed by its run-time inputs. For example, if a program is - executed with the command: - @smallexample - $ my_program arg1 arg2 - @end smallexample - then @file{gmem.out} can be analysed by @code{gnatmem} using the command: - @smallexample - $ gnatmem -i gmem.out my_program arg1 arg2 - @end smallexample - - @node Switches for gnatmem - @section Switches for @code{gnatmem} - - @noindent - @code{gnatmem} recognizes the following switches: - - @table @code - - @item @code{-q} - @cindex @code{-q} (@code{gnatmem}) - Quiet. Gives the minimum output needed to identify the origin of the - memory leaks. Omit statistical information. - - @item @code{n} - @cindex @code{n} (@code{gnatmem}) - N is an integer literal (usually between 1 and 10) which controls the - depth of the backtraces defining allocation root. The default value for - N is 1. The deeper the backtrace, the more precise the localization of - the root. Note that the total number of roots can depend on this - parameter. - - @item @code{-o file} - @cindex @code{-o} (@code{gnatmem}) - Direct the gdb output to the specified file. The @code{gdb} script used - to generate this output is also saved in the file @file{gnatmem.tmp}. - - @item @code{-i file} - @cindex @code{-i} (@code{gnatmem}) - Do the @code{gnatmem} processing starting from @file{file} which has - been generated by a previous call to @code{gnatmem} with the -o - switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful - for post mortem processing. - - @end table - - @node Examples of gnatmem Usage - @section Example of @code{gnatmem} Usage - - @noindent - This section is based on the @code{GDB} mode of @code{gnatmem}. The same - results can be achieved using @code{GMEM} mode. See section - @ref{Running gnatmem (GMEM Mode)}. - - @noindent - The first example shows the use of @code{gnatmem} - on a simple leaking program. - Suppose that we have the following Ada program: - - @smallexample - @group - @cartouche - @b{with} Unchecked_Deallocation; - @b{procedure} Test_Gm @b{is} - - @b{type} T @b{is array} (1..1000) @b{of} Integer; - @b{type} Ptr @b{is access} T; - @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr); - A : Ptr; - - @b{procedure} My_Alloc @b{is} - @b{begin} - A := @b{new} T; - @b{end} My_Alloc; - - @b{procedure} My_DeAlloc @b{is} - B : Ptr := A; - @b{begin} - Free (B); - @b{end} My_DeAlloc; - - @b{begin} - My_Alloc; - @b{for} I @b{in} 1 .. 5 @b{loop} - @b{for} J @b{in} I .. 5 @b{loop} - My_Alloc; - @b{end loop}; - My_Dealloc; - @b{end loop}; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - The program needs to be compiled with debugging option: - - @smallexample - $ gnatmake -g test_gm - @end smallexample - - @code{gnatmem} is invoked simply with - @smallexample - $ gnatmem test_gm - @end smallexample - - @noindent - which produces the following output: - - @smallexample - Global information - ------------------ - Total number of allocations : 18 - Total number of deallocations : 5 - Final Water Mark (non freed mem) : 53.00 Kilobytes - High Water Mark : 56.90 Kilobytes - - Allocation Root # 1 - ------------------- - Number of non freed allocations : 11 - Final Water Mark (non freed mem) : 42.97 Kilobytes - High Water Mark : 46.88 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - - Allocation Root # 2 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 10.02 Kilobytes - High Water Mark : 10.02 Kilobytes - Backtrace : - s-secsta.adb:81 system.secondary_stack.ss_init - - Allocation Root # 3 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 12 Bytes - High Water Mark : 12 Bytes - Backtrace : - s-secsta.adb:181 system.secondary_stack.ss_init - @end smallexample - - @noindent - Note that the GNAT run time contains itself a certain number of - allocations that have no corresponding deallocation, - as shown here for root #2 and root - #1. This is a normal behavior when the number of non freed allocations - is one, it locates dynamic data structures that the run time needs for - the complete lifetime of the program. Note also that there is only one - allocation root in the user program with a single line back trace: - test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the - program shows that 'My_Alloc' is called at 2 different points in the - source (line 21 and line 24). If those two allocation roots need to be - distinguished, the backtrace depth parameter can be used: - - @smallexample - $ gnatmem 3 test_gm - @end smallexample - - @noindent - which will give the following output: - - @smallexample - Global information - ------------------ - Total number of allocations : 18 - Total number of deallocations : 5 - Final Water Mark (non freed mem) : 53.00 Kilobytes - High Water Mark : 56.90 Kilobytes - - Allocation Root # 1 - ------------------- - Number of non freed allocations : 10 - Final Water Mark (non freed mem) : 39.06 Kilobytes - High Water Mark : 42.97 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - test_gm.adb:24 test_gm - b_test_gm.c:52 main - - Allocation Root # 2 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 10.02 Kilobytes - High Water Mark : 10.02 Kilobytes - Backtrace : - s-secsta.adb:81 system.secondary_stack.ss_init - s-secsta.adb:283 - b_test_gm.c:33 adainit - - Allocation Root # 3 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 3.91 Kilobytes - High Water Mark : 3.91 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - test_gm.adb:21 test_gm - b_test_gm.c:52 main - - Allocation Root # 4 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 12 Bytes - High Water Mark : 12 Bytes - Backtrace : - s-secsta.adb:181 system.secondary_stack.ss_init - s-secsta.adb:283 - b_test_gm.c:33 adainit - @end smallexample - - @noindent - The allocation root #1 of the first example has been split in 2 roots #1 - and #3 thanks to the more precise associated backtrace. - - @node GDB and GMEM Modes - @section GDB and GMEM Modes - - @noindent - The main advantage of the @code{GMEM} mode is that it is a lot faster than the - @code{GDB} mode where the application must be monitored by a @code{GDB} script. - But the @code{GMEM} mode is available only for DEC Unix, Linux x86, - Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86). - - @noindent - The main advantage of the @code{GDB} mode is that it is available on all - supported platforms. But it can be very slow if the application does a - lot of allocations and deallocations. - - @node Implementation Note - @section Implementation Note - - @menu - * gnatmem Using GDB Mode:: - * gnatmem Using GMEM Mode:: - @end menu - - @node gnatmem Using GDB Mode - @subsection @code{gnatmem} Using @code{GDB} Mode - - @noindent - @code{gnatmem} executes the user program under the control of @code{GDB} using - a script that sets breakpoints and gathers information on each dynamic - allocation and deallocation. The output of the script is then analyzed - by @code{gnatmem} - in order to locate memory leaks and their origin in the - program. Gnatmem works by recording each address returned by the - allocation procedure (@code{__gnat_malloc}) - along with the backtrace at the - allocation point. On each deallocation, the deallocated address is - matched with the corresponding allocation. At the end of the processing, - the unmatched allocations are considered potential leaks. All the - allocations associated with the same backtrace are grouped together and - form an allocation root. The allocation roots are then sorted so that - those with the biggest number of unmatched allocation are printed - first. A delicate aspect of this technique is to distinguish between the - data produced by the user program and the data produced by the gdb - script. Currently, on systems that allow probing the terminal, the gdb - command "tty" is used to force the program output to be redirected to the - current terminal while the @code{gdb} output is directed to a file or to a - pipe in order to be processed subsequently by @code{gnatmem}. - - @node gnatmem Using GMEM Mode - @subsection @code{gnatmem} Using @code{GMEM} Mode - - @noindent - This mode use the same algorithm to detect memory leak as the @code{GDB} - mode of @code{gnatmem}, the only difference is in the way data are - gathered. In @code{GMEM} mode the program is linked with instrumented - version of @code{__gnat_malloc} and @code{__gnat_free} - routines. Information needed to find memory leak are recorded by these - routines in file @file{gmem.out}. This mode also require that the stack - traceback be available, this is only implemented on some platforms - @ref{GDB and GMEM Modes}. - - - @node Finding Memory Problems with GNAT Debug Pool - @chapter Finding Memory Problems with GNAT Debug Pool - @findex Debug Pool - @cindex storage, pool, memory corruption - - @noindent - The use of unchecked deallocation and unchecked conversion can easily - lead to incorrect memory references. The problems generated by such - references are usually difficult to tackle because the symptoms can be - very remote from the origin of the problem. In such cases, it is - very helpful to detect the problem as early as possible. This is the - purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. - - @noindent - In order to use the GNAT specific debugging pool, the user must - associate a debug pool object with each of the access types that may be - related to suspected memory problems. See Ada Reference Manual - 13.11. - @smallexample - @b{type} Ptr @b{is} @b{access} Some_Type; - Pool : GNAT.Debug_Pools.Debug_Pool; - @b{for} Ptr'Storage_Pool @b{use} Pool; - @end smallexample - - @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of - pool: the Checked_Pool. Such pools, like standard Ada storage pools, - allow the user to redefine allocation and deallocation strategies. They - also provide a checkpoint for each dereference, through the use of - the primitive operation @code{Dereference} which is implicitly called at - each dereference of an access value. - - Once an access type has been associated with a debug pool, operations on - values of the type may raise four distinct exceptions, - which correspond to four potential kinds of memory corruption: - @itemize @bullet - @item - @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } - @end itemize - - @noindent - For types associated with a Debug_Pool, dynamic allocation is performed using - the standard - GNAT allocation routine. References to all allocated chunks of memory - are kept in an internal dictionary. The deallocation strategy consists - in not releasing the memory to the underlying system but rather to fill - it with a memory pattern easily recognizable during debugging sessions: - The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#. - Upon each dereference, a check is made that the access value denotes a properly - allocated memory location. Here is a complete example of use of - @code{Debug_Pools}, that includes typical instances of memory corruption: - @smallexample - @iftex - @leftskip=0cm - @end iftex - @b{with} Gnat.Io; @b{use} Gnat.Io; - @b{with} Unchecked_Deallocation; - @b{with} Unchecked_Conversion; - @b{with} GNAT.Debug_Pools; - @b{with} System.Storage_Elements; - @b{with} Ada.Exceptions; @b{use} Ada.Exceptions; - @b{procedure} Debug_Pool_Test @b{is} - - @b{type} T @b{is} @b{access} Integer; - @b{type} U @b{is} @b{access} @b{all} T; - - P : GNAT.Debug_Pools.Debug_Pool; - @b{for} T'Storage_Pool @b{use} P; - - @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T); - @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T); - A, B : @b{aliased} T; - - @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line); - - @b{begin} - Info (P); - A := @b{new} Integer; - B := @b{new} Integer; - B := A; - Info (P); - Free (A); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - B := UC(A'Access); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - Info (P); - @b{end} Debug_Pool_Test; - @end smallexample - @noindent - The debug pool mechanism provides the following precise diagnostics on the - execution of this erroneous program: - @smallexample - Debug Pool info: - Total allocated bytes : 0 - Total deallocated bytes : 0 - Current Water Mark: 0 - High Water Mark: 0 - - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 0 - Current Water Mark: 8 - High Water Mark: 8 - - raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 4 - Current Water Mark: 4 - High Water Mark: 8 - - @end smallexample - - @node Creating Sample Bodies Using gnatstub - @chapter Creating Sample Bodies Using @code{gnatstub} - @findex gnatstub - - @noindent - @code{gnatstub} creates body stubs, that is, empty but compilable bodies - for library unit declarations. - - To create a body stub, @code{gnatstub} has to compile the library - unit declaration. Therefore, bodies can be created only for legal - library units. Moreover, if a library unit depends semantically upon - units located outside the current directory, you have to provide - the source search path when calling @code{gnatstub}, see the description - of @code{gnatstub} switches below. - - @menu - * Running gnatstub:: - * Switches for gnatstub:: - @end menu - - @node Running gnatstub - @section Running @code{gnatstub} - - @noindent - @code{gnatstub} has the command-line interface of the form - - @smallexample - $ gnatstub [switches] filename [directory] - @end smallexample - - @noindent - where - @table @code - @item filename - is the name of the source file that contains a library unit declaration - for which a body must be created. This name should follow the GNAT file name - conventions. No crunching is allowed for this file name. The file - name may contain the path information. - - @item directory - indicates the directory to place a body stub (default is the - current directory) - - @item switches - is an optional sequence of switches as described in the next section - @end table - - @node Switches for gnatstub - @section Switches for @code{gnatstub} - - @table @code - - @item -f - If the destination directory already contains a file with a name of the body file - for the argument spec file, replace it with the generated body stub. - - @item -hs - Put the comment header (i.e. all the comments preceding the - compilation unit) from the source of the library unit declaration - into the body stub. - - @item -hg - Put a sample comment header into the body stub. - - @item -IDIR - @itemx -I- - These switches have the same meaning as in calls to gcc. - They define the source search path in the call to gcc issued - by @code{gnatstub} to compile an argument source file. - - @item -i@var{n} - (@var{n} is a decimal natural number). Set the indentation level in the - generated body sample to n, '-i0' means "no indentation", - the default indentation is 3. - - @item -k - Do not remove the tree file (i.e. the snapshot of the compiler internal - structures used by @code{gnatstub}) after creating the body stub. - - @item -l@var{n} - (@var{n} is a decimal positive number) Set the maximum line length in the - body stub to n, the default is 78. - - @item -q - Quiet mode: do not generate a confirmation when a body is - successfully created or a message when a body is not required for an - argument unit. - - @item -r - Reuse the tree file (if it exists) instead of creating it: instead of - creating the tree file for the library unit declaration, gnatstub - tries to find it in the current directory and use it for creating - a body. If the tree file is not found, no body is created. @code{-r} - also implies @code{-k}, whether or not - @code{-k} is set explicitly. - - @item -t - Overwrite the existing tree file: if the current directory already - contains the file which, according to the GNAT file name rules should - be considered as a tree file for the argument source file, gnatstub - will refuse to create the tree file needed to create a body sampler, - unless @code{-t} option is set - - @item -v - Verbose mode: generate version information. - - @end table - - @node Reducing the Size of Ada Executables with gnatelim - @chapter Reducing the Size of Ada Executables with @code{gnatelim} - @findex gnatelim - - @menu - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - @end menu - - @node About gnatelim - @section About @code{gnatelim} - - @noindent - When a program shares a set of Ada - packages with other programs, it may happen that this program uses - only a fraction of the subprograms defined in these packages. The code - created for these unused subprograms increases the size of the executable. - - @code{gnatelim} tracks unused subprograms in an Ada program and - outputs a list of GNAT-specific @code{Eliminate} pragmas (see next - section) marking all the subprograms that are declared but never called. - By placing the list of @code{Eliminate} pragmas in the GNAT configuration - file @file{gnat.adc} and recompiling your program, you may decrease the - size of its executable, because the compiler will not generate the code - for 'eliminated' subprograms. - - @code{gnatelim} needs as its input data a set of tree files - (see @ref{Tree Files}) representing all the components of a program to - process and a bind file for a main subprogram (see - @ref{Preparing Tree and Bind Files for gnatelim}). - - @node Eliminate Pragma - @section @code{Eliminate} Pragma - @findex Eliminate - - @noindent - The simplified syntax of the Eliminate pragma used by @code{gnatelim} is: - - @smallexample - @cartouche - @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name); - @end cartouche - @end smallexample - - @noindent - where - @table @code - @item Library_Unit_Name - full expanded Ada name of a library unit - - @item Subprogram_Name - a simple or expanded name of a subprogram declared within this - compilation unit - - @end table - - @noindent - The effect of an @code{Eliminate} pragma placed in the GNAT configuration - file @file{gnat.adc} is: - - @itemize @bullet - - @item - If the subprogram @code{Subprogram_Name} is declared within - the library unit @code{Library_Unit_Name}, the compiler will not generate - code for this subprogram. This applies to all overloaded subprograms denoted - by @code{Subprogram_Name}. - - @item - If a subprogram marked by the pragma @code{Eliminate} is used (called) - in a program, the compiler will produce an error message in the place where - it is called. - @end itemize - - @node Tree Files - @section Tree Files - @cindex Tree file - - @noindent - A tree file stores a snapshot of the compiler internal data - structures at the very end of a successful compilation. It contains all the - syntactic and semantic information for the compiled unit and all the - units upon which it depends semantically. - To use tools that make use of tree files, you - need to first produce the right set of tree files. - - GNAT produces correct tree files when -gnatt -gnatc options are set - in a gcc call. The tree files have an .adt extension. - Therefore, to produce a tree file for the compilation unit contained in a file - named @file{foo.adb}, you must use the command - - @smallexample - $ gcc -c -gnatc -gnatt foo.adb - @end smallexample - - @noindent - and you will get the tree file @file{foo.adt}. - compilation. - - @node Preparing Tree and Bind Files for gnatelim - @section Preparing Tree and Bind Files for @code{gnatelim} - - @noindent - A set of tree files covering the program to be analyzed with - @code{gnatelim} and - the bind file for the main subprogram does not have to - be in the current directory. - '-T' gnatelim option may be used to provide - the search path for tree files, and '-b' - option may be used to point to the bind - file to process (see @ref{Running gnatelim}) - - If you do not have the appropriate set of tree - files and the right bind file, you - may create them in the current directory using the following procedure. - - Let @code{Main_Prog} be the name of a main subprogram, and suppose - this subprogram is in a file named @file{main_prog.adb}. - - To create a bind file for @code{gnatelim}, run @code{gnatbind} for - the main subprogram. @code{gnatelim} can work with both Ada and C - bind files; when both are present, it uses the Ada bind file. - The following commands will build the program and create the bind file: - - @smallexample - $ gnatmake -c Main_Prog - $ gnatbind main_prog - @end smallexample - - @noindent - To create a minimal set of tree files covering the whole program, call - @code{gnatmake} for this program as follows: - - @smallexample - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end smallexample - - @noindent - The @code{-c} gnatmake option turns off the bind and link - steps, that are useless anyway because the sources are compiled with - @option{-gnatc} option which turns off code generation. - - The @code{-f} gnatmake option forces - recompilation of all the needed sources. - - This sequence of actions will create all the data needed by @code{gnatelim} - from scratch and therefore guarantee its consistency. If you would like to - use some existing set of files as @code{gnatelim} output, you must make - sure that the set of files is complete and consistent. You can use the - @code{-m} switch to check if there are missed tree files - - Note, that @code{gnatelim} needs neither object nor ALI files. - - @node Running gnatelim - @section Running @code{gnatelim} - - @noindent - @code{gnatelim} has the following command-line interface: - - @smallexample - $ gnatelim [options] name - @end smallexample - - @noindent - @code{name} should be a full expanded Ada name of a main subprogram - of a program (partition). - - @code{gnatelim} options: - - @table @code - @item -q - Quiet mode: by default @code{gnatelim} generates to the standard error - stream a trace of the source file names of the compilation units being - processed. This option turns this trace off. - - @item -v - Verbose mode: @code{gnatelim} version information is printed as Ada - comments to the standard output stream. - - @item -a - Also look for subprograms from the GNAT run time that can be eliminated. - - @item -m - Check if any tree files are missing for an accurate result. - - @item -T@var{dir} - When looking for tree files also look in directory @var{dir} - - @item -b@var{bind_file} - Specifies @var{bind_file} as the bind file to process. If not set, the name - of the bind file is computed from the full expanded Ada name of a main subprogram. - - @item -d@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - mode desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Gnatelim.Options} unit in the compiler - source file @file{gnatelim-options.adb}. - @end table - - @noindent - @code{gnatelim} sends its output to the standard output stream, and all the - tracing and debug information is sent to the standard error stream. - In order to produce a proper GNAT configuration file - @file{gnat.adc}, redirection must be used: - - @smallexample - $ gnatelim Main_Prog > gnat.adc - @end smallexample - - @noindent - or - - @smallexample - $ gnatelim Main_Prog >> gnat.adc - @end smallexample - - @noindent - In order to append the @code{gnatelim} output to the existing contents of - @file{gnat.adc}. - - @node Correcting the List of Eliminate Pragmas - @section Correcting the List of Eliminate Pragmas - - @noindent - In some rare cases it may happen that @code{gnatelim} will try to eliminate - subprograms which are actually called in the program. In this case, the - compiler will generate an error message of the form: - - @smallexample - file.adb:106:07: cannot call eliminated subprogram "My_Prog" - @end smallexample - - @noindent - You will need to manually remove the wrong @code{Eliminate} pragmas from - the @file{gnat.adc} file. It is advised that you recompile your program - from scratch after that because you need a consistent @file{gnat.adc} file - during the entire compilation. - - @node Making Your Executables Smaller - @section Making Your Executables Smaller - - @noindent - In order to get a smaller executable for your program you now have to - recompile the program completely with the new @file{gnat.adc} file - created by @code{gnatelim} in your current directory: - - @smallexample - $ gnatmake -f Main_Prog - @end smallexample - - @noindent - (you will need @code{-f} option for gnatmake to - recompile everything - with the set of pragmas @code{Eliminate} you have obtained with - @code{gnatelim}). - - Be aware that the set of @code{Eliminate} pragmas is specific to each - program. It is not recommended to merge sets of @code{Eliminate} - pragmas created for different programs in one @file{gnat.adc} file. - - @node Summary of the gnatelim Usage Cycle - @section Summary of the gnatelim Usage Cycle - - @noindent - Here is a quick summary of the steps to be taken in order to reduce - the size of your executables with @code{gnatelim}. You may use - other GNAT options to control the optimization level, - to produce the debugging information, to set search path, etc. - - @enumerate - @item - Produce a bind file and a set of tree files - - @smallexample - $ gnatmake -c Main_Prog - $ gnatbind main_prog - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end smallexample - - @item - Generate a list of @code{Eliminate} pragmas - @smallexample - $ gnatelim Main_Prog >[>] gnat.adc - @end smallexample - - @item - Recompile the application - - @smallexample - $ gnatmake -f Main_Prog - @end smallexample - - @end enumerate - - @node Other Utility Programs - @chapter Other Utility Programs - - @noindent - This chapter discusses some other utility programs available in the Ada - environment. - - @menu - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - * Installing gnathtml:: - @end menu - - @node Using Other Utility Programs with GNAT - @section Using Other Utility Programs with GNAT - - @noindent - The object files generated by GNAT are in standard system format and in - particular the debugging information uses this format. This means - programs generated by GNAT can be used with existing utilities that - depend on these formats. - - In general, any utility program that works with C will also often work with - Ada programs generated by GNAT. This includes software utilities such as - gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such - as Purify. - - @node The gnatpsta Utility Program - @section The @code{gnatpsta} Utility Program - - @noindent - Many of the definitions in package Standard are implementation-dependent. - However, the source of this package does not exist as an Ada source - file, so these values cannot be determined by inspecting the source. - They can be determined by examining in detail the coding of - @file{cstand.adb} which creates the image of Standard in the compiler, - but this is awkward and requires a great deal of internal knowledge - about the system. - - The @code{gnatpsta} utility is designed to deal with this situation. - It is an Ada program that dynamically determines the - values of all the relevant parameters in Standard, and prints them - out in the form of an Ada source listing for Standard, displaying all - the values of interest. This output is generated to - @file{stdout}. - - To determine the value of any parameter in package Standard, simply - run @code{gnatpsta} with no qualifiers or arguments, and examine - the output. This is preferable to consulting documentation, because - you know that the values you are getting are the actual ones provided - by the executing system. - - @node The External Symbol Naming Scheme of GNAT - @section The External Symbol Naming Scheme of GNAT - - @noindent - In order to interpret the output from GNAT, when using tools that are - originally intended for use with other languages, it is useful to - understand the conventions used to generate link names from the Ada - entity names. - - All link names are in all lowercase letters. With the exception of library - procedure names, the mechanism used is simply to use the full expanded - Ada name with dots replaced by double underscores. For example, suppose - we have the following package spec: - - @smallexample - @group - @cartouche - @b{package} QRS @b{is} - MN : Integer; - @b{end} QRS; - @end cartouche - @end group - @end smallexample - - @noindent - The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so - the corresponding link name is @code{qrs__mn}. - @findex Export - Of course if a @code{pragma Export} is used this may be overridden: - - @smallexample - @group - @cartouche - @b{package} Exports @b{is} - Var1 : Integer; - @b{pragma} Export (Var1, C, External_Name => "var1_name"); - Var2 : Integer; - @b{pragma} Export (Var2, C, Link_Name => "var2_link_name"); - @b{end} Exports; - @end cartouche - @end group - @end smallexample - - @noindent - In this case, the link name for @var{Var1} is whatever link name the - C compiler would assign for the C function @var{var1_name}. This typically - would be either @var{var1_name} or @var{_var1_name}, depending on operating - system conventions, but other possibilities exist. The link name for - @var{Var2} is @var{var2_link_name}, and this is not operating system - dependent. - - @findex _main - One exception occurs for library level procedures. A potential ambiguity - arises between the required name @code{_main} for the C main program, - and the name we would otherwise assign to an Ada library level procedure - called @code{Main} (which might well not be the main program). - - To avoid this ambiguity, we attach the prefix @code{_ada_} to such - names. So if we have a library level procedure such as - - @smallexample - @group - @cartouche - @b{procedure} Hello (S : String); - @end cartouche - @end group - @end smallexample - - @noindent - the external name of this procedure will be @var{_ada_hello}. - - @node Ada Mode for Glide - @section Ada Mode for @code{Glide} - - @noindent - The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the - user in understanding existing code and facilitates writing new code. It - furthermore provides some utility functions for easier integration of - standard Emacs features when programming in Ada. - - @subsection General Features: - - @itemize @bullet - @item - Full Integrated Development Environment : - - @itemize @bullet - @item - support of 'project files' for the configuration (directories, - compilation options,...) - - @item - compiling and stepping through error messages. - - @item - running and debugging your applications within Glide. - @end itemize - - @item - easy to use for beginners by pull-down menus, - - @item - user configurable by many user-option variables. - @end itemize - - @subsection Ada Mode Features That Help Understanding Code: - - @itemize @bullet - @item - functions for easy and quick stepping through Ada code, - - @item - getting cross reference information for identifiers (e.g. find the - defining place by a keystroke), - - @item - displaying an index menu of types and subprograms and move point to - the chosen one, - - @item - automatic color highlighting of the various entities in Ada code. - @end itemize - - @subsection Glide Support for Writing Ada Code: - - @itemize @bullet - @item - switching between spec and body files with possible - autogeneration of body files, - - @item - automatic formating of subprograms parameter lists. - - @item - automatic smart indentation according to Ada syntax, - - @item - automatic completion of identifiers, - - @item - automatic casing of identifiers, keywords, and attributes, - - @item - insertion of statement templates, - - @item - filling comment paragraphs like filling normal text, - @end itemize - - For more information, please refer to the online Glide documentation - available in the Glide --> Help Menu. - - @node Converting Ada Files to html with gnathtml - @section Converting Ada Files to html with @code{gnathtml} - - @noindent - This @code{Perl} script allows Ada source files to be browsed using - standard Web browsers. For installation procedure, see the section - @xref{Installing gnathtml}. - - Ada reserved keywords are highlighted in a bold font and Ada comments in - a blue font. Unless your program was compiled with the gcc @option{-gnatx} - switch to suppress the generation of cross-referencing information, user - defined variables and types will appear in a different color; you will - be able to click on any identifier and go to its declaration. - - The command line is as follow: - @smallexample - $ perl gnathtml.pl [switches] ada-files - @end smallexample - - You can pass it as many Ada files as you want. @code{gnathtml} will generate - an html file for every ada file, and a global file called @file{index.htm}. - This file is an index of every identifier defined in the files. - - The available switches are the following ones : - - @table @code - @item -83 - @cindex @code{-83} (@code{gnathtml}) - Only the subset on the Ada 83 keywords will be highlighted, not the full - Ada 95 keywords set. - - @item -cc @var{color} - This option allows you to change the color used for comments. The default - value is green. The color argument can be any name accepted by html. - - @item -d - @cindex @code{-d} (@code{gnathtml}) - If the ada files depend on some other files (using for instance the - @code{with} command, the latter will also be converted to html. - Only the files in the user project will be converted to html, not the files - in the run-time library itself. - - @item -D - This command is the same as -d above, but @code{gnathtml} will also look - for files in the run-time library, and generate html files for them. - - @item -f - @cindex @code{-f} (@code{gnathtml}) - By default, gnathtml will generate html links only for global entities - ('with'ed units, global variables and types,...). If you specify the - @code{-f} on the command line, then links will be generated for local - entities too. - - @item -l @var{number} - @cindex @code{-l} (@code{gnathtml}) - If this switch is provided and @var{number} is not 0, then @code{gnathtml} - will number the html files every @var{number} line. - - @item -I @var{dir} - @cindex @code{-I} (@code{gnathtml}) - Specify a directory to search for library files (@file{.ali} files) and - source files. You can provide several -I switches on the command line, - and the directories will be parsed in the order of the command line. - - @item -o @var{dir} - @cindex @code{-o} (@code{gnathtml}) - Specify the output directory for html files. By default, gnathtml will - saved the generated html files in a subdirectory named @file{html/}. - - @item -p @var{file} - @cindex @code{-p} (@code{gnathtml}) - If you are using Emacs and the most recent Emacs Ada mode, which provides - a full Integrated Development Environment for compiling, checking, - running and debugging applications, you may be using @file{.adp} files - to give the directories where Emacs can find sources and object files. - - Using this switch, you can tell gnathtml to use these files. This allows - you to get an html version of your application, even if it is spread - over multiple directories. - - @item -sc @var{color} - @cindex @code{-sc} (@code{gnathtml}) - This option allows you to change the color used for symbol definitions. - The default value is red. The color argument can be any name accepted by html. - - @item -t @var{file} - @cindex @code{-t} (@code{gnathtml}) - This switch provides the name of a file. This file contains a list of - file names to be converted, and the effect is exactly as though they had - appeared explicitly on the command line. This - is the recommended way to work around the command line length limit on some - systems. - - @end table - - @node Installing gnathtml - @section Installing @code{gnathtml} - - @noindent - @code{Perl} needs to be installed on your machine to run this script. - @code{Perl} is freely available for almost every architecture and - Operating System via the Internet. - - On Unix systems, you may want to modify the first line of the script - @code{gnathtml}, to explicitly tell the Operating system where Perl - is. The syntax of this line is : - @smallexample - #!full_path_name_to_perl - @end smallexample - - @noindent - Alternatively, you may run the script using the following command line: - - @smallexample - $ perl gnathtml.pl [switches] files - @end smallexample - - - @node Running and Debugging Ada Programs - @chapter Running and Debugging Ada Programs - @cindex Debugging - - @noindent - This chapter discusses how to debug Ada programs. An incorrect Ada program - may be handled in three ways by the GNAT compiler: - - @enumerate - @item - The illegality may be a violation of the static semantics of Ada. In - that case GNAT diagnoses the constructs in the program that are illegal. - It is then a straightforward matter for the user to modify those parts of - the program. - - @item - The illegality may be a violation of the dynamic semantics of Ada. In - that case the program compiles and executes, but may generate incorrect - results, or may terminate abnormally with some exception. - - @item - When presented with a program that contains convoluted errors, GNAT - itself may terminate abnormally without providing full diagnostics on - the incorrect user program. - @end enumerate - - @menu - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - @end menu - - @cindex Debugger - @findex gdb - - @node The GNAT Debugger GDB - @section The GNAT Debugger GDB - - @noindent - @code{GDB} is a general purpose, platform-independent debugger that - can be used to debug mixed-language programs compiled with @code{GCC}, - and in particular is capable of debugging Ada programs compiled with - GNAT. The latest versions of @code{GDB} are Ada-aware and can handle - complex Ada data structures. - - The manual @cite{Debugging with GDB} - contains full details on the usage of @code{GDB}, including a section on - its usage on programs. This manual should be consulted for full - details. The section that follows is a brief introduction to the - philosophy and use of @code{GDB}. - - When GNAT programs are compiled, the compiler optionally writes debugging - information into the generated object file, including information on - line numbers, and on declared types and variables. This information is - separate from the generated code. It makes the object files considerably - larger, but it does not add to the size of the actual executable that - will be loaded into memory, and has no impact on run-time performance. The - generation of debug information is triggered by the use of the - -g switch in the gcc or gnatmake command used to carry out - the compilations. It is important to emphasize that the use of these - options does not change the generated code. - - The debugging information is written in standard system formats that - are used by many tools, including debuggers and profilers. The format - of the information is typically designed to describe C types and - semantics, but GNAT implements a translation scheme which allows full - details about Ada types and variables to be encoded into these - standard C formats. Details of this encoding scheme may be found in - the file exp_dbug.ads in the GNAT source distribution. However, the - details of this encoding are, in general, of no interest to a user, - since @code{GDB} automatically performs the necessary decoding. - - When a program is bound and linked, the debugging information is - collected from the object files, and stored in the executable image of - the program. Again, this process significantly increases the size of - the generated executable file, but it does not increase the size of - the executable program itself. Furthermore, if this program is run in - the normal manner, it runs exactly as if the debug information were - not present, and takes no more actual memory. - - However, if the program is run under control of @code{GDB}, the - debugger is activated. The image of the program is loaded, at which - point it is ready to run. If a run command is given, then the program - will run exactly as it would have if @code{GDB} were not present. This - is a crucial part of the @code{GDB} design philosophy. @code{GDB} is - entirely non-intrusive until a breakpoint is encountered. If no - breakpoint is ever hit, the program will run exactly as it would if no - debugger were present. When a breakpoint is hit, @code{GDB} accesses - the debugging information and can respond to user commands to inspect - variables, and more generally to report on the state of execution. - - @node Running GDB - @section Running GDB - - @noindent - The debugger can be launched directly and simply from @code{glide} or - through its graphical interface: @code{gvd}. It can also be used - directly in text mode. Here is described the basic use of @code{GDB} - in text mode. All the commands described below can be used in the - @code{gvd} console window eventhough there is usually other more - graphical ways to achieve the same goals. - - @noindent - The command to run de graphical interface of the debugger is - @smallexample - $ gvd program - @end smallexample - - @noindent - The command to run @code{GDB} in text mode is - - @smallexample - $ gdb program - @end smallexample - - @noindent - where @code{program} is the name of the executable file. This - activates the debugger and results in a prompt for debugger commands. - The simplest command is simply @code{run}, which causes the program to run - exactly as if the debugger were not present. The following section - describes some of the additional commands that can be given to @code{GDB}. - - - @node Introduction to GDB Commands - @section Introduction to GDB Commands - - @noindent - @code{GDB} contains a large repertoire of commands. The manual - @cite{Debugging with GDB} - includes extensive documentation on the use - of these commands, together with examples of their use. Furthermore, - the command @var{help} invoked from within @code{GDB} activates a simple help - facility which summarizes the available commands and their options. - In this section we summarize a few of the most commonly - used commands to give an idea of what @code{GDB} is about. You should create - a simple program with debugging information and experiment with the use of - these @code{GDB} commands on the program as you read through the - following section. - - @table @code - @item set args @var{arguments} - The @var{arguments} list above is a list of arguments to be passed to - the program on a subsequent run command, just as though the arguments - had been entered on a normal invocation of the program. The @code{set args} - command is not needed if the program does not require arguments. - - @item run - The @code{run} command causes execution of the program to start from - the beginning. If the program is already running, that is to say if - you are currently positioned at a breakpoint, then a prompt will ask - for confirmation that you want to abandon the current execution and - restart. - - @item breakpoint @var{location} - The breakpoint command sets a breakpoint, that is to say a point at which - execution will halt and @code{GDB} will await further - commands. @var{location} is - either a line number within a file, given in the format @code{file:linenumber}, - or it is the name of a subprogram. If you request that a breakpoint be set on - a subprogram that is overloaded, a prompt will ask you to specify on which of - those subprograms you want to breakpoint. You can also - specify that all of them should be breakpointed. If the program is run - and execution encounters the breakpoint, then the program - stops and @code{GDB} signals that the breakpoint was encountered by - printing the line of code before which the program is halted. - - @item breakpoint exception @var{name} - A special form of the breakpoint command which breakpoints whenever - exception @var{name} is raised. - If @var{name} is omitted, - then a breakpoint will occur when any exception is raised. - - @item print @var{expression} - This will print the value of the given expression. Most simple - Ada expression formats are properly handled by @code{GDB}, so the expression - can contain function calls, variables, operators, and attribute references. - - @item continue - Continues execution following a breakpoint, until the next breakpoint or the - termination of the program. - - @item step - Executes a single line after a breakpoint. If the next statement is a subprogram - call, execution continues into (the first statement of) the - called subprogram. - - @item next - Executes a single line. If this line is a subprogram call, executes and - returns from the call. - - @item list - Lists a few lines around the current source location. In practice, it - is usually more convenient to have a separate edit window open with the - relevant source file displayed. Successive applications of this command - print subsequent lines. The command can be given an argument which is a - line number, in which case it displays a few lines around the specified one. - - @item backtrace - Displays a backtrace of the call chain. This command is typically - used after a breakpoint has occurred, to examine the sequence of calls that - leads to the current breakpoint. The display includes one line for each - activation record (frame) corresponding to an active subprogram. - - @item up - At a breakpoint, @code{GDB} can display the values of variables local - to the current frame. The command @code{up} can be used to - examine the contents of other active frames, by moving the focus up - the stack, that is to say from callee to caller, one frame at a time. - - @item down - Moves the focus of @code{GDB} down from the frame currently being - examined to the frame of its callee (the reverse of the previous command), - - @item frame @var{n} - Inspect the frame with the given number. The value 0 denotes the frame - of the current breakpoint, that is to say the top of the call stack. - - @end table - - The above list is a very short introduction to the commands that - @code{GDB} provides. Important additional capabilities, including conditional - breakpoints, the ability to execute command sequences on a breakpoint, - the ability to debug at the machine instruction level and many other - features are described in detail in @cite{Debugging with GDB}. - Note that most commands can be abbreviated - (for example, c for continue, bt for backtrace). - - @node Using Ada Expressions - @section Using Ada Expressions - @cindex Ada expressions - - @noindent - @code{GDB} supports a fairly large subset of Ada expression syntax, with some - extensions. The philosophy behind the design of this subset is - - @itemize @bullet - @item - That @code{GDB} should provide basic literals and access to operations for - arithmetic, dereferencing, field selection, indexing, and subprogram calls, - leaving more sophisticated computations to subprograms written into the - program (which therefore may be called from @code{GDB}). - - @item - That type safety and strict adherence to Ada language restrictions - are not particularly important to the @code{GDB} user. - - @item - That brevity is important to the @code{GDB} user. - @end itemize - - Thus, for brevity, the debugger acts as if there were - implicit @code{with} and @code{use} clauses in effect for all user-written - packages, thus making it unnecessary to fully qualify most names with - their packages, regardless of context. Where this causes ambiguity, - @code{GDB} asks the user's intent. - - For details on the supported Ada syntax, see @cite{Debugging with GDB}. - - @node Calling User-Defined Subprograms - @section Calling User-Defined Subprograms - - @noindent - An important capability of @code{GDB} is the ability to call user-defined - subprograms while debugging. This is achieved simply by entering - a subprogram call statement in the form: - - @smallexample - call subprogram-name (parameters) - @end smallexample - - @noindent - The keyword @code{call} can be omitted in the normal case where the - @code{subprogram-name} does not coincide with any of the predefined - @code{GDB} commands. - - The effect is to invoke the given subprogram, passing it the - list of parameters that is supplied. The parameters can be expressions and - can include variables from the program being debugged. The - subprogram must be defined - at the library level within your program, and @code{GDB} will call the - subprogram within the environment of your program execution (which - means that the subprogram is free to access or even modify variables - within your program). - - The most important use of this facility is in allowing the inclusion of - debugging routines that are tailored to particular data structures - in your program. Such debugging routines can be written to provide a suitably - high-level description of an abstract type, rather than a low-level dump - of its physical layout. After all, the standard - @code{GDB print} command only knows the physical layout of your - types, not their abstract meaning. Debugging routines can provide information - at the desired semantic level and are thus enormously useful. - - For example, when debugging GNAT itself, it is crucial to have access to - the contents of the tree nodes used to represent the program internally. - But tree nodes are represented simply by an integer value (which in turn - is an index into a table of nodes). - Using the @code{print} command on a tree node would simply print this integer - value, which is not very useful. But the PN routine (defined in file - treepr.adb in the GNAT sources) takes a tree node as input, and displays - a useful high level representation of the tree node, which includes the - syntactic category of the node, its position in the source, the integers - that denote descendant nodes and parent node, as well as varied - semantic information. To study this example in more detail, you might want to - look at the body of the PN procedure in the stated file. - - @node Using the Next Command in a Function - @section Using the Next Command in a Function - - @noindent - When you use the @code{next} command in a function, the current source - location will advance to the next statement as usual. A special case - arises in the case of a @code{return} statement. - - Part of the code for a return statement is the "epilog" of the function. - This is the code that returns to the caller. There is only one copy of - this epilog code, and it is typically associated with the last return - statement in the function if there is more than one return. In some - implementations, this epilog is associated with the first statement - of the function. - - The result is that if you use the @code{next} command from a return - statement that is not the last return statement of the function you - may see a strange apparent jump to the last return statement or to - the start of the function. You should simply ignore this odd jump. - The value returned is always that from the first return statement - that was stepped through. - - @node Ada Exceptions - @section Breaking on Ada Exceptions - @cindex Exceptions - - @noindent - You can set breakpoints that trip when your program raises - selected exceptions. - - @table @code - @item break exception - Set a breakpoint that trips whenever (any task in the) program raises - any exception. - - @item break exception @var{name} - Set a breakpoint that trips whenever (any task in the) program raises - the exception @var{name}. - - @item break exception unhandled - Set a breakpoint that trips whenever (any task in the) program raises an - exception for which there is no handler. - - @item info exceptions - @itemx info exceptions @var{regexp} - The @code{info exceptions} command permits the user to examine all defined - exceptions within Ada programs. With a regular expression, @var{regexp}, as - argument, prints out only those exceptions whose name matches @var{regexp}. - @end table - - @node Ada Tasks - @section Ada Tasks - @cindex Tasks - - @noindent - @code{GDB} allows the following task-related commands: - - @table @code - @item info tasks - This command shows a list of current Ada tasks, as in the following example: - - @smallexample - @iftex - @leftskip=0cm - @end iftex - (gdb) info tasks - ID TID P-ID Thread Pri State Name - 1 8088000 0 807e000 15 Child Activation Wait main_task - 2 80a4000 1 80ae000 15 Accept/Select Wait b - 3 809a800 1 80a4800 15 Child Activation Wait a - * 4 80ae800 3 80b8000 15 Running c - @end smallexample - - @noindent - In this listing, the asterisk before the first task indicates it to be the - currently running task. The first column lists the task ID that is used - to refer to tasks in the following commands. - - @item break @var{linespec} task @var{taskid} - @itemx break @var{linespec} task @var{taskid} if @dots{} - @cindex Breakpoints and tasks - These commands are like the @code{break @dots{} thread @dots{}}. - @var{linespec} specifies source lines. - - Use the qualifier @samp{task @var{taskid}} with a breakpoint command - to specify that you only want @code{GDB} to stop the program when a - particular Ada task reaches this breakpoint. @var{taskid} is one of the - numeric task identifiers assigned by @code{GDB}, shown in the first - column of the @samp{info tasks} display. - - If you do not specify @samp{task @var{taskid}} when you set a - breakpoint, the breakpoint applies to @emph{all} tasks of your - program. - - You can use the @code{task} qualifier on conditional breakpoints as - well; in this case, place @samp{task @var{taskid}} before the - breakpoint condition (before the @code{if}). - - @item task @var{taskno} - @cindex Task switching - - This command allows to switch to the task referred by @var{taskno}. In - particular, This allows to browse the backtrace of the specified - task. It is advised to switch back to the original task before - continuing execution otherwise the scheduling of the program may be - perturbated. - @end table - - @noindent - For more detailed information on the tasking support, see @cite{Debugging with GDB}. - - @node Debugging Generic Units - @section Debugging Generic Units - @cindex Debugging Generic Units - @cindex Generics - - @noindent - GNAT always uses code expansion for generic instantiation. This means that - each time an instantiation occurs, a complete copy of the original code is - made, with appropriate substitutions of formals by actuals. - - It is not possible to refer to the original generic entities in - @code{GDB}, but it is always possible to debug a particular instance of - a generic, by using the appropriate expanded names. For example, if we have - - @smallexample - @group - @cartouche - @b{procedure} g @b{is} - - @b{generic package} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer); - @b{end} k; - - @b{package body} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer) @b{is} - @b{begin} - v1 := v1 + 1; - @b{end} kp; - @b{end} k; - - @b{package} k1 @b{is new} k; - @b{package} k2 @b{is new} k; - - var : integer := 1; - - @b{begin} - k1.kp (var); - k2.kp (var); - k1.kp (var); - k2.kp (var); - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Then to break on a call to procedure kp in the k2 instance, simply - use the command: - - @smallexample - (gdb) break g.k2.kp - @end smallexample - - @noindent - When the breakpoint occurs, you can step through the code of the - instance in the normal manner and examine the values of local variables, as for - other units. - - @node GNAT Abnormal Termination or Failure to Terminate - @section GNAT Abnormal Termination or Failure to Terminate - @cindex GNAT Abnormal Termination or Failure to Terminate - - @noindent - When presented with programs that contain serious errors in syntax - or semantics, - GNAT may on rare occasions experience problems in operation, such - as aborting with a - segmentation fault or illegal memory access, raising an internal - exception, terminating abnormally, or failing to terminate at all. - In such cases, you can activate - various features of GNAT that can help you pinpoint the construct in your - program that is the likely source of the problem. - - The following strategies are presented in increasing order of - difficulty, corresponding to your experience in using GNAT and your - familiarity with compiler internals. - - @enumerate - @item - Run @code{gcc} with the @option{-gnatf}. This first - switch causes all errors on a given line to be reported. In its absence, - only the first error on a line is displayed. - - The @option{-gnatdO} switch causes errors to be displayed as soon as they - are encountered, rather than after compilation is terminated. If GNAT - terminates prematurely or goes into an infinite loop, the last error - message displayed may help to pinpoint the culprit. - - @item - Run @code{gcc} with the @code{-v (verbose)} switch. In this mode, - @code{gcc} produces ongoing information about the progress of the - compilation and provides the name of each procedure as code is - generated. This switch allows you to find which Ada procedure was being - compiled when it encountered a code generation problem. - - @item - @cindex @option{-gnatdc} switch - Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific - switch that does for the front-end what @code{-v} does for the back end. - The system prints the name of each unit, either a compilation unit or - nested unit, as it is being analyzed. - @item - Finally, you can start - @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the - front-end of GNAT, and can be run independently (normally it is just - called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you - would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The - @code{where} command is the first line of attack; the variable - @code{lineno} (seen by @code{print lineno}), used by the second phase of - @code{gnat1} and by the @code{gcc} backend, indicates the source line at - which the execution stopped, and @code{input_file name} indicates the name of - the source file. - @end enumerate - - @node Naming Conventions for GNAT Source Files - @section Naming Conventions for GNAT Source Files - - @noindent - In order to examine the workings of the GNAT system, the following - brief description of its organization may be helpful: - - @itemize @bullet - @item - Files with prefix @file{sc} contain the lexical scanner. - - @item - All files prefixed with @file{par} are components of the parser. The - numbers correspond to chapters of the Ada 95 Reference Manual. For example, - parsing of select statements can be found in @file{par-ch9.adb}. - - @item - All files prefixed with @file{sem} perform semantic analysis. The - numbers correspond to chapters of the Ada standard. For example, all - issues involving context clauses can be found in @file{sem_ch10.adb}. In - addition, some features of the language require sufficient special processing - to justify their own semantic files: sem_aggr for aggregates, sem_disp for - dynamic dispatching, etc. - - @item - All files prefixed with @file{exp} perform normalization and - expansion of the intermediate representation (abstract syntax tree, or AST). - these files use the same numbering scheme as the parser and semantics files. - For example, the construction of record initialization procedures is done in - @file{exp_ch3.adb}. - - @item - The files prefixed with @file{bind} implement the binder, which - verifies the consistency of the compilation, determines an order of - elaboration, and generates the bind file. - - @item - The files @file{atree.ads} and @file{atree.adb} detail the low-level - data structures used by the front-end. - - @item - The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of - the abstract syntax tree as produced by the parser. - - @item - The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of - all entities, computed during semantic analysis. - - @item - Library management issues are dealt with in files with prefix - @file{lib}. - - @item - @findex Ada - @cindex Annex A - Ada files with the prefix @file{a-} are children of @code{Ada}, as - defined in Annex A. - - @item - @findex Interfaces - @cindex Annex B - Files with prefix @file{i-} are children of @code{Interfaces}, as - defined in Annex B. - - @item - @findex System - Files with prefix @file{s-} are children of @code{System}. This includes - both language-defined children and GNAT run-time routines. - - @item - @findex GNAT - Files with prefix @file{g-} are children of @code{GNAT}. These are useful - general-purpose packages, fully documented in their specifications. All - the other @file{.c} files are modifications of common @code{gcc} files. - @end itemize - - @node Getting Internal Debugging Information - @section Getting Internal Debugging Information - - @noindent - Most compilers have internal debugging switches and modes. GNAT - does also, except GNAT internal debugging switches and modes are not - secret. A summary and full description of all the compiler and binder - debug flags are in the file @file{debug.adb}. You must obtain the - sources of the compiler to see the full detailed effects of these flags. - - The switches that print the source of the program (reconstructed from - the internal tree) are of general interest for user programs, as are the - options to print - the full internal tree, and the entity table (the symbol table - information). The reconstructed source provides a readable version of the - program after the front-end has completed analysis and expansion, and is useful - when studying the performance of specific constructs. For example, constraint - checks are indicated, complex aggregates are replaced with loops and - assignments, and tasking primitives are replaced with run-time calls. - - @node Stack Traceback - @section Stack Traceback - @cindex traceback - @cindex stack traceback - @cindex stack unwinding - - @noindent - Traceback is a mechanism to display the sequence of subprogram calls that - leads to a specified execution point in a program. Often (but not always) - the execution point is an instruction at which an exception has been raised. - This mechanism is also known as @i{stack unwinding} because it obtains - its information by scanning the run-time stack and recovering the activation - records of all active subprograms. Stack unwinding is one of the most - important tools for program debugging. - - @noindent - The first entry stored in traceback corresponds to the deepest calling level, - that is to say the subprogram currently executing the instruction - from which we want to obtain the traceback. - - @noindent - Note that there is no runtime performance penalty when stack traceback - is enabled and no exception are raised during program execution. - - @menu - * Non-Symbolic Traceback:: - * Symbolic Traceback:: - @end menu - - @node Non-Symbolic Traceback - @subsection Non-Symbolic Traceback - @cindex traceback, non-symbolic - - @noindent - Note: this feature is not supported on all platforms. See - @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported - platforms. - - @menu - * Tracebacks From an Unhandled Exception:: - * Tracebacks From Exception Occurrences (non-symbolic):: - * Tracebacks From Anywhere in a Program (non-symbolic):: - @end menu - - @node Tracebacks From an Unhandled Exception - @subsubsection Tracebacks From an Unhandled Exception - - @noindent - A runtime non-symbolic traceback is a list of addresses of call instructions. - To enable this feature you must use the @code{-E} - @code{gnatbind}'s option. With this option a stack traceback is stored as part - of exception information. It is possible to retrieve this information using the - standard @code{Ada.Exception.Exception_Information} routine. - - @noindent - Let's have a look at a simple example: - - @smallexample - @cartouche - @group - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @noindent - As we see the traceback lists a sequence of addresses for the unhandled - exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to - guess that this exception come from procedure P1. To translate these - addresses into the source lines where the calls appear, the - @code{addr2line} tool, described below, is invaluable. The use of this tool - requires the program to be compiled with debug information. - - @smallexample - $ gnatmake -g stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - - $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 - 0x4011f1 0x77e892a4 - - 00401373 at d:/stb/stb.adb:5 - 0040138B at d:/stb/stb.adb:10 - 0040139C at d:/stb/stb.adb:14 - 00401335 at d:/stb/b~stb.adb:104 - 004011C4 at /build/.../crt1.c:200 - 004011F1 at /build/.../crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - @code{addr2line} has a number of other useful options: - - @table @code - @item --functions - to get the function name corresponding to any location - - @item --demangle=gnat - to use the @b{gnat} decoding mode for the function names. Note that - for binutils version 2.9.x the option is simply @code{--demangle}. - @end table - - @smallexample - $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b - 0x40139c 0x401335 0x4011c4 0x4011f1 - - 00401373 in stb.p1 at d:/stb/stb.adb:5 - 0040138B in stb.p2 at d:/stb/stb.adb:10 - 0040139C in stb at d:/stb/stb.adb:14 - 00401335 in main at d:/stb/b~stb.adb:104 - 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200 - 004011F1 in at /build/.../crt1.c:222 - @end smallexample - - @noindent - From this traceback we can see that the exception was raised in - @file{stb.adb} at line 5, which was reached from a procedure call in - @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file, - which contains the call to the main program. - @pxref{Running gnatbind}. The remaining entries are assorted runtime routines, - and the output will vary from platform to platform. - - @noindent - It is also possible to use @code{GDB} with these traceback addresses to debug - the program. For example, we can break at a given code location, as reported - in the stack traceback: - - @smallexample - $ gdb -nw stb - - (gdb) break *0x401373 - Breakpoint 1 at 0x401373: file stb.adb, line 5. - @end smallexample - - @noindent - It is important to note that the stack traceback addresses - do not change when debug information is included. This is particularly useful - because it makes it possible to release software without debug information (to - minimize object size), get a field report that includes a stack traceback - whenever an internal bug occurs, and then be able to retrieve the sequence - of calls with the same program compiled with debug information. - - @node Tracebacks From Exception Occurrences (non-symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @noindent - Non-symbolic tracebacks are obtained by using the @code{-E} binder argument. - The stack traceback is attached to the exception information string, and can - be retrieved in an exception handler within the Ada program, by means of the - Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with Ada.Exceptions; - - procedure STB is - - use Ada; - use Ada.Exceptions; - - procedure P1 is - K : Positive := 1; - begin - K := K - 1; - exception - when E : others => - Text_IO.Put_Line (Exception_Information (E)); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @noindent - This program will output: - - @smallexample - $ stb - - Exception name: CONSTRAINT_ERROR - Message: stb.adb:12 - Call stack traceback locations: - 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @node Tracebacks From Anywhere in a Program (non-symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is also possible to retrieve a stack traceback from anywhere in a - program. For this you need to - use the @code{GNAT.Traceback} API. This package includes a procedure called - @code{Call_Chain} that computes a complete stack traceback, as well as useful - display procedures described below. It is not necessary to use the - @code{-E gnatbind} option in this case, because the stack traceback mechanism - is invoked explicitly. - - @noindent - In the following example we compute a traceback at a specific location in - the program, and we display it using @code{GNAT.Debug_Utilities.Image} to - convert addresses to strings: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Debug_Utilities; - - procedure STB is - - use Ada; - use GNAT; - use GNAT.Traceback; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - - Text_IO.Put ("In STB.P1 : "); - - for K in 1 .. Len loop - Text_IO.Put (Debug_Utilities.Image (TB (K))); - Text_IO.Put (' '); - end loop; - - Text_IO.New_Line; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb - $ stb - - In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# - 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# - @end smallexample - - @node Symbolic Traceback - @subsection Symbolic Traceback - @cindex traceback, symbolic - - @noindent - A symbolic traceback is a stack traceback in which procedure names are - associated with each code location. - - @noindent - Note that this feature is not supported on all platforms. See - @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete - list of currently supported platforms. - - @noindent - Note that the symbolic traceback requires that the program be compiled - with debug information. If it is not compiled with debug information - only the non-symbolic information will be valid. - - @menu - * Tracebacks From Exception Occurrences (symbolic):: - * Tracebacks From Anywhere in a Program (symbolic):: - @end menu - - @node Tracebacks From Exception Occurrences (symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback.Symbolic; - - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - procedure P3 is - begin - P2; - end P3; - - begin - P3; - exception - when E : others => - Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl - $ stb - - 0040149F in stb.p1 at stb.adb:8 - 004014B7 in stb.p2 at stb.adb:13 - 004014CF in stb.p3 at stb.adb:18 - 004015DD in ada.stb at stb.adb:22 - 00401461 in main at b~stb.adb:168 - 004011C4 in __mingw_CRTStartup at crt1.c:200 - 004011F1 in mainCRTStartup at crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - The exact sequence of linker options may vary from platform to platform. - The above @code{-largs} section is for Windows platforms. By contrast, - under Unix there is no need for the @code{-largs} section. - Differences across platforms are due to details of linker implementation. - - @node Tracebacks From Anywhere in a Program (symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is possible to get a symbolic stack traceback - from anywhere in a program, just as for non-symbolic tracebacks. - The first step is to obtain a non-symbolic - traceback, and then call @code{Symbolic_Traceback} to compute the symbolic - information. Here is an example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Traceback.Symbolic; - - procedure STB is - - use Ada; - use GNAT.Traceback; - use GNAT.Traceback.Symbolic; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - - @node Inline Assembler - @chapter Inline Assembler - - @noindent - If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program. First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT. However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler. The Inline Assembler approach offers a number of advantages, including the following: - - @itemize @bullet - @item No need to use non-Ada tools - @item Consistent interface over different targets - @item Automatic usage of the proper calling conventions - @item Access to Ada constants and variables - @item Definition of intrinsic routines - @item Possibility of inlining a subprogram comprising assembler code - @item Code optimizer can take Inline Assembler code into account - @end itemize - - This chapter presents a series of examples to show you how to use the Inline Assembler. Although it focuses on the Intel x86, the general approach applies also to other processors. It is assumed that you are familiar with Ada and with assembly language programming. - - @menu - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - @end menu - - @c --------------------------------------------------------------------------- - @node Basic Assembler Syntax - @section Basic Assembler Syntax - - @noindent - The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a - language that descends from the AT&T Unix assembler @emph{as} (and which is often - referred to as ``AT&T syntax''). - The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions. - See the gcc @emph{as} and @emph{gas} (an @emph{as} macro - pre-processor) documentation for further information. - - @table @asis - @item Register names - gcc / @emph{as}: Prefix with ``%''; for example @code{%eax} - @* - Intel: No extra punctuation; for example @code{eax} - - @item Immediate operand - gcc / @emph{as}: Prefix with ``$''; for example @code{$4} - @* - Intel: No extra punctuation; for example @code{4} - - @item Address - gcc / @emph{as}: Prefix with ``$''; for example @code{$loc} - @* - Intel: No extra punctuation; for example @code{loc} - - @item Memory contents - gcc / @emph{as}: No extra punctuation; for example @code{loc} - @* - Intel: Square brackets; for example @code{[loc]} - - @item Register contents - gcc / @emph{as}: Parentheses; for example @code{(%eax)} - @* - Intel: Square brackets; for example @code{[eax]} - - @item Hexadecimal numbers - gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} - @* - Intel: Trailing ``h''; for example @code{A0h} - - @item Operand size - gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word - @* - Intel: Implicit, deduced by assembler; for example @code{mov} - - @item Instruction repetition - gcc / @emph{as}: Split into two lines; for example - @* - @code{rep} - @* - @code{stosl} - @* - Intel: Keep on one line; for example @code{rep stosl} - - @item Order of operands - gcc / @emph{as}: Source first; for example @code{movw $4, %eax} - @* - Intel: Destination first; for example @code{mov eax, 4} - @end table - - @c --------------------------------------------------------------------------- - @node A Simple Example of Inline Assembler - @section A Simple Example of Inline Assembler - - @noindent - The following example will generate a single assembly language statement, @code{nop}, which does nothing. Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility. - - @smallexample - @group - with System.Machine_Code; use System.Machine_Code; - procedure Nothing is - begin - Asm ("nop"); - end Nothing; - @end group - @end smallexample - - @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction. - @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions. - - The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}. - - Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}. You can build the executable in the usual way: - @smallexample - gnatmake nothing - @end smallexample - However, the interesting aspect of this example is not its run-time behavior but rather the - generated assembly code. To see this output, invoke the compiler as follows: - @smallexample - gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb} - @end smallexample - where the options are: - - @table @code - @item -c - compile only (no bind or link) - @item -S - generate assembler listing - @item -fomit-frame-pointer - do not set up separate stack frames - @item -gnatp - do not add runtime checks - @end table - - This gives a human-readable assembler version of the code. The resulting - file will have the same name as the Ada source file, but with a @code{.s} extension. - In our example, the file @file{nothing.s} has the following contents: - - @smallexample - @group - .file "nothing.adb" - gcc2_compiled.: - ___gnu_compiled_ada: - .text - .align 4 - .globl __ada_nothing - __ada_nothing: - #APP - nop - #NO_APP - jmp L1 - .align 2,0x90 - L1: - ret - @end group - @end smallexample - - The assembly code you included is clearly indicated by - the compiler, between the @code{#APP} and @code{#NO_APP} - delimiters. The character before the 'APP' and 'NOAPP' - can differ on different targets. For example, Linux uses '#APP' while - on NT you will see '/APP'. - - If you make a mistake in your assembler code (such as using the - wrong size modifier, or using a wrong operand for the instruction) GNAT - will report this error in a temporary file, which will be deleted when - the compilation is finished. Generating an assembler file will help - in such cases, since you can assemble this file separately using the - @emph{as} assembler that comes with gcc. - - Assembling the file using the command - - @smallexample - as @file{nothing.s} - @end smallexample - @noindent - will give you error messages whose lines correspond to the assembler - input file, so you can easily find and correct any mistakes you made. - If there are no errors, @emph{as} will generate an object file @file{nothing.out}. - - @c --------------------------------------------------------------------------- - @node Output Variables in Inline Assembler - @section Output Variables in Inline Assembler - - @noindent - The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements. - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags; - @end group - @end smallexample - - In order to have a nicely aligned assembly listing, we have separated - multiple assembler statements in the Asm template string with linefeed (ASCII.LF) - and horizontal tab (ASCII.HT) characters. The resulting section of the - assembly output file is: - - @smallexample - @group - #APP - pushfl - popl %eax - movl %eax, -40(%ebp) - #NO_APP - @end group - @end smallexample - - It would have been legal to write the Asm invocation as: - - @smallexample - Asm ("pushfl popl %%eax movl %%eax, %0") - @end smallexample - - but in the generated assembler file, this would come out as: - - @smallexample - #APP - pushfl popl %eax movl %eax, -40(%ebp) - #NO_APP - @end smallexample - - which is not so convenient for the human reader. - - We use Ada comments - at the end of each line to explain what the assembler instructions - actually do. This is a useful convention. - - When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign. Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}. In the generated assembly code, one of the percent signs will be stripped off. - - Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}. - An output variable is illustrated in - the third statement in the Asm template string: - @smallexample - movl %%eax, %0 - @end smallexample - The intent is to store the contents of the eax register in a variable that can be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization. The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable. - - Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}: - @smallexample - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end smallexample - - The output is defined by the @code{Asm_Output} attribute of the target type; the general format is - @smallexample - Type'Asm_Output (constraint_string, variable_name) - @end smallexample - - The constraint string directs the compiler how - to store/access the associated variable. In the example - @smallexample - Unsigned_32'Asm_Output ("=m", Flags); - @end smallexample - the @code{"m"} (memory) constraint tells the compiler that the variable - @code{Flags} should be stored in a memory variable, thus preventing - the optimizer from keeping it in a register. In contrast, - @smallexample - Unsigned_32'Asm_Output ("=r", Flags); - @end smallexample - uses the @code{"r"} (register) constraint, telling the compiler to - store the variable in a register. - - If the constraint is preceded by the equal character (@strong{=}), it tells the - compiler that the variable will be used to store data into it. - - In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer - to choose whatever it deems best. - - There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following: - - @table @code - @item = - output constraint - @item g - global (i.e. can be stored anywhere) - @item m - in memory - @item I - a constant - @item a - use eax - @item b - use ebx - @item c - use ecx - @item d - use edx - @item S - use esi - @item D - use edi - @item r - use one of eax, ebx, ecx or edx - @item q - use one of eax, ebx, ecx, edx, esi or edi - @end table - - The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string. - - You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer. Thus in - @smallexample - @group - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end group - @end smallexample - @noindent - @code{%0} will be replaced in the expanded code by the appropriate operand, - whatever - the compiler decided for the @code{Flags} variable. - - In general, you may have any number of output variables: - @itemize @bullet - @item - Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. - @item - Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes - @end itemize - - For example: - @smallexample - @group - Asm ("movl %%eax, %0" & LF & HT & - "movl %%ebx, %1" & LF & HT & - "movl %%ecx, %2", - Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A - Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B - Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C - @end group - @end smallexample - @noindent - where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program. - - As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_2 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax", -- save flags in eax - Outputs => Unsigned_32'Asm_Output ("=a", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_2; - @end group - @end smallexample - - @noindent - The @code{"a"} constraint tells the compiler that the @code{Flags} - variable will come from the eax register. Here is the resulting code: - - @smallexample - @group - #APP - pushfl - popl %eax - #NO_APP - movl %eax,-40(%ebp) - @end group - @end smallexample - - @noindent - The compiler generated the store of eax into Flags after - expanding the assembler code. - - Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_3 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "pop %0", -- save flags in Flags - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_3; - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Input Variables in Inline Assembler - @section Input Variables in Inline Assembler - - @noindent - The example in this section illustrates how to specify the source operands for assembly language statements. The program simply increments its input value by 1: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Incr (Value); - Put_Line ("Value after is" & Value'Img); - end Increment; - @end group - @end smallexample - - The @code{Outputs} parameter to @code{Asm} specifies - that the result will be in the eax register and that it is to be stored in the @code{Result} - variable. - - The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an - @code{Asm_Input} attribute. The - @code{"="} constraint, indicating an output value, is not present. - - You can have multiple input variables, in the same way that you can have more - than one output variable. - - The parameter count (%0, %1) etc, now starts at the first input - statement, and continues with the output statements. - When both parameters use the same variable, the - compiler will treat them as the same %n operand, which is the case here. - - Just as the @code{Outputs} parameter causes the register to be stored into the - target variable after execution of the assembler statements, so does the - @code{Inputs} parameter cause its variable to be loaded into the register before execution - of the - assembler statements. - - Thus the effect of the @code{Asm} invocation is: - @enumerate - @item load the 32-bit value of @code{Value} into eax - @item execute the @code{incl %eax} instruction - @item store the contents of eax into the @code{Result} variable - @end enumerate - - The resulting assembler file (with @code{-O2} optimization) contains: - @smallexample - @group - _increment__incr.1: - subl $4,%esp - movl 8(%esp),%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - movl %ecx,(%esp) - addl $4,%esp - ret - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Inlining Inline Assembler Code - @section Inlining Inline Assembler Code - - @noindent - For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame) - can be significant, compared to the amount of code in the subprogram body. - A solution is to apply Ada's @code{Inline} pragma to the subprogram, - which directs the compiler to expand invocations of the subprogram at the point(s) - of call, instead of setting up a stack frame for out-of-line calls. - Here is the resulting program: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment_2 is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - pragma Inline (Increment); - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Increment (Value); - Put_Line ("Value after is" & Value'Img); - end Increment_2; - @end group - @end smallexample - - Compile the program with both optimization (@code{-O2}) and inlining - enabled (@option{-gnatpn} instead of @option{-gnatp}). - - The @code{Incr} function is still compiled as usual, but at the - point in @code{Increment} where our function used to be called: - - @smallexample - @group - pushl %edi - call _increment__incr.1 - @end group - @end smallexample - - @noindent - the code for the function body directly appears: - - @smallexample - @group - movl %esi,%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - @end group - @end smallexample - - @noindent - thus saving the overhead of stack frame setup and an out-of-line call. - - @c --------------------------------------------------------------------------- - @node Other Asm Functionality - @section Other @code{Asm} Functionality - - @noindent - This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations. - - @menu - * The Clobber Parameter:: - * The Volatile Parameter:: - @end menu - - @c --------------------------------------------------------------------------- - @node The Clobber Parameter - @subsection The @code{Clobber} Parameter - - @noindent - One of the dangers of intermixing assembly language and a compiled language such as Ada is - that the compiler needs to be aware of which registers are being used by the assembly code. - In some cases, such as the earlier examples, the constraint string is sufficient to - indicate register usage (e.g. "a" for the eax register). But more generally, the - compiler needs an explicit identification of the registers that are used by the Inline - Assembly statements. - - Using a register that the compiler doesn't know about - could be a side effect of an instruction (like @code{mull} - storing its result in both eax and edx). - It can also arise from explicit register usage in your - assembly code; for example: - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out)); - @end group - @end smallexample - @noindent - where the compiler (since it does not analyze the @code{Asm} template string) - does not know you are using the ebx register. - - In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, - to identify the registers that will be used by your assembly code: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx"); - @end group - @end smallexample - - The Clobber parameter is a static string expression specifying the - register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign. - Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"} - - The @code{Clobber} parameter has several additional uses: - @enumerate - @item Use the "register" name @code{cc} to indicate that flags might have changed - @item Use the "register" name @code{memory} if you changed a memory location - @end enumerate - - @c --------------------------------------------------------------------------- - @node The Volatile Parameter - @subsection The @code{Volatile} Parameter - @cindex Volatile parameter - - @noindent - Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects. - For example, when - an @code{Asm} invocation with an input variable is inside a loop, the compiler might move - the loading of the input variable outside the loop, regarding it as a - one-time initialization. - - If this effect is not desired, you can disable such optimizations by setting the - @code{Volatile} parameter to @code{True}; for example: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx", - Volatile => True); - @end group - @end smallexample - - By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs} - parameter. - - Although setting @code{Volatile} to @code{True} prevents unwanted optimizations, - it will also disable other optimizations that might be important for efficiency. - In general, you should set @code{Volatile} to @code{True} only if the compiler's - optimizations have created problems. - - @c --------------------------------------------------------------------------- - @node A Complete Example - @section A Complete Example - - @noindent - This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler - capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}. - The package declares a collection of functions that detect the properties of the 32-bit - x86 processor that is running the program. The main procedure invokes these functions - and displays the information. - - The Intel_CPU package could be enhanced by adding functions to - detect the type of x386 co-processor, the processor caching options and - special operations such as the SIMD extensions. - - Although the Intel_CPU package has been written for 32-bit Intel - compatible CPUs, it is OS neutral. It has been tested on DOS, - Windows/NT and Linux. - - @menu - * Check_CPU Procedure:: - * Intel_CPU Package Specification:: - * Intel_CPU Package Body:: - @end menu - - @c --------------------------------------------------------------------------- - @node Check_CPU Procedure - @subsection @code{Check_CPU} Procedure - @cindex Check_CPU procedure - - @smallexample - --------------------------------------------------------------------- - -- -- - -- Uses the Intel_CPU package to identify the CPU the program is -- - -- running on, and some of the features it supports. -- - -- -- - --------------------------------------------------------------------- - - with Intel_CPU; -- Intel CPU detection functions - with Ada.Text_IO; -- Standard text I/O - with Ada.Command_Line; -- To set the exit status - - procedure Check_CPU is - - Type_Found : Boolean := False; - -- Flag to indicate that processor was identified - - Features : Intel_CPU.Processor_Features; - -- The processor features - - Signature : Intel_CPU.Processor_Signature; - -- The processor type signature - - begin - - ----------------------------------- - -- Display the program banner. -- - ----------------------------------- - - Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name & - ": check Intel CPU version and features, v1.0"); - Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever"); - Ada.Text_IO.New_Line; - - ----------------------------------------------------------------------- - -- We can safely start with the assumption that we are on at least -- - -- a x386 processor. If the CPUID instruction is present, then we -- - -- have a later processor type. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Has_CPUID = False then - - -- No CPUID instruction, so we assume this is indeed a x386 - -- processor. We can still check if it has a FP co-processor. - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line - ("x386-type processor with a FP co-processor"); - else - Ada.Text_IO.Put_Line - ("x386-type processor without a FP co-processor"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check for CPUID - - ----------------------------------------------------------------------- - -- If CPUID is supported, check if this is a true Intel processor, -- - -- if it is not, display a warning. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then - Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor"); - Ada.Text_IO.Put_Line ("*** Some information may be incorrect"); - end if; -- check if Intel - - ---------------------------------------------------------------------- - -- With the CPUID instruction present, we can assume at least a -- - -- x486 processor. If the CPUID support level is < 1 then we have -- - -- to leave it at that. -- - ---------------------------------------------------------------------- - - if Intel_CPU.CPUID_Level < 1 then - - -- Ok, this is a x486 processor. we still can get the Vendor ID - Ada.Text_IO.Put_Line ("x486-type processor"); - Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID); - - -- We can also check if there is a FPU present - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line ("Floating-Point support"); - else - Ada.Text_IO.Put_Line ("No Floating-Point support"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check CPUID level - - --------------------------------------------------------------------- - -- With a CPUID level of 1 we can use the processor signature to -- - -- determine it's exact type. -- - --------------------------------------------------------------------- - - Signature := Intel_CPU.Signature; - - ---------------------------------------------------------------------- - -- Ok, now we go into a lot of messy comparisons to get the -- - -- processor type. For clarity, no attememt to try to optimize the -- - -- comparisons has been made. Note that since Intel_CPU does not -- - -- support getting cache info, we cannot distinguish between P5 -- - -- and Celeron types yet. -- - ---------------------------------------------------------------------- - - -- x486SL - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486SL processor"); - end if; - - -- x486DX2 Write-Back - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0111# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor"); - end if; - - -- x486DX4 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 processor"); - end if; - - -- x486DX4 Overdrive - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor"); - end if; - - -- Pentium (60, 66) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium processor (60, 66)"); - end if; - - -- Pentium (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive (60, 66) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)"); - end if; - - -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive processor for x486 processor-based systems - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor for x486 processor-based systems"); - end if; - - -- Pentium processor with MMX technology (166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor with MMX technology (166, 200)"); - end if; - - -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor with MMX " & - "technology for Pentium processor (75, 90, 100, 120, 133)"); - end if; - - -- Pentium Pro processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro processor"); - end if; - - -- Pentium II processor, model 3 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium II processor, model 3"); - end if; - - -- Pentium II processor, model 5 or Celeron processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0101# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium II processor, model 5 or Celeron processor"); - end if; - - -- Pentium Pro OverDrive processor - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor"); - end if; - - -- If no type recognized, we have an unknown. Display what - -- we _do_ know - if Type_Found = False then - Ada.Text_IO.Put_Line ("Unknown processor"); - end if; - - ----------------------------------------- - -- Display processor stepping level. -- - ----------------------------------------- - - Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img); - - --------------------------------- - -- Display vendor ID string. -- - --------------------------------- - - Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID); - - ------------------------------------ - -- Get the processors features. -- - ------------------------------------ - - Features := Intel_CPU.Features; - - ----------------------------- - -- Check for a FPU unit. -- - ----------------------------- - - if Features.FPU = True then - Ada.Text_IO.Put_Line ("Floating-Point unit available"); - else - Ada.Text_IO.Put_Line ("no Floating-Point unit"); - end if; -- check for FPU - - -------------------------------- - -- List processor features. -- - -------------------------------- - - Ada.Text_IO.Put_Line ("Supported features: "); - - -- Virtual Mode Extension - if Features.VME = True then - Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension"); - end if; - - -- Debugging Extension - if Features.DE = True then - Ada.Text_IO.Put_Line (" DE - Debugging Extension"); - end if; - - -- Page Size Extension - if Features.PSE = True then - Ada.Text_IO.Put_Line (" PSE - Page Size Extension"); - end if; - - -- Time Stamp Counter - if Features.TSC = True then - Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter"); - end if; - - -- Model Specific Registers - if Features.MSR = True then - Ada.Text_IO.Put_Line (" MSR - Model Specific Registers"); - end if; - - -- Physical Address Extension - if Features.PAE = True then - Ada.Text_IO.Put_Line (" PAE - Physical Address Extension"); - end if; - - -- Machine Check Extension - if Features.MCE = True then - Ada.Text_IO.Put_Line (" MCE - Machine Check Extension"); - end if; - - -- CMPXCHG8 instruction supported - if Features.CX8 = True then - Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction"); - end if; - - -- on-chip APIC hardware support - if Features.APIC = True then - Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support"); - end if; - - -- Fast System Call - if Features.SEP = True then - Ada.Text_IO.Put_Line (" SEP - Fast System Call"); - end if; - - -- Memory Type Range Registers - if Features.MTRR = True then - Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers"); - end if; - - -- Page Global Enable - if Features.PGE = True then - Ada.Text_IO.Put_Line (" PGE - Page Global Enable"); - end if; - - -- Machine Check Architecture - if Features.MCA = True then - Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture"); - end if; - - -- Conditional Move Instruction Supported - if Features.CMOV = True then - Ada.Text_IO.Put_Line - (" CMOV - Conditional Move Instruction Supported"); - end if; - - -- Page Attribute Table - if Features.PAT = True then - Ada.Text_IO.Put_Line (" PAT - Page Attribute Table"); - end if; - - -- 36-bit Page Size Extension - if Features.PSE_36 = True then - Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension"); - end if; - - -- MMX technology supported - if Features.MMX = True then - Ada.Text_IO.Put_Line (" MMX - MMX technology supported"); - end if; - - -- Fast FP Save and Restore - if Features.FXSR = True then - Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore"); - end if; - - --------------------- - -- Program done. -- - --------------------- - - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - - exception - - when others => - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); - raise; - - end Check_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Specification - @subsection @code{Intel_CPU} Package Specification - @cindex Intel_CPU package specification - - @smallexample - ------------------------------------------------------------------------- - -- -- - -- file: intel_cpu.ads -- - -- -- - -- ********************************************* -- - -- * WARNING: for 32-bit Intel processors only * -- - -- ********************************************* -- - -- -- - -- This package contains a number of subprograms that are useful in -- - -- determining the Intel x86 CPU (and the features it supports) on -- - -- which the program is running. -- - -- -- - -- The package is based upon the information given in the Intel -- - -- Application Note AP-485: "Intel Processor Identification and the -- - -- CPUID Instruction" as of April 1998. This application note can be -- - -- found on www.intel.com. -- - -- -- - -- It currently deals with 32-bit processors only, will not detect -- - -- features added after april 1998, and does not guarantee proper -- - -- results on Intel-compatible processors. -- - -- -- - -- Cache info and x386 fpu type detection are not supported. -- - -- -- - -- This package does not use any privileged instructions, so should -- - -- work on any OS running on a 32-bit Intel processor. -- - -- -- - ------------------------------------------------------------------------- - - with Interfaces; use Interfaces; - -- for using unsigned types - - with System.Machine_Code; use System.Machine_Code; - -- for using inline assembler code - - with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; - -- for inserting control characters - - package Intel_CPU is - - ---------------------- - -- Processor bits -- - ---------------------- - - subtype Num_Bits is Natural range 0 .. 31; - -- the number of processor bits (32) - - -------------------------- - -- Processor register -- - -------------------------- - - -- define a processor register type for easy access to - -- the individual bits - - type Processor_Register is array (Num_Bits) of Boolean; - pragma Pack (Processor_Register); - for Processor_Register'Size use 32; - - ------------------------- - -- Unsigned register -- - ------------------------- - - -- define a processor register type for easy access to - -- the individual bytes - - type Unsigned_Register is - record - L1 : Unsigned_8; - H1 : Unsigned_8; - L2 : Unsigned_8; - H2 : Unsigned_8; - end record; - - for Unsigned_Register use - record - L1 at 0 range 0 .. 7; - H1 at 0 range 8 .. 15; - L2 at 0 range 16 .. 23; - H2 at 0 range 24 .. 31; - end record; - - for Unsigned_Register'Size use 32; - - --------------------------------- - -- Intel processor vendor ID -- - --------------------------------- - - Intel_Processor : constant String (1 .. 12) := "GenuineIntel"; - -- indicates an Intel manufactured processor - - ------------------------------------ - -- Processor signature register -- - ------------------------------------ - - -- a register type to hold the processor signature - - type Processor_Signature is - record - Stepping : Natural range 0 .. 15; - Model : Natural range 0 .. 15; - Family : Natural range 0 .. 15; - Processor_Type : Natural range 0 .. 3; - Reserved : Natural range 0 .. 262143; - end record; - - for Processor_Signature use - record - Stepping at 0 range 0 .. 3; - Model at 0 range 4 .. 7; - Family at 0 range 8 .. 11; - Processor_Type at 0 range 12 .. 13; - Reserved at 0 range 14 .. 31; - end record; - - for Processor_Signature'Size use 32; - - ----------------------------------- - -- Processor features register -- - ----------------------------------- - - -- a processor register to hold the processor feature flags - - type Processor_Features is - record - FPU : Boolean; -- floating point unit on chip - VME : Boolean; -- virtual mode extension - DE : Boolean; -- debugging extension - PSE : Boolean; -- page size extension - TSC : Boolean; -- time stamp counter - MSR : Boolean; -- model specific registers - PAE : Boolean; -- physical address extension - MCE : Boolean; -- machine check extension - CX8 : Boolean; -- cmpxchg8 instruction - APIC : Boolean; -- on-chip apic hardware - Res_1 : Boolean; -- reserved for extensions - SEP : Boolean; -- fast system call - MTRR : Boolean; -- memory type range registers - PGE : Boolean; -- page global enable - MCA : Boolean; -- machine check architecture - CMOV : Boolean; -- conditional move supported - PAT : Boolean; -- page attribute table - PSE_36 : Boolean; -- 36-bit page size extension - Res_2 : Natural range 0 .. 31; -- reserved for extensions - MMX : Boolean; -- MMX technology supported - FXSR : Boolean; -- fast FP save and restore - Res_3 : Natural range 0 .. 127; -- reserved for extensions - end record; - - for Processor_Features use - record - FPU at 0 range 0 .. 0; - VME at 0 range 1 .. 1; - DE at 0 range 2 .. 2; - PSE at 0 range 3 .. 3; - TSC at 0 range 4 .. 4; - MSR at 0 range 5 .. 5; - PAE at 0 range 6 .. 6; - MCE at 0 range 7 .. 7; - CX8 at 0 range 8 .. 8; - APIC at 0 range 9 .. 9; - Res_1 at 0 range 10 .. 10; - SEP at 0 range 11 .. 11; - MTRR at 0 range 12 .. 12; - PGE at 0 range 13 .. 13; - MCA at 0 range 14 .. 14; - CMOV at 0 range 15 .. 15; - PAT at 0 range 16 .. 16; - PSE_36 at 0 range 17 .. 17; - Res_2 at 0 range 18 .. 22; - MMX at 0 range 23 .. 23; - FXSR at 0 range 24 .. 24; - Res_3 at 0 range 25 .. 31; - end record; - - for Processor_Features'Size use 32; - - ------------------- - -- Subprograms -- - ------------------- - - function Has_FPU return Boolean; - -- return True if a FPU is found - -- use only if CPUID is not supported - - function Has_CPUID return Boolean; - -- return True if the processor supports the CPUID instruction - - function CPUID_Level return Natural; - -- return the CPUID support level (0, 1 or 2) - -- can only be called if the CPUID instruction is supported - - function Vendor_ID return String; - -- return the processor vendor identification string - -- can only be called if the CPUID instruction is supported - - function Signature return Processor_Signature; - -- return the processor signature - -- can only be called if the CPUID instruction is supported - - function Features return Processor_Features; - -- return the processors features - -- can only be called if the CPUID instruction is supported - - private - - ------------------------ - -- EFLAGS bit names -- - ------------------------ - - ID_Flag : constant Num_Bits := 21; - -- ID flag bit - - end Intel_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Body - @subsection @code{Intel_CPU} Package Body - @cindex Intel_CPU package body - - @smallexample - package body Intel_CPU is - - --------------------------- - -- Detect FPU presence -- - --------------------------- - - -- There is a FPU present if we can set values to the FPU Status - -- and Control Words. - - function Has_FPU return Boolean is - - Register : Unsigned_16; - -- processor register to store a word - - begin - - -- check if we can change the status word - Asm ( - - -- the assembler code - "finit" & LF & HT & -- reset status word - "movw $0x5A5A, %%ax" & LF & HT & -- set value status word - "fnstsw %0" & LF & HT & -- save status word - "movw %%ax, %0", -- store status word - - -- output stored in Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register), - - -- tell compiler that we used eax - Clobber => "eax"); - - -- if the status word is zero, there is no FPU - if Register = 0 then - return False; -- no status word - end if; -- check status word value - - -- check if we can get the control word - Asm ( - - -- the assembler code - "fnstcw %0", -- save the control word - - -- output into Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register)); - - -- check the relevant bits - if (Register and 16#103F#) /= 16#003F# then - return False; -- no control word - end if; -- check control word value - - -- FPU found - return True; - - end Has_FPU; - - -------------------------------- - -- Detect CPUID instruction -- - -------------------------------- - - -- The processor supports the CPUID instruction if it is possible - -- to change the value of ID flag bit in the EFLAGS register. - - function Has_CPUID return Boolean is - - Original_Flags, Modified_Flags : Processor_Register; - -- EFLAG contents before and after changing the ID flag - - begin - - -- try flipping the ID flag in the EFLAGS register - Asm ( - - -- the assembler code - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %%eax" & LF & HT & -- pop EFLAGS into eax - "movl %%eax, %0" & LF & HT & -- save EFLAGS content - "xor $0x200000, %%eax" & LF & HT & -- flip ID flag - "push %%eax" & LF & HT & -- push EFLAGS on stack - "popfl" & LF & HT & -- load EFLAGS register - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %1", -- save EFLAGS content - - -- output values, may be anything - -- Original_Flags is %0 - -- Modified_Flags is %1 - Outputs => - (Processor_Register'Asm_output ("=g", Original_Flags), - Processor_Register'Asm_output ("=g", Modified_Flags)), - - -- tell compiler eax is destroyed - Clobber => "eax"); - - -- check if CPUID is supported - if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then - return True; -- ID flag was modified - else - return False; -- ID flag unchanged - end if; -- check for CPUID - - end Has_CPUID; - - ------------------------------- - -- Get CPUID support level -- - ------------------------------- - - function CPUID_Level return Natural is - - Level : Unsigned_32; - -- returned support level - - begin - - -- execute CPUID, storing the results in the Level register - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero is stored in eax - -- returning the support level in eax - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- eax is stored in Level - Outputs => Unsigned_32'Asm_output ("=a", Level), - - -- tell compiler ebx, ecx and edx registers are destroyed - Clobber => "ebx, ecx, edx"); - - -- return the support level - return Natural (Level); - - end CPUID_Level; - - -------------------------------- - -- Get CPU Vendor ID String -- - -------------------------------- - - -- The vendor ID string is returned in the ebx, ecx and edx register - -- after executing the CPUID instruction with eax set to zero. - -- In case of a true Intel processor the string returned is - -- "GenuineIntel" - - function Vendor_ID return String is - - Ebx, Ecx, Edx : Unsigned_Register; - -- registers containing the vendor ID string - - Vendor_ID : String (1 .. 12); - -- the vendor ID string - - begin - - -- execute CPUID, storing the results in the processor registers - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero stored in eax - -- vendor ID string returned in ebx, ecx and edx - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- ebx is stored in Ebx - -- ecx is stored in Ecx - -- edx is stored in Edx - Outputs => (Unsigned_Register'Asm_output ("=b", Ebx), - Unsigned_Register'Asm_output ("=c", Ecx), - Unsigned_Register'Asm_output ("=d", Edx))); - - -- now build the vendor ID string - Vendor_ID( 1) := Character'Val (Ebx.L1); - Vendor_ID( 2) := Character'Val (Ebx.H1); - Vendor_ID( 3) := Character'Val (Ebx.L2); - Vendor_ID( 4) := Character'Val (Ebx.H2); - Vendor_ID( 5) := Character'Val (Edx.L1); - Vendor_ID( 6) := Character'Val (Edx.H1); - Vendor_ID( 7) := Character'Val (Edx.L2); - Vendor_ID( 8) := Character'Val (Edx.H2); - Vendor_ID( 9) := Character'Val (Ecx.L1); - Vendor_ID(10) := Character'Val (Ecx.H1); - Vendor_ID(11) := Character'Val (Ecx.L2); - Vendor_ID(12) := Character'Val (Ecx.H2); - - -- return string - return Vendor_ID; - - end Vendor_ID; - - ------------------------------- - -- Get processor signature -- - ------------------------------- - - function Signature return Processor_Signature is - - Result : Processor_Signature; - -- processor signature returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one is stored in eax - -- processor signature returned in eax - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- eax is stored in Result - Outputs => Processor_Signature'Asm_output ("=a", Result), - - -- tell compiler that ebx, ecx and edx are also destroyed - Clobber => "ebx, ecx, edx"); - - -- return processor signature - return Result; - - end Signature; - - ------------------------------ - -- Get processor features -- - ------------------------------ - - function Features return Processor_Features is - - Result : Processor_Features; - -- processor features returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one stored in eax - -- processor features returned in edx - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- edx is stored in Result - Outputs => Processor_Features'Asm_output ("=d", Result), - - -- tell compiler that ebx and ecx are also destroyed - Clobber => "ebx, ecx"); - - -- return processor signature - return Result; - - end Features; - - end Intel_CPU; - @end smallexample - @c END OF INLINE ASSEMBLER CHAPTER - @c =============================== - - - - - @node Performance Considerations - @chapter Performance Considerations - @cindex Performance - - @noindent - The GNAT system provides a number of options that allow a trade-off - between - - @itemize @bullet - @item - performance of the generated code - - @item - speed of compilation - - @item - minimization of dependences and recompilation - - @item - the degree of run-time checking. - @end itemize - - @noindent - The defaults (if no options are selected) aim at improving the speed - of compilation and minimizing dependences, at the expense of performance - of the generated code: - - @itemize @bullet - @item - no optimization - - @item - no inlining of subprogram calls - - @item - all run-time checks enabled except overflow and elaboration checks - @end itemize - - @noindent - These options are suitable for most program development purposes. This - chapter describes how you can modify these choices, and also provides - some guidelines on debugging optimized code. - - @menu - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - @end menu - - @node Controlling Run-Time Checks - @section Controlling Run-Time Checks - - @noindent - By default, GNAT generates all run-time checks, except arithmetic overflow - checking for integer operations and checks for access before elaboration on - subprogram calls. The latter are not required in default mode, because all - necessary checking is done at compile time. - @cindex @option{-gnatp} (@code{gcc}) - @cindex @option{-gnato} (@code{gcc}) - Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to - be modified. @xref{Run-Time Checks}. - - Our experience is that the default is suitable for most development - purposes. - - We treat integer overflow specially because these - are quite expensive and in our experience are not as important as other - run-time checks in the development process. Note that division by zero - is not considered an overflow check, and divide by zero checks are - generated where required by default. - - Elaboration checks are off by default, and also not needed by default, since - GNAT uses a static elaboration analysis approach that avoids the need for - run-time checking. This manual contains a full chapter discussing the issue - of elaboration checks, and if the default is not satisfactory for your use, - you should read this chapter. - - For validity checks, the minimal checks required by the Ada Reference - Manual (for case statements and assignments to array elements) are on - by default. These can be suppressed by use of the @option{-gnatVn} switch. - Note that in Ada 83, there were no validity checks, so if the Ada 83 mode - is acceptable (or when comparing GNAT performance with an Ada 83 compiler), - it may be reasonable to routinely use @option{-gnatVn}. Validity checks - are also suppressed entirely if @option{-gnatp} is used. - - @cindex Overflow checks - @cindex Checks, overflow - @findex Suppress - @findex Unsuppress - @cindex pragma Suppress - @cindex pragma Unsuppress - Note that the setting of the switches controls the default setting of - the checks. They may be modified using either @code{pragma Suppress} (to - remove checks) or @code{pragma Unsuppress} (to add back suppressed - checks) in the program source. - - @node Optimization Levels - @section Optimization Levels - @cindex @code{-O} (@code{gcc}) - - @noindent - The default is optimization off. This results in the fastest compile - times, but GNAT makes absolutely no attempt to optimize, and the - generated programs are considerably larger and slower than when - optimization is enabled. You can use the - @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3, - on the @code{gcc} command line to control the optimization level: - - @table @code - @item -O0 - no optimization (the default) - - @item -O1 - medium level optimization - - @item -O2 - full optimization - - @item -O3 - full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - @end table - - Higher optimization levels perform more global transformations on the - program and apply more expensive analysis algorithms in order to generate - faster and more compact code. The price in compilation time, and the - resulting improvement in execution time, - both depend on the particular application and the hardware environment. - You should experiment to find the best level for your application. - - Note: Unlike some other compilation systems, @code{gcc} has - been tested extensively at all optimization levels. There are some bugs - which appear only with optimization turned on, but there have also been - bugs which show up only in @emph{unoptimized} code. Selecting a lower - level of optimization does not improve the reliability of the code - generator, which in practice is highly reliable at all optimization - levels. - - Note regarding the use of @code{-O3}: The use of this optimization level - is generally discouraged with GNAT, since it often results in larger - executables which run more slowly. See further discussion of this point - in @pxref{Inlining of Subprograms}. - - @node Debugging Optimized Code - @section Debugging Optimized Code - - @noindent - Since the compiler generates debugging tables for a compilation unit before - it performs optimizations, the optimizing transformations may invalidate some - of the debugging data. You therefore need to anticipate certain - anomalous situations that may arise while debugging optimized code. This - section describes the most common cases. - - @enumerate - @item - @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC - bouncing back and forth in the code. This may result from any of the following - optimizations: - - @itemize @bullet - @item - @i{Common subexpression elimination:} using a single instance of code for a - quantity that the source computes several times. As a result you - may not be able to stop on what looks like a statement. - - @item - @i{Invariant code motion:} moving an expression that does not change within a - loop, to the beginning of the loop. - - @item - @i{Instruction scheduling:} moving instructions so as to - overlap loads and stores (typically) with other code, or in - general to move computations of values closer to their uses. Often - this causes you to pass an assignment statement without the assignment - happening and then later bounce back to the statement when the - value is actually needed. Placing a breakpoint on a line of code - and then stepping over it may, therefore, not always cause all the - expected side-effects. - @end itemize - - @item - @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two - identical pieces of code are merged and the program counter suddenly - jumps to a statement that is not supposed to be executed, simply because - it (and the code following) translates to the same thing as the code - that @emph{was} supposed to be executed. This effect is typically seen in - sequences that end in a jump, such as a @code{goto}, a @code{return}, or - a @code{break} in a C @code{switch} statement. - - @item - @i{The "roving variable":} The symptom is an unexpected value in a variable. - There are various reasons for this effect: - - @itemize @bullet - @item - In a subprogram prologue, a parameter may not yet have been moved to its - "home". - - @item - A variable may be dead, and its register re-used. This is - probably the most common cause. - - @item - As mentioned above, the assignment of a value to a variable may - have been moved. - - @item - A variable may be eliminated entirely by value propagation or - other means. In this case, GCC may incorrectly generate debugging - information for the variable - @end itemize - - @noindent - In general, when an unexpected value appears for a local variable or parameter - you should first ascertain if that value was actually computed by - your program, as opposed to being incorrectly reported by the debugger. - Record fields or - array elements in an object designated by an access value - are generally less of a problem, once you have ascertained that the access value - is sensible. - Typically, this means checking variables in the preceding code and in the - calling subprogram to verify that the value observed is explainable from other - values (one must apply the procedure recursively to those - other values); or re-running the code and stopping a little earlier - (perhaps before the call) and stepping to better see how the variable obtained - the value in question; or continuing to step @emph{from} the point of the - strange value to see if code motion had simply moved the variable's - assignments later. - @end enumerate - - @node Inlining of Subprograms - @section Inlining of Subprograms - - @noindent - A call to a subprogram in the current unit is inlined if all the - following conditions are met: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else that @code{gcc} - cannot support in inlined subprograms. - - @item - The call occurs after the definition of the body of the subprogram. - - @item - @cindex pragma Inline - @findex Inline - Either @code{pragma Inline} applies to the subprogram or it is - small and automatic inlining (optimization level @code{-O3}) is - specified. - @end itemize - - @noindent - Calls to subprograms in @code{with}'ed units are normally not inlined. - To achieve this level of inlining, the following conditions must all be - true: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else @code{gcc} cannot - support in inlined subprograms. - - @item - The call appears in a body (not in a package spec). - - @item - There is a @code{pragma Inline} for the subprogram. - - @item - @cindex @option{-gnatn} (@code{gcc}) - The @code{-gnatn} switch - is used in the @code{gcc} command line - @end itemize - - Note that specifying the @option{-gnatn} switch causes additional - compilation dependencies. Consider the following: - - @smallexample - @group - @cartouche - @b{package} R @b{is} - @b{procedure} Q; - @b{pragma} Inline (Q); - @b{end} R; - @b{package body} R @b{is} - ... - @b{end} R; - - @b{with} R; - @b{procedure} Main @b{is} - @b{begin} - ... - R.Q; - @b{end} Main; - @end cartouche - @end group - @end smallexample - - @noindent - With the default behavior (no @option{-gnatn} switch specified), the - compilation of the @code{Main} procedure depends only on its own source, - @file{main.adb}, and the spec of the package in file @file{r.ads}. This - means that editing the body of @code{R} does not require recompiling - @code{Main}. - - On the other hand, the call @code{R.Q} is not inlined under these - circumstances. If the @option{-gnatn} switch is present when @code{Main} - is compiled, the call will be inlined if the body of @code{Q} is small - enough, but now @code{Main} depends on the body of @code{R} in - @file{r.adb} as well as on the spec. This means that if this body is edited, - the main program must be recompiled. Note that this extra dependency - occurs whether or not the call is in fact inlined by @code{gcc}. - - The use of front end inlining with @option{-gnatN} generates similar - additional dependencies. - - @cindex @code{-fno-inline} (@code{gcc}) - Note: The @code{-fno-inline} switch - can be used to prevent - all inlining. This switch overrides all other conditions and ensures - that no inlining occurs. The extra dependences resulting from - @option{-gnatn} will still be active, even if - this switch is used to suppress the resulting inlining actions. - - Note regarding the use of @code{-O3}: There is no difference in inlining - behavior between @code{-O2} and @code{-O3} for subprograms with an explicit - pragma @code{Inline} assuming the use of @option{-gnatn} - or @option{-gnatN} (the switches that activate inlining). If you have used - pragma @code{Inline} in appropriate cases, then it is usually much better - to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which - in this case only has the effect of inlining subprograms you did not - think should be inlined. We often find that the use of @code{-O3} slows - down code by performing excessive inlining, leading to increased instruction - cache pressure from the increased code size. So the bottom line here is - that you should not automatically assume that @code{-O3} is better than - @code{-O2}, and indeed you should use @code{-O3} only if tests show that - it actually improves performance. - - - @include fdl.texi - @c GNU Free Documentation License - - @node Index,,GNU Free Documentation License, Top - @unnumbered Index - - @printindex cp - - @contents - - @bye --- 0 ---- diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_ug_vms.texi gcc-3.4.1/gcc/ada/gnat_ug_vms.texi *** gcc-3.4.0/gcc/ada/gnat_ug_vms.texi 2004-03-20 15:33:53.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_ug_vms.texi 1970-01-01 00:00:00.000000000 +0000 *************** *** 1,19073 **** - \input texinfo @c -*-texinfo-*- - @c %**start of header - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c o - @c GNAT DOCUMENTATION o - @c o - @c G N A T _ U G o - @c o - @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. o - @c o - @c GNAT is free software; you can redistribute it and/or modify it under o - @c terms of the GNU General Public License as published by the Free Soft- o - @c ware Foundation; either version 2, or (at your option) any later ver- o - @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o - @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o - @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o - @c for more details. You should have received a copy of the GNU General o - @c Public License distributed with GNAT; see file COPYING. If not, write o - @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o - @c MA 02111-1307, USA. o - @c o - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c - @c GNAT_UG Style Guide - @c - @c 1. Always put a @noindent on the line before the first paragraph - @c after any of these commands: - @c - @c @chapter - @c @section - @c @subsection - @c @subsubsection - @c @subsubsubsection - @c - @c @end smallexample - @c @end itemize - @c @end enumerate - @c - @c 2. DO NOT use @example. Use @smallexample instead. - @c - @c 3. Each @chapter, @section, @subsection, @subsubsection, etc. - @c command must be preceded by two empty lines - @c - @c 4. The @item command must be on a line of its own if it is in an - @c @itemize or @enumerate command. - @c - @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" - @c or "ali". - @c - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @setfilename gnat_ug_vms.info - @settitle GNAT User's Guide for OpenVMS Alpha - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_vms). GNAT User's Guide for OpenVMS Alpha. - @end direntry - - - - - @include gcc-common.texi - - @setchapternewpage odd - @syncodeindex fn cp - @c %**end of header - - @copying - Copyright @copyright{} 1995-2003, Free Software Foundation - - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with the Invariant Sections being ``GNU Free Documentation License'', with the - Front-Cover Texts being - ``GNAT User's Guide for OpenVMS Alpha'', - and with no Back-Cover Texts. - A copy of the license is included in the section entitled ``GNU - Free Documentation License''. - @end copying - - @titlepage - - @title GNAT User's Guide - @center @titlefont{for OpenVMS Alpha} - - - - - @subtitle GNAT, The GNU Ada 95 Compiler - @subtitle GNAT Version for GCC @value{version-GCC} - - @author Ada Core Technologies, Inc. - - @page - @vskip 0pt plus 1filll - - @insertcopying - - @end titlepage - - @ifnottex - @node Top, About This Guide, (dir), (dir) - @top GNAT User's Guide - - GNAT User's Guide for OpenVMS Alpha - - - - - GNAT, The GNU Ada 95 Compiler - - GNAT Version for GCC @value{version-GCC} - - Ada Core Technologies, Inc. - - @insertcopying - - @menu - * About This Guide:: - * Getting Started with GNAT:: - * The GNAT Compilation Model:: - * Compiling Using GNAT COMPILE:: - * Binding Using GNAT BIND:: - * Linking Using GNAT LINK:: - * The GNAT Make Program GNAT MAKE:: - * Renaming Files Using GNAT CHOP:: - * Configuration Pragmas:: - * Handling Arbitrary File Naming Conventions Using gnatname:: - * GNAT Project Manager:: - * Elaboration Order Handling in GNAT:: - * The Cross-Referencing Tools GNAT XREF and GNAT FIND:: - * File Name Krunching Using GNAT KRUNCH:: - * Preprocessing Using GNAT PREPROCESS:: - * The GNAT Run-Time Library Builder GNAT LIBRARY:: - * The GNAT Library Browser GNAT LIST:: - * Finding Memory Problems with GNAT Debug Pool:: - * Creating Sample Bodies Using GNAT STUB:: - * Reducing the Size of Ada Executables with GNAT ELIM:: - * Other Utility Programs:: - * Compatibility with DEC Ada:: - * Running and Debugging Ada Programs:: - * Inline Assembler:: - * Performance Considerations:: - * GNU Free Documentation License:: - * Index:: - - --- The Detailed Node Listing --- - - About This Guide - - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - - - Getting Started with GNAT - - * Running GNAT:: - * Running a Simple Ada Program:: - * Running a Program with Multiple Units:: - * Using the GNAT MAKE Utility:: - * Editing with EMACS:: - - The GNAT Compilation Model - - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - - Foreign Language Representation - - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - - Compiling Ada Programs With GNAT COMPILE - - * Compiling Programs:: - * Qualifiers for GNAT COMPILE:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - - Qualifiers for GNAT COMPILE - - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using GNAT COMPILE for Syntax Checking:: - * Using GNAT COMPILE for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - - Binding Ada Programs With GNAT BIND - - * Running GNAT BIND:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Qualifiers:: - * Command-Line Access:: - * Search Paths for GNAT BIND:: - * Examples of GNAT BIND Usage:: - - Linking Using GNAT LINK - - * Running GNAT LINK:: - * Qualifiers for GNAT LINK:: - * Setting Stack Size from GNAT LINK:: - * Setting Heap Size from GNAT LINK:: - - The GNAT Make Program GNAT MAKE - - * Running GNAT MAKE:: - * Qualifiers for GNAT MAKE:: - * Mode Qualifiers for GNAT MAKE:: - * Notes on the Command Line:: - * How GNAT MAKE Works:: - * Examples of GNAT MAKE Usage:: - - Renaming Files Using GNAT CHOP - - * Handling Files with Multiple Units:: - * Operating GNAT CHOP in Compilation Mode:: - * Command Line for GNAT CHOP:: - * Qualifiers for GNAT CHOP:: - * Examples of GNAT CHOP Usage:: - - Configuration Pragmas - - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - - Handling Arbitrary File Naming Conventions Using gnatname - - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Qualifiers for gnatname:: - * Examples of gnatname Usage:: - - GNAT Project Manager - - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Qualifiers Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - - Elaboration Order Handling in GNAT - - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - - The Cross-Referencing Tools GNAT XREF and GNAT FIND - - * GNAT XREF Qualifiers:: - * GNAT FIND Qualifiers:: - * Project Files for GNAT XREF and GNAT FIND:: - * Regular Expressions in GNAT FIND and GNAT XREF:: - * Examples of GNAT XREF Usage:: - * Examples of GNAT FIND Usage:: - - File Name Krunching Using GNAT KRUNCH - - * About GNAT KRUNCH:: - * Using GNAT KRUNCH:: - * Krunching Method:: - * Examples of GNAT KRUNCH Usage:: - - Preprocessing Using GNAT PREPROCESS - - * Using GNAT PREPROCESS:: - * Qualifiers for GNAT PREPROCESS:: - * Form of Definitions File:: - * Form of Input Text for GNAT PREPROCESS:: - - The GNAT Run-Time Library Builder GNAT LIBRARY - - * Running GNAT LIBRARY:: - * Qualifiers for GNAT LIBRARY:: - * Examples of GNAT LIBRARY Usage:: - - The GNAT Library Browser GNAT LIST - - * Running GNAT LIST:: - * Qualifiers for GNAT LIST:: - * Examples of GNAT LIST Usage:: - - - Finding Memory Problems with GNAT Debug Pool - - Creating Sample Bodies Using GNAT STUB - - * Running GNAT STUB:: - * Qualifiers for GNAT STUB:: - - Reducing the Size of Ada Executables with GNAT ELIM - - * About GNAT ELIM:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for GNAT ELIM:: - * Running GNAT ELIM:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the GNAT ELIM Usage Cycle:: - - Other Utility Programs - - * Using Other Utility Programs with GNAT:: - * The GNAT STANDARD Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - * LSE:: - - Compatibility with DEC Ada - - * Ada 95 Compatibility:: - * Differences in the Definition of Package System:: - * Language-Related Features:: - * The Package STANDARD:: - * The Package SYSTEM:: - * Tasking and Task-Related Features:: - * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems:: - * Pragmas and Pragma-Related Features:: - * Library of Predefined Units:: - * Bindings:: - * Main Program Definition:: - * Implementation-Defined Attributes:: - * Compiler and Run-Time Interfacing:: - * Program Compilation and Library Management:: - * Input-Output:: - * Implementation Limits:: - * Tools:: - - Language-Related Features - - * Integer Types and Representations:: - * Floating-Point Types and Representations:: - * Pragmas Float_Representation and Long_Float:: - * Fixed-Point Types and Representations:: - * Record and Array Component Alignment:: - * Address Clauses:: - * Other Representation Clauses:: - - Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems - - * Assigning Task IDs:: - * Task IDs and Delays:: - * Task-Related Pragmas:: - * Scheduling and Task Priority:: - * The Task Stack:: - * External Interrupts:: - - Pragmas and Pragma-Related Features - - * Restrictions on the Pragma INLINE:: - * Restrictions on the Pragma INTERFACE:: - * Restrictions on the Pragma SYSTEM_NAME:: - - Library of Predefined Units - - * Changes to DECLIB:: - - Bindings - - * Shared Libraries and Options Files:: - * Interfaces to C:: - - Running and Debugging Ada Programs - - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - - Inline Assembler - - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - - - - Performance Considerations - - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - * Coverage Analysis:: - - * Index:: - @end menu - @end ifnottex - - @node About This Guide - @unnumbered About This Guide - - @noindent - This guide describes the use of of GNAT, a full language compiler for the Ada - 95 programming language, implemented on DIGITAL OpenVMS Alpha Systems. - It describes the features of the compiler and tools, and details - how to use them to build Ada 95 applications. - - @menu - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - @end menu - - @node What This Guide Contains - @unnumberedsec What This Guide Contains - - @noindent - This guide contains the following chapters: - @itemize @bullet - @item - @ref{Getting Started with GNAT}, describes how to get started compiling - and running Ada programs with the GNAT Ada programming environment. - @item - @ref{The GNAT Compilation Model}, describes the compilation model used - by GNAT. - @item - @ref{Compiling Using GNAT COMPILE}, describes how to compile - Ada programs with @code{GNAT COMPILE}, the Ada compiler. - @item - @ref{Binding Using GNAT BIND}, describes how to - perform binding of Ada programs with @code{GNAT BIND}, the GNAT binding - utility. - @item - @ref{Linking Using GNAT LINK}, - describes @code{GNAT LINK}, a - program that provides for linking using the GNAT run-time library to - construct a program. @code{GNAT LINK} can also incorporate foreign language - object units into the executable. - @item - @ref{The GNAT Make Program GNAT MAKE}, describes @code{GNAT MAKE}, a - utility that automatically determines the set of sources - needed by an Ada compilation unit, and executes the necessary compilations - binding and link. - @item - @ref{Renaming Files Using GNAT CHOP}, describes - @code{GNAT CHOP}, a utility that allows you to preprocess a file that - contains Ada source code, and split it into one or more new files, one - for each compilation unit. - @item - @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT. - @item - @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override - the default GNAT file naming conventions, either for an individual unit or globally. - @item - @ref{GNAT Project Manager}, describes how to use project files to organize large projects. - @item - @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with - elaboration order issues. - @item - @ref{The Cross-Referencing Tools GNAT XREF and GNAT FIND}, discusses - @code{GNAT XREF} and @code{GNAT FIND}, two tools that provide an easy - way to navigate through sources. - @item - @ref{File Name Krunching Using GNAT KRUNCH}, describes the @code{GNAT KRUNCH} - file name krunching utility, used to handle shortened - file names on operating systems with a limit on the length of names. - @item - @ref{Preprocessing Using GNAT PREPROCESS}, describes @code{GNAT PREPROCESS}, a - preprocessor utility that allows a single source file to be used to - generate multiple or parameterized source files, by means of macro - substitution. - @item - @ref{The GNAT Library Browser GNAT LIST}, describes @code{GNAT LIST}, a - utility that displays information about compiled units, including dependences - on the corresponding sources files, and consistency of compilations. - @item - @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to - use the GNAT-specific Debug Pool in order to detect as early as possible - the use of incorrect memory references. - - @item - @ref{Creating Sample Bodies Using GNAT STUB}, discusses @code{GNAT STUB}, - a utility that generates empty but compilable bodies for library units. - - @item - @ref{Reducing the Size of Ada Executables with GNAT ELIM}, describes - @code{GNAT ELIM}, a tool which detects unused subprograms and helps - the compiler to create a smaller executable for the program. - - @item - @ref{Other Utility Programs}, discusses several other GNAT utilities, - including @code{GNAT STANDARD}. - - @item - @ref{Running and Debugging Ada Programs}, describes how to run and debug - Ada programs. - - @item - @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program. - - - @item - @ref{Performance Considerations}, reviews the trade offs between using - defaults or options in program development. - @item - @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with - DEC Ada 83 for OpenVMS Alpha. - @end itemize - - @node What You Should Know before Reading This Guide - @unnumberedsec What You Should Know before Reading This Guide - - @cindex Ada 95 Language Reference Manual - @noindent - This user's guide assumes that you are familiar with Ada 95 language, as - described in the International Standard ANSI/ISO/IEC-8652:1995, Jan - 1995. - - @node Related Information - @unnumberedsec Related Information - - @noindent - For further information about related tools, refer to the following - documents: - - @itemize @bullet - @item - @cite{GNAT Reference Manual}, which contains all reference - material for the GNAT implementation of Ada 95. - - @item - @cite{Ada 95 Language Reference Manual}, which contains all reference - material for the Ada 95 programming language. - - @item - @cite{Debugging with GDB} - , located in the GNU:[DOCS] directory, - contains all details on the use of the GNU source-level debugger. - - @item - @cite{GNU EMACS Manual} - , located in the GNU:[DOCS] directory if the EMACS kit is installed, - contains full information on the extensible editor and programming - environment EMACS. - - @end itemize - - @node Conventions - @unnumberedsec Conventions - @cindex Conventions - @cindex Typographical conventions - - @noindent - Following are examples of the typographical and graphic conventions used - in this guide: - - @itemize @bullet - @item - @code{Functions}, @code{utility program names}, @code{standard names}, - and @code{classes}. - - @item - @samp{Option flags} - - @item - @file{File Names}, @file{button names}, and @file{field names}. - - @item - @var{Variables}. - - @item - @emph{Emphasis}. - - @item - [optional information or parameters] - - @item - Examples are described by text - @smallexample - and then shown this way. - @end smallexample - @end itemize - - @noindent - Commands that are entered by the user are preceded in this manual by the - characters @w{"@code{$ }"} (dollar sign followed by space). If your system - uses this sequence as a prompt, then the commands will appear exactly as - you see them in the manual. If your system uses some other prompt, then - the command will appear with the @code{$} replaced by whatever prompt - character you are using. - - - @node Getting Started with GNAT - @chapter Getting Started with GNAT - - @noindent - This chapter describes some simple ways of using GNAT to build - executable Ada programs. - - @menu - * Running GNAT:: - * Running a Simple Ada Program:: - - * Running a Program with Multiple Units:: - - * Using the GNAT MAKE Utility:: - * Editing with EMACS:: - @end menu - - @node Running GNAT - @section Running GNAT - - @noindent - Three steps are needed to create an executable file from an Ada source - file: - - @enumerate - @item - The source file(s) must be compiled. - @item - The file(s) must be bound using the GNAT binder. - @item - All appropriate object files must be linked to produce an executable. - @end enumerate - - @noindent - All three steps are most commonly handled by using the @code{GNAT MAKE} - utility program that, given the name of the main program, automatically - performs the necessary compilation, binding and linking steps. - - @node Running a Simple Ada Program - @section Running a Simple Ada Program - - @noindent - Any text editor may be used to prepare an Ada program. If @code{Glide} is - used, the optional Ada mode may be helpful in laying out the program. The - program text is a normal text file. We will suppose in our initial - example that you have used your editor to prepare the following - standard format text file: - - @smallexample - @group - @cartouche - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - @end cartouche - @end group - @end smallexample - - @noindent - This file should be named @file{HELLO.ADB}. - With the normal default file naming conventions, GNAT requires - that each file - contain a single compilation unit whose file name is the - unit name, - with periods replaced by hyphens; the - extension is @file{ads} for a - spec and @file{adb} for a body. - You can override this default file naming convention by use of the - special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). - Alternatively, if you want to rename your files according to this default - convention, which is probably more convenient if you will be using GNAT - for all your compilations, then the @code{GNAT CHOP} utility - can be used to generate correctly-named source files - (@pxref{Renaming Files Using GNAT CHOP}). - - You can compile the program using the following command (@code{$} is used - as the command prompt in the examples in this document): - - @smallexample - $ GNAT COMPILE HELLO.ADB - @end smallexample - - - @noindent - @code{GNAT COMPILE} is the command used to run the compiler. This compiler is - capable of compiling programs in several languages, including Ada 95 and - C. It assumes that you have given it an Ada program if the file extension is - either @file{.ADS} or @file{.ADB}, and it will then call the GNAT compiler to compile - the specified file. - - - This compile command generates a file - @file{HELLO.OBJ}, which is the object - file corresponding to your Ada program. It also generates an "Ada Library Information" file - @file{HELLO.ALI}, - which contains additional information used to check - that an Ada program is consistent. - To build an executable file, - use @code{GNAT BIND} to bind the program - and @code{GNAT LINK} to link it. The - argument to both @code{GNAT BIND} and @code{GNAT LINK} is the name of the - @file{ali} file, but the default extension of @file{.ALI} can - be omitted. This means that in the most common case, the argument - is simply the name of the main program: - - @smallexample - $ GNAT BIND hello - $ GNAT LINK hello - @end smallexample - - - @noindent - A simpler method of carrying out these steps is to use - @command{GNAT MAKE}, - a master program that invokes all the required - compilation, binding and linking tools in the correct order. In particular, - @command{GNAT MAKE} automatically recompiles any sources that have been modified - since they were last compiled, or sources that depend - on such modified sources, so that "version skew" is avoided. - @cindex Version skew (avoided by @command{GNAT MAKE}) - - @smallexample - $ GNAT MAKE HELLO.ADB - @end smallexample - - - @noindent - The result is an executable program called @file{hello}, which can be - run by entering: - - @c The following should be removed (BMB 2001-01-23) - @c @smallexample - @c $ $ RUN HELLO - @c @end smallexample - - @smallexample - $ hello - @end smallexample - - @noindent - assuming that the current directory is on the search path for executable programs. - - @noindent - and, if all has gone well, you will see - - @smallexample - Hello WORLD! - @end smallexample - - @noindent - appear in response to this command. - - - - - @node Running a Program with Multiple Units - @section Running a Program with Multiple Units - - @noindent - Consider a slightly more complicated example that has three files: a - main program, and the spec and body of a package: - - @smallexample - @cartouche - @group - @b{package} Greetings @b{is} - @b{procedure} Hello; - @b{procedure} Goodbye; - @b{end} Greetings; - - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{package} @b{body} Greetings @b{is} - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - - @b{procedure} Goodbye @b{is} - @b{begin} - Put_Line ("Goodbye WORLD!"); - @b{end} Goodbye; - @b{end} Greetings; - @end group - - @group - @b{with} Greetings; - @b{procedure} Gmain @b{is} - @b{begin} - Greetings.Hello; - Greetings.Goodbye; - @b{end} Gmain; - @end group - @end cartouche - @end smallexample - - @noindent - Following the one-unit-per-file rule, place this program in the - following three separate files: - - @table @file - @item GREETINGS.ADS - spec of package @code{Greetings} - - @item GREETINGS.ADB - body of package @code{Greetings} - - @item GMAIN.ADB - body of main program - @end table - - @noindent - To build an executable version of - this program, we could use four separate steps to compile, bind, and link - the program, as follows: - - @smallexample - $ GNAT COMPILE GMAIN.ADB - $ GNAT COMPILE GREETINGS.ADB - $ GNAT BIND gmain - $ GNAT LINK gmain - @end smallexample - - - @noindent - Note that there is no required order of compilation when using GNAT. - In particular it is perfectly fine to compile the main program first. - Also, it is not necessary to compile package specs in the case where - there is an accompanying body; you only need to compile the body. If you want - to submit these files to the compiler for semantic checking and not code generation, - then use the - @option{/NOLOAD} qualifier: - - @smallexample - $ GNAT COMPILE GREETINGS.ADS /NOLOAD - @end smallexample - - - @noindent - Although the compilation can be done in separate steps as in the - above example, in practice it is almost always more convenient - to use the @code{GNAT MAKE} tool. All you need to know in this case - is the name of the main program's source file. The effect of the above four - commands can be achieved with a single one: - - @smallexample - $ GNAT MAKE GMAIN.ADB - @end smallexample - - - @noindent - In the next section we discuss the advantages of using @code{GNAT MAKE} in - more detail. - - @node Using the GNAT MAKE Utility - @section Using the @command{GNAT MAKE} Utility - - @noindent - If you work on a program by compiling single components at a time using - @code{GNAT COMPILE}, you typically keep track of the units you modify. In order to - build a consistent system, you compile not only these units, but also any - units that depend on the units you have modified. - For example, in the preceding case, - if you edit @file{GMAIN.ADB}, you only need to recompile that file. But if - you edit @file{GREETINGS.ADS}, you must recompile both - @file{GREETINGS.ADB} and @file{GMAIN.ADB}, because both files contain - units that depend on @file{GREETINGS.ADS}. - - @code{GNAT BIND} will warn you if you forget one of these compilation - steps, so that it is impossible to generate an inconsistent program as a - result of forgetting to do a compilation. Nevertheless it is tedious and - error-prone to keep track of dependencies among units. - One approach to handle the dependency-bookkeeping is to use a - makefile. However, makefiles present maintenance problems of their own: - if the dependencies change as you change the program, you must make - sure that the makefile is kept up-to-date manually, which is also an - error-prone process. - - The @code{GNAT MAKE} utility takes care of these details automatically. - Invoke it using either one of the following forms: - - @smallexample - $ GNAT MAKE GMAIN.ADB - $ GNAT MAKE GMAIN - @end smallexample - - - @noindent - The argument is the name of the file containing the main program; - you may omit the extension. @code{GNAT MAKE} - examines the environment, automatically recompiles any files that need - recompiling, and binds and links the resulting set of object files, - generating the executable file, @file{GMAIN.EXE}. - In a large program, it - can be extremely helpful to use @code{GNAT MAKE}, because working out by hand - what needs to be recompiled can be difficult. - - Note that @code{GNAT MAKE} - takes into account all the Ada 95 rules that - establish dependencies among units. These include dependencies that result - from inlining subprogram bodies, and from - generic instantiation. Unlike some other - Ada make tools, @code{GNAT MAKE} does not rely on the dependencies that were - found by the compiler on a previous compilation, which may possibly - be wrong when sources change. @code{GNAT MAKE} determines the exact set of - dependencies from scratch each time it is run. - - @node Editing with EMACS - @section Editing with EMACS - @cindex EMACS - - @noindent - EMACS is an extensible self-documenting text editor that is available in a - separate VMSINSTAL kit. - - Invoke EMACS by typing "EMACS" at the command prompt. To get started, - click on the EMACS Help menu and run the EMACS Tutorial. - In a character cell terminal, EMACS help is invoked with "Ctrl-h" (also written - as "C-h"), and the tutorial by "C-h t". - - Documentation on EMACS and other tools is available in EMACS under the - pull-down menu button: Help - Info. After selecting Info, use the middle - mouse button to select a topic (e.g. EMACS). - - In a character cell terminal, do "C-h i" to invoke info, and then "m" - (stands for menu) followed by the menu item desired, as in "m EMACS", to get - to the EMACS manual. - Help on EMACS is also available by typing "HELP EMACS" at the DCL command - prompt. - - The tutorial is highly recommended in order to learn the intricacies of EMACS, - which is sufficiently extensible to provide for a complete programming - environment and shell for the sophisticated user. - - - @node The GNAT Compilation Model - @chapter The GNAT Compilation Model - @cindex GNAT compilation model - @cindex Compilation model - - @menu - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - @end menu - - @noindent - This chapter describes the compilation model used by GNAT. Although - similar to that used by other languages, such as C and C++, this model - is substantially different from the traditional Ada compilation models, - which are based on a library. The model is initially described without - reference to the library-based model. If you have not previously used an - Ada compiler, you need only read the first part of this chapter. The - last section describes and discusses the differences between the GNAT - model and the traditional Ada compiler models. If you have used other - Ada compilers, this section will help you to understand those - differences, and the advantages of the GNAT model. - - @node Source Representation - @section Source Representation - @cindex Latin-1 - - @noindent - Ada source programs are represented in standard text files, using - Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar - 7-bit ASCII set, plus additional characters used for - representing foreign languages (@pxref{Foreign Language Representation} - for support of non-USA character sets). The format effector characters - are represented using their standard ASCII encodings, as follows: - - @table @code - @item VT - @findex VT - Vertical tab, @code{16#0B#} - - @item HT - @findex HT - Horizontal tab, @code{16#09#} - - @item CR - @findex CR - Carriage return, @code{16#0D#} - - @item LF - @findex LF - Line feed, @code{16#0A#} - - @item FF - @findex FF - Form feed, @code{16#0C#} - @end table - - @noindent - Source files are in standard text file format. In addition, GNAT will - recognize a wide variety of stream formats, in which the end of physical - physical lines is marked by any of the following sequences: - @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful - in accommodating files that are imported from other operating systems. - - @cindex End of source file - @cindex Source file, end - @findex SUB - The end of a source file is normally represented by the physical end of - file. However, the control character @code{16#1A#} (@code{SUB}) is also - recognized as signalling the end of the source file. Again, this is - provided for compatibility with other operating systems where this - code is used to represent the end of file. - - Each file contains a single Ada compilation unit, including any pragmas - associated with the unit. For example, this means you must place a - package declaration (a package @dfn{spec}) and the corresponding body in - separate files. An Ada @dfn{compilation} (which is a sequence of - compilation units) is represented using a sequence of files. Similarly, - you will place each subunit or child unit in a separate file. - - @node Foreign Language Representation - @section Foreign Language Representation - - @noindent - GNAT supports the standard character sets defined in Ada 95 as well as - several other non-standard character sets for use in localized versions - of the compiler (@pxref{Character Set Control}). - @menu - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - @end menu - - @node Latin-1 - @subsection Latin-1 - @cindex Latin-1 - - @noindent - The basic character set is Latin-1. This character set is defined by ISO - standard 8859, part 1. The lower half (character codes @code{16#00#} - ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is - used to represent additional characters. These include extended letters - used by European languages, such as French accents, the vowels with umlauts - used in German, and the extra letter A-ring used in Swedish. - - @findex Ada.Characters.Latin_1 - For a complete list of Latin-1 codes and their encodings, see the source - file of library unit @code{Ada.Characters.Latin_1} in file - @file{A-CHLAT1.ADS}. - You may use any of these extended characters freely in character or - string literals. In addition, the extended characters that represent - letters can be used in identifiers. - - @node Other 8-Bit Codes - @subsection Other 8-Bit Codes - - @noindent - GNAT also supports several other 8-bit coding schemes: - - @table @asis - @cindex Latin-2 - @item Latin-2 - Latin-2 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-3 - @cindex Latin-3 - Latin-3 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-4 - @cindex Latin-4 - Latin-4 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-5 - @cindex Latin-5 - @cindex Cyrillic - Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase - equivalence. - - @item IBM PC (code page 437) - @cindex code page 437 - This code page is the normal default for PCs in the U.S. It corresponds - to the original IBM PC character set. This set has some, but not all, of - the extended Latin-1 letters, but these letters do not have the same - encoding as Latin-1. In this mode, these letters are allowed in - identifiers with uppercase and lowercase equivalence. - - @item IBM PC (code page 850) - @cindex code page 850 - This code page is a modification of 437 extended to include all the - Latin-1 letters, but still not with the usual Latin-1 encoding. In this - mode, all these letters are allowed in identifiers with uppercase and - lowercase equivalence. - - @item Full Upper 8-bit - Any character in the range 80-FF allowed in identifiers, and all are - considered distinct. In other words, there are no uppercase and lowercase - equivalences in this range. This is useful in conjunction with - certain encoding schemes used for some foreign character sets (e.g. - the typical method of representing Chinese characters on the PC). - - @item No Upper-Half - No upper-half characters in the range 80-FF are allowed in identifiers. - This gives Ada 83 compatibility for identifier names. - @end table - - @noindent - For precise data on the encodings permitted, and the uppercase and lowercase - equivalences that are recognized, see the file @file{CSETS.ADB} in - the GNAT compiler sources. You will need to obtain a full source release - of GNAT to obtain this file. - - @node Wide Character Encodings - @subsection Wide Character Encodings - - @noindent - GNAT allows wide character codes to appear in character and string - literals, and also optionally in identifiers, by means of the following - possible encoding schemes: - - @table @asis - - @item Hex Coding - In this encoding, a wide character is represented by the following five - character sequence: - - @smallexample - ESC a b c d - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ESC A345 is used to represent the wide character with code - @code{16#A345#}. - This scheme is compatible with use of the full Wide_Character set. - - @item Upper-Half Coding - @cindex Upper-Half Coding - The wide character with encoding @code{16#abcd#} where the upper bit is on (in - other words, "a" is in the range 8-F) is represented as two bytes, - @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control - character, but is not required to be in the upper half. This method can - be also used for shift-JIS or EUC, where the internal coding matches the - external coding. - - @item Shift JIS Coding - @cindex Shift JIS Coding - A wide character is represented by a two-character sequence, - @code{16#ab#} and - @code{16#cd#}, with the restrictions described for upper-half encoding as - described above. The internal character code is the corresponding JIS - character according to the standard algorithm for Shift-JIS - conversion. Only characters defined in the JIS code set table can be - used with this encoding method. - - @item EUC Coding - @cindex EUC Coding - A wide character is represented by a two-character sequence - @code{16#ab#} and - @code{16#cd#}, with both characters being in the upper half. The internal - character code is the corresponding JIS character according to the EUC - encoding algorithm. Only characters defined in the JIS code set table - can be used with this encoding method. - - @item UTF-8 Coding - A wide character is represented using - UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO - 10646-1/Am.2. Depending on the character value, the representation - is a one, two, or three byte sequence: - @smallexample - @iftex - @leftskip=.7cm - @end iftex - 16#0000#-16#007f#: 2#0xxxxxxx# - 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# - 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# - - @end smallexample - - @noindent - where the xxx bits correspond to the left-padded bits of the - 16-bit character value. Note that all lower half ASCII characters - are represented as ASCII bytes and all upper half characters and - other wide characters are represented as sequences of upper-half - (The full UTF-8 scheme allows for encoding 31-bit characters as - 6-byte sequences, but in this implementation, all UTF-8 sequences - of four or more bytes length will be treated as illegal). - @item Brackets Coding - In this encoding, a wide character is represented by the following eight - character sequence: - - @smallexample - [ " a b c d " ] - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ["A345"] is used to represent the wide character with code - @code{16#A345#}. It is also possible (though not required) to use the - Brackets coding for upper half characters. For example, the code - @code{16#A3#} can be represented as @code{["A3"]}. - - This scheme is compatible with use of the full Wide_Character set, - and is also the method used for wide character encoding in the standard - ACVC (Ada Compiler Validation Capability) test suite distributions. - - @end table - - @noindent - Note: Some of these coding schemes do not permit the full use of the - Ada 95 character set. For example, neither Shift JIS, nor EUC allow the - use of the upper half of the Latin-1 set. - - @node File Naming Rules - @section File Naming Rules - - @noindent - The default file name is determined by the name of the unit that the - file contains. The name is formed by taking the full expanded name of - the unit and replacing the separating dots with hyphens and using - uppercase for all letters. - - An exception arises if the file name generated by the above rules starts - with one of the characters - A,G,I, or S, - and the second character is a - minus. In this case, the character dollar sign is used in place - of the minus. The reason for this special rule is to avoid clashes with - the standard names for child units of the packages System, Ada, - Interfaces, and GNAT, which use the prefixes - S- A- I- and G- - respectively. - - The file extension is @file{.ADS} for a spec and - @file{.ADB} for a body. The following list shows some - examples of these rules. - - @table @file - @item MAIN.ADS - Main (spec) - @item MAIN.ADB - Main (body) - @item ARITH_FUNCTIONS.ADS - Arith_Functions (package spec) - @item ARITH_FUNCTIONS.ADB - Arith_Functions (package body) - @item FUNC-SPEC.ADS - Func.Spec (child package spec) - @item FUNC-SPEC.ADB - Func.Spec (child package body) - @item MAIN-SUB.ADB - Sub (subunit of Main) - @item A$BAD.ADB - A.Bad (child package body) - @end table - - @noindent - Following these rules can result in excessively long - file names if corresponding - unit names are long (for example, if child units or subunits are - heavily nested). An option is available to shorten such long file names - (called file name "krunching"). This may be particularly useful when - programs being developed with GNAT are to be used on operating systems - with limited file name lengths. @xref{Using GNAT KRUNCH}. - - Of course, no file shortening algorithm can guarantee uniqueness over - all possible unit names; if file name krunching is used, it is your - responsibility to ensure no name clashes occur. Alternatively you - can specify the exact file names that you want used, as described - in the next section. Finally, if your Ada programs are migrating from a - compiler with a different naming convention, you can use the GNAT CHOP - utility to produce source files that follow the GNAT naming conventions. - (For details @pxref{Renaming Files Using GNAT CHOP}.) - - @node Using Other File Names - @section Using Other File Names - @cindex File names - - @noindent - In the previous section, we have described the default rules used by - GNAT to determine the file name in which a given unit resides. It is - often convenient to follow these default rules, and if you follow them, - the compiler knows without being explicitly told where to find all - the files it needs. - - However, in some cases, particularly when a program is imported from - another Ada compiler environment, it may be more convenient for the - programmer to specify which file names contain which units. GNAT allows - arbitrary file names to be used by means of the Source_File_Name pragma. - The form of this pragma is as shown in the following examples: - @cindex Source_File_Name pragma - - @smallexample - @group - @cartouche - @b{pragma} Source_File_Name (My_Utilities.Stacks, - Spec_File_Name => "MYUTILST_A.ADA"); - @b{pragma} Source_File_name (My_Utilities.Stacks, - Body_File_Name => "MYUTILST.ADA"); - @end cartouche - @end group - @end smallexample - - @noindent - As shown in this example, the first argument for the pragma is the unit - name (in this example a child unit). The second argument has the form - of a named association. The identifier - indicates whether the file name is for a spec or a body; - the file name itself is given by a string literal. - - The source file name pragma is a configuration pragma, which means that - normally it will be placed in the @file{GNAT.ADC} - file used to hold configuration - pragmas that apply to a complete compilation environment. - For more details on how the @file{GNAT.ADC} file is created and used - @pxref{Handling of Configuration Pragmas} - @cindex @file{GNAT.ADC} - - - @noindent - @code{GNAT MAKE} handles non-standard file names in the usual manner (the - non-standard file name for the main program is simply used as the - argument to GNAT MAKE). Note that if the extension is also non-standard, - then it must be included in the GNAT MAKE command, it may not be omitted. - - @node Alternative File Naming Schemes - @section Alternative File Naming Schemes - @cindex File naming schemes, alternative - @cindex File names - - In the previous section, we described the use of the @code{Source_File_Name} - pragma to allow arbitrary names to be assigned to individual source files. - However, this approach requires one pragma for each file, and especially in - large systems can result in very long @file{GNAT.ADC} files, and also create - a maintenance problem. - - GNAT also provides a facility for specifying systematic file naming schemes - other than the standard default naming scheme previously described. An - alternative scheme for naming is specified by the use of - @code{Source_File_Name} pragmas having the following format: - @cindex Source_File_Name pragma - - @smallexample - pragma Source_File_Name ( - Spec_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Body_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Subunit_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - FILE_NAME_PATTERN ::= STRING_LITERAL - CASING_SPEC ::= Lowercase | Uppercase | Mixedcase - - @end smallexample - - @noindent - The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. - It contains a single asterisk character, and the unit name is substituted - systematically for this asterisk. The optional parameter - @code{Casing} indicates - whether the unit name is to be all upper-case letters, all lower-case letters, - or mixed-case. If no - @code{Casing} parameter is used, then the default is all - upper-case. - - The optional @code{Dot_Replacement} string is used to replace any periods - that occur in subunit or child unit names. If no @code{Dot_Replacement} - argument is used then separating dots appear unchanged in the resulting - file name. - Although the above syntax indicates that the - @code{Casing} argument must appear - before the @code{Dot_Replacement} argument, but it - is also permissible to write these arguments in the opposite order. - - As indicated, it is possible to specify different naming schemes for - bodies, specs, and subunits. Quite often the rule for subunits is the - same as the rule for bodies, in which case, there is no need to give - a separate @code{Subunit_File_Name} rule, and in this case the - @code{Body_File_name} rule is used for subunits as well. - - The separate rule for subunits can also be used to implement the rather - unusual case of a compilation environment (e.g. a single directory) which - contains a subunit and a child unit with the same unit name. Although - both units cannot appear in the same partition, the Ada Reference Manual - allows (but does not require) the possibility of the two units coexisting - in the same environment. - - The file name translation works in the following steps: - - @itemize @bullet - - @item - If there is a specific @code{Source_File_Name} pragma for the given unit, - then this is always used, and any general pattern rules are ignored. - - @item - If there is a pattern type @code{Source_File_Name} pragma that applies to - the unit, then the resulting file name will be used if the file exists. If - more than one pattern matches, the latest one will be tried first, and the - first attempt resulting in a reference to a file that exists will be used. - - @item - If no pattern type @code{Source_File_Name} pragma that applies to the unit - for which the corresponding file exists, then the standard GNAT default - naming rules are used. - - @end itemize - - @noindent - As an example of the use of this mechanism, consider a commonly used scheme - in which file names are all lower case, with separating periods copied - unchanged to the resulting file name, and specs end with ".1.ADA", and - bodies end with ".2.ADA". GNAT will follow this scheme if the following - two pragmas appear: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.1.ADA"); - pragma Source_File_Name - (Body_File_Name => "*.2.ADA"); - @end smallexample - - @noindent - The default GNAT scheme is actually implemented by providing the following - default pragmas internally: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.ADS", Dot_Replacement => "-"); - pragma Source_File_Name - (Body_File_Name => "*.ADB", Dot_Replacement => "-"); - @end smallexample - - @noindent - Our final example implements a scheme typically used with one of the - Ada 83 compilers, where the separator character for subunits was "__" - (two underscores), specs were identified by adding @file{_.ADA}, bodies - by adding @file{.ADA}, and subunits by - adding @file{.SEP}. All file names were - upper case. Child units were not present of course since this was an - Ada 83 compiler, but it seems reasonable to extend this scheme to use - the same double underscore separator for child units. - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*_.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Body_File_Name => "*.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Subunit_File_Name => "*.SEP", - Dot_Replacement => "__", - Casing = Uppercase); - @end smallexample - - @node Generating Object Files - @section Generating Object Files - - @noindent - An Ada program consists of a set of source files, and the first step in - compiling the program is to generate the corresponding object files. - These are generated by compiling a subset of these source files. - The files you need to compile are the following: - - @itemize @bullet - @item - If a package spec has no body, compile the package spec to produce the - object file for the package. - - @item - If a package has both a spec and a body, compile the body to produce the - object file for the package. The source file for the package spec need - not be compiled in this case because there is only one object file, which - contains the code for both the spec and body of the package. - - @item - For a subprogram, compile the subprogram body to produce the object file - for the subprogram. The spec, if one is present, is as usual in a - separate file, and need not be compiled. - - @item - @cindex Subunits - In the case of subunits, only compile the parent unit. A single object - file is generated for the entire subunit tree, which includes all the - subunits. - - @item - Compile child units independently of their parent units - (though, of course, the spec of all the ancestor unit must be present in order - to compile a child unit). - - @item - @cindex Generics - Compile generic units in the same manner as any other units. The object - files in this case are small dummy files that contain at most the - flag used for elaboration checking. This is because GNAT always handles generic - instantiation by means of macro expansion. However, it is still necessary to - compile generic units, for dependency checking and elaboration purposes. - @end itemize - - @noindent - The preceding rules describe the set of files that must be compiled to - generate the object files for a program. Each object file has the same - name as the corresponding source file, except that the extension is - @file{.OBJ} as usual. - - You may wish to compile other files for the purpose of checking their - syntactic and semantic correctness. For example, in the case where a - package has a separate spec and body, you would not normally compile the - spec. However, it is convenient in practice to compile the spec to make - sure it is error-free before compiling clients of this spec, because such - compilations will fail if there is an error in the spec. - - GNAT provides an option for compiling such files purely for the - purposes of checking correctness; such compilations are not required as - part of the process of building a program. To compile a file in this - checking mode, use the @option{/NOLOAD} qualifier. - - @node Source Dependencies - @section Source Dependencies - - @noindent - A given object file clearly depends on the source file which is compiled - to produce it. Here we are using @dfn{depends} in the sense of a typical - @code{make} utility; in other words, an object file depends on a source - file if changes to the source file require the object file to be - recompiled. - In addition to this basic dependency, a given object may depend on - additional source files as follows: - - @itemize @bullet - @item - If a file being compiled @code{with}'s a unit @var{X}, the object file - depends on the file containing the spec of unit @var{X}. This includes - files that are @code{with}'ed implicitly either because they are parents - of @code{with}'ed child units or they are run-time units required by the - language constructs used in a particular unit. - - @item - If a file being compiled instantiates a library level generic unit, the - object file depends on both the spec and body files for this generic - unit. - - @item - If a file being compiled instantiates a generic unit defined within a - package, the object file depends on the body file for the package as - well as the spec file. - - @item - @findex Inline - @cindex @option{/INLINE=PRAGMA} qualifier - If a file being compiled contains a call to a subprogram for which - pragma @code{Inline} applies and inlining is activated with the - @option{/INLINE=PRAGMA} qualifier, the object file depends on the file containing the - body of this subprogram as well as on the file containing the spec. Note - that for inlining to actually occur as a result of the use of this qualifier, - it is necessary to compile in optimizing mode. - - @cindex @option{-gnatN} qualifier - The use of @option{-gnatN} activates a more extensive inlining optimization - that is performed by the front end of the compiler. This inlining does - not require that the code generation be optimized. Like @option{/INLINE=PRAGMA}, - the use of this qualifier generates additional dependencies. - - @item - If an object file O depends on the proper body of a subunit through inlining - or instantiation, it depends on the parent unit of the subunit. This means that - any modification of the parent unit or one of its subunits affects the - compilation of O. - - @item - The object file for a parent unit depends on all its subunit body files. - - @item - The previous two rules meant that for purposes of computing dependencies and - recompilation, a body and all its subunits are treated as an indivisible whole. - - @noindent - These rules are applied transitively: if unit @code{A} @code{with}'s - unit @code{B}, whose elaboration calls an inlined procedure in package - @code{C}, the object file for unit @code{A} will depend on the body of - @code{C}, in file @file{C.ADB}. - - The set of dependent files described by these rules includes all the - files on which the unit is semantically dependent, as described in the - Ada 95 Language Reference Manual. However, it is a superset of what the - ARM describes, because it includes generic, inline, and subunit dependencies. - - An object file must be recreated by recompiling the corresponding source - file if any of the source files on which it depends are modified. For - example, if the @code{make} utility is used to control compilation, - the rule for an Ada object file must mention all the source files on - which the object file depends, according to the above definition. - The determination of the necessary - recompilations is done automatically when one uses @code{GNAT MAKE}. - @end itemize - - @node The Ada Library Information Files - @section The Ada Library Information Files - @cindex Ada Library Information files - @cindex @file{ali} files - - @noindent - Each compilation actually generates two output files. The first of these - is the normal object file that has a @file{.OBJ} extension. The second is a - text file containing full dependency information. It has the same - name as the source file, but an @file{.ALI} extension. - This file is known as the Ada Library Information (@file{ali}) file. - The following information is contained in the @file{ali} file. - - @itemize @bullet - @item - Version information (indicates which version of GNAT was used to compile - the unit(s) in question) - - @item - Main program information (including priority and time slice settings, - as well as the wide character encoding used during compilation). - - @item - List of arguments used in the @code{GNAT COMPILE} command for the compilation - - @item - Attributes of the unit, including configuration pragmas used, an indication - of whether the compilation was successful, exception model used etc. - - @item - A list of relevant restrictions applying to the unit (used for consistency) - checking. - - @item - Categorization information (e.g. use of pragma @code{Pure}). - - @item - Information on all @code{with}'ed units, including presence of - @code{Elaborate} or @code{Elaborate_All} pragmas. - - @item - Information from any @code{Linker_Options} pragmas used in the unit - - @item - Information on the use of @code{Body_Version} or @code{Version} - attributes in the unit. - - @item - Dependency information. This is a list of files, together with - time stamp and checksum information. These are files on which - the unit depends in the sense that recompilation is required - if any of these units are modified. - - @item - Cross-reference data. Contains information on all entities referenced - in the unit. Used by tools like @code{GNAT XREF} and @code{GNAT FIND} to - provide cross-reference information. - - @end itemize - - @noindent - For a full detailed description of the format of the @file{ali} file, - see the source of the body of unit @code{Lib.Writ}, contained in file - @file{LIB-WRIT.ADB} in the GNAT compiler sources. - - @node Binding an Ada Program - @section Binding an Ada Program - - @noindent - When using languages such as C and C++, once the source files have been - compiled the only remaining step in building an executable program - is linking the object modules together. This means that it is possible to - link an inconsistent version of a program, in which two units have - included different versions of the same header. - - The rules of Ada do not permit such an inconsistent program to be built. - For example, if two clients have different versions of the same package, - it is illegal to build a program containing these two clients. - These rules are enforced by the GNAT binder, which also determines an - elaboration order consistent with the Ada rules. - - The GNAT binder is run after all the object files for a program have - been created. It is given the name of the main program unit, and from - this it determines the set of units required by the program, by reading the - corresponding ALI files. It generates error messages if the program is - inconsistent or if no valid order of elaboration exists. - - If no errors are detected, the binder produces a main program, in Ada by - default, that contains calls to the elaboration procedures of those - compilation unit that require them, followed by - a call to the main program. This Ada program is compiled to generate the - object file for the main program. The name of - the Ada file is @file{B$@var{xxx}.ADB} (with the corresponding spec - @file{B$@var{xxx}.ADS}) where @var{xxx} is the name of the - main program unit. - - Finally, the linker is used to build the resulting executable program, - using the object from the main program from the bind step as well as the - object files for the Ada units of the program. - - @node Mixed Language Programming - @section Mixed Language Programming - @cindex Mixed Language Programming - - @menu - * Interfacing to C:: - * Calling Conventions:: - @end menu - - @node Interfacing to C - @subsection Interfacing to C - @noindent - There are two ways to - build a program that contains some Ada files and some other language - files depending on whether the main program is in Ada or not. - If the main program is in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - GNAT COMPILE FILE1.C - GNAT COMPILE FILE2.C - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - GNAT MAKE /ACTIONS=COMPILE MY_MAIN.ADB - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - GNAT BIND MY_MAIN.ALI - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. For instance: - @smallexample - GNAT LINK MY_MAIN.ALI FILE1.OBJ FILE2.OBJ - @end smallexample - @end enumerate - - The three last steps can be grouped in a single command: - @smallexample - GNAT MAKE MY_MAIN.ADB /LINKER_QUALIFIERS FILE1.OBJ FILE2.OBJ - @end smallexample - - @cindex Binder output file - @noindent - If the main program is in some language other than Ada, you may - have more than one entry point in the Ada subsystem. You must use a - special option of the binder to generate callable routines to initialize - and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). - Calls to the initialization and finalization routines must be inserted in - the main program, or some other appropriate point in the code. The call to - initialize the Ada units must occur before the first Ada subprogram is - called, and the call to finalize the Ada units must occur after the last - Ada subprogram returns. You use the same procedure for building the - program as described previously. In this case, however, the binder - only places the initialization and finalization subprograms into file - @file{B$@var{xxx}.ADB} instead of the main program. - So, if the main program is not in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - GNAT COMPILE FILE1.C - GNAT COMPILE FILE2.C - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - GNAT MAKE /ACTIONS=COMPILE ENTRY_POINT1.ADB - GNAT MAKE /ACTIONS=COMPILE ENTRY_POINT2.ADB - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - GNAT BIND /NOMAIN ENTRY_POINT1.ALI ENTRY_POINT2.ALI - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. You only need to give the last entry point here. For instance: - @smallexample - GNAT LINK ENTRY_POINT2.ALI FILE1.OBJ FILE2.OBJ - @end smallexample - @end enumerate - - @node Calling Conventions - @subsection Calling Conventions - @cindex Foreign Languages - @cindex Calling Conventions - GNAT follows standard calling sequence conventions and will thus interface - to any other language that also follows these conventions. The following - Convention identifiers are recognized by GNAT: - - @itemize @bullet - @cindex Interfacing to Ada - @cindex Other Ada compilers - @cindex Convention Ada - @item - Ada. This indicates that the standard Ada calling sequence will be - used and all Ada data items may be passed without any limitations in the - case where GNAT is used to generate both the caller and callee. It is also - possible to mix GNAT generated code and code generated by another Ada - compiler. In this case, the data types should be restricted to simple - cases, including primitive types. Whether complex data types can be passed - depends on the situation. Probably it is safe to pass simple arrays, such - as arrays of integers or floats. Records may or may not work, depending - on whether both compilers lay them out identically. Complex structures - involving variant records, access parameters, tasks, or protected types, - are unlikely to be able to be passed. - - Note that in the case of GNAT running - on a platform that supports DEC Ada 83, a higher degree of compatibility - can be guaranteed, and in particular records are layed out in an identical - manner in the two compilers. Note also that if output from two different - compilers is mixed, the program is responsible for dealing with elaboration - issues. Probably the safest approach is to write the main program in the - version of Ada other than GNAT, so that it takes care of its own elaboration - requirements, and then call the GNAT-generated adainit procedure to ensure - elaboration of the GNAT components. Consult the documentation of the other - Ada compiler for further details on elaboration. - - However, it is not possible to mix the tasking run time of GNAT and - DEC Ada 83, All the tasking operations must either be entirely within - GNAT compiled sections of the program, or entirely within DEC Ada 83 - compiled sections of the program. - - @cindex Interfacing to Assembly - @cindex Convention Assembler - @item - Assembler. Specifies assembler as the convention. In practice this has the - same effect as convention Ada (but is not equivalent in the sense of being - considered the same convention). - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembler. - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembly. - - @cindex Interfacing to COBOL - @cindex Convention COBOL - @findex COBOL - @item - COBOL. Data will be passed according to the conventions described - in section B.4 of the Ada 95 Reference Manual. - - @findex C - @cindex Interfacing to C - @cindex Convention C - @item - C. Data will be passed according to the conventions described - in section B.3 of the Ada 95 Reference Manual. - - @cindex Convention Default - @findex Default - @item - Default. Equivalent to C. - - @cindex Convention External - @findex External - @item - External. Equivalent to C. - - @findex C++ - @cindex Interfacing to C++ - @cindex Convention C++ - @item - CPP. This stands for C++. For most purposes this is identical to C. - See the separate description of the specialized GNAT pragmas relating to - C++ interfacing for further details. - - @findex Fortran - @cindex Interfacing to Fortran - @cindex Convention Fortran - @item - Fortran. Data will be passed according to the conventions described - in section B.5 of the Ada 95 Reference Manual. - - @item - Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95 - Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, - this means that the body of the subprogram is provided by the compiler itself, - usually by means of an efficient code sequence, and that the user does not - supply an explicit body for it. In an application program, the pragma can only - be applied to the following two sets of names, which the GNAT compiler - recognizes. - @itemize @bullet - @item - Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_- - Arithmetic. The corresponding subprogram declaration must have - two formal parameters. The - first one must be a signed integer type or a modular type with a binary - modulus, and the second parameter must be of type Natural. - The return type must be the same as the type of the first argument. The size - of this type can only be 8, 16, 32, or 64. - @item binary arithmetic operators: "+", "-", "*", "/" - The corresponding operator declaration must have parameters and result type - that have the same root numeric type (for example, all three are long_float - types). This simplifies the definition of operations that use type checking - to perform dimensional checks: - @smallexample - type Distance is new Long_Float; - type Time is new Long_Float; - type Velocity is new Long_Float; - function "/" (D : Distance; T : Time) - return Velocity; - pragma Import (Intrinsic, "/"); - @end smallexample - @noindent - This common idiom is often programmed with a generic definition and an explicit - body. The pragma makes it simpler to introduce such declarations. It incurs - no overhead in compilation time or code size, because it is implemented as a - single machine instruction. - @end itemize - @noindent - - @findex Stdcall - @cindex Convention Stdcall - @item - Stdcall. This is relevant only to NT/Win95 implementations of GNAT, - and specifies that the Stdcall calling sequence will be used, as defined - by the NT API. - - @findex DLL - @cindex Convention DLL - @item - DLL. This is equivalent to Stdcall. - - @findex Win32 - @cindex Convention Win32 - @item - Win32. This is equivalent to Stdcall. - - @findex Stubbed - @cindex Convention Stubbed - @item - Stubbed. This is a special convention that indicates that the compiler - should provide a stub body that raises @code{Program_Error}. - @end itemize - - @noindent - GNAT additionally provides a useful pragma @code{Convention_Identifier} - that can be used to parametrize conventions and allow additional synonyms - to be specified. For example if you have legacy code in which the convention - identifier Fortran77 was used for Fortran, you can use the configuration - pragma: - - @smallexample - pragma Convention_Identifier (Fortran77, Fortran); - @end smallexample - - @noindent - And from now on the identifier Fortran77 may be used as a convention - identifier (for example in an @code{Import} pragma) with the same - meaning as Fortran. - - @node Building Mixed Ada & C++ Programs - @section Building Mixed Ada & C++ Programs - - @noindent - Building a mixed application containing both Ada and C++ code may be a - challenge for the unaware programmer. As a matter of fact, this - interfacing has not been standardized in the Ada 95 reference manual due - to the immaturity and lack of standard of C++ at the time. This - section gives a few hints that should make this task easier. In - particular the first section addresses the differences with - interfacing with C. The second section looks into the delicate problem - of linking the complete application from its Ada and C++ parts. The last - section give some hints on how the GNAT run time can be adapted in order - to allow inter-language dispatching with a new C++ compiler. - - @menu - * Interfacing to C++:: - * Linking a Mixed C++ & Ada Program:: - * A Simple Example:: - * Adapting the Run Time to a New C++ Compiler:: - @end menu - - @node Interfacing to C++ - @subsection Interfacing to C++ - - @noindent - GNAT supports interfacing with C++ compilers generating code that is - compatible with the standard Application Binary Interface of the given - platform. - - @noindent - Interfacing can be done at 3 levels: simple data, subprograms and - classes. In the first 2 cases, GNAT offer a specific @var{Convention - CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle - names of subprograms and currently GNAT does not provide any help to - solve the demangling problem. This problem can be addressed in 2 ways: - @itemize @bullet - @item - by modifying the C++ code in order to force a C convention using - the @var{extern "C"} syntax. - - @item - by figuring out the mangled name and use it as the Link_Name argument of - the pragma import. - @end itemize - - @noindent - Interfacing at the class level can be achieved by using the GNAT specific - pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT - Reference Manual for additional information. - - @node Linking a Mixed C++ & Ada Program - @subsection Linking a Mixed C++ & Ada Program - - @noindent - Usually the linker of the C++ development system must be used to link - mixed applications because most C++ systems will resolve elaboration - issues (such as calling constructors on global class instances) - transparently during the link phase. GNAT has been adapted to ease the - use of a foreign linker for the last phase. Three cases can be - considered: - @enumerate - - @item - Using GNAT and G++ (GNU C++ compiler) from the same GCC - installation. The c++ linker can simply be called by using the c++ - specific driver called @code{c++}. Note that this setup is not - very common because it may request recompiling the whole GCC - tree from sources and it does not allow to upgrade easily to a new - version of one compiler for one of the two languages without taking the - risk of destabilizing the other. - - @smallexample - $ c++ -c file1.C - $ c++ -c file2.C - $ GNAT MAKE ada_unit /LINKER_QUALIFIERS FILE1.OBJ FILE2.OBJ --LINK=c++ - @end smallexample - - @item - Using GNAT and G++ from 2 different GCC installations. If both compilers - are on the PATH, the same method can be used. It is important to be - aware that environment variables such as C_INCLUDE_PATH, - GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at - the same time and thus may make one of the 2 compilers operate - improperly if they are set for the other. In particular it is important - that the link command has access to the proper GNAT COMPILE library @file{libgcc.a}, - that is to say the one that is part of the C++ compiler - installation. The implicit link command as suggested in the GNAT MAKE - command from the former example can be replaced by an explicit link - command with full verbosity in order to verify which library is used: - @smallexample - $ GNAT BIND ada_unit - $ GNAT LINK -v -v ada_unit FILE1.OBJ FILE2.OBJ --LINK=c++ - @end smallexample - If there is a problem due to interfering environment variables, it can - be workaround by using an intermediate script. The following example - shows the proper script to use when GNAT has not been installed at its - default location and g++ has been installed at its default location: - - @smallexample - $ GNAT LINK -v -v ada_unit FILE1.OBJ FILE2.OBJ --LINK=./my_script - $ cat ./my_script - #!/bin/sh - unset BINUTILS_ROOT - unset GCC_ROOT - c++ $* - @end smallexample - - @item - Using a non GNU C++ compiler. The same set of command as previously - described can be used to insure that the c++ linker is - used. Nonetheless, you need to add the path to libgcc explicitely, since some - libraries needed by GNAT are located in this directory: - - @smallexample - - $ GNAT LINK ada_unit FILE1.OBJ FILE2.OBJ --LINK=./my_script - $ cat ./my_script - #!/bin/sh - CC $* `GNAT COMPILE -print-libgcc-file-name` - - @end smallexample - - Where CC is the name of the non GNU C++ compiler. - - @end enumerate - - @node A Simple Example - @subsection A Simple Example - @noindent - The following example, provided as part of the GNAT examples, show how - to achieve procedural interfacing between Ada and C++ in both - directions. The C++ class A has 2 methods. The first method is exported - to Ada by the means of an extern C wrapper function. The second method - calls an Ada subprogram. On the Ada side, The C++ calls is modelized by - a limited record with a layout comparable to the C++ class. The Ada - subprogram, in turn, calls the c++ method. So from the C++ main program - the code goes back and forth between the 2 languages. - - @noindent - Here are the compilation commands - for native configurations: - @smallexample - $ GNAT MAKE -c simple_cpp_interface - $ c++ -c cpp_main.C - $ c++ -c ex7.C - $ GNAT BIND -n simple_cpp_interface - $ GNAT LINK simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS) - -lstdc++ EX7.OBJ CPP_MAIN.OBJ - @end smallexample - @noindent - Here are the corresponding sources: - @smallexample - - //cpp_main.C - - #include "ex7.h" - - extern "C" @{ - void adainit (void); - void adafinal (void); - void method1 (A *t); - @} - - void method1 (A *t) - @{ - t->method1 (); - @} - - int main () - @{ - A obj; - adainit (); - obj.method2 (3030); - adafinal (); - @} - - //ex7.h - - class Origin @{ - public: - int o_value; - @}; - class A : public Origin @{ - public: - void method1 (void); - virtual void method2 (int v); - A(); - int a_value; - @}; - - //ex7.C - - #include "ex7.h" - #include - - extern "C" @{ void ada_method2 (A *t, int v);@} - - void A::method1 (void) - @{ - a_value = 2020; - printf ("in A::method1, a_value = %d \n",a_value); - - @} - - void A::method2 (int v) - @{ - ada_method2 (this, v); - printf ("in A::method2, a_value = %d \n",a_value); - - @} - - A::A(void) - @{ - a_value = 1010; - printf ("in A::A, a_value = %d \n",a_value); - @} - - -- Ada sources - @b{package} @b{body} Simple_Cpp_Interface @b{is} - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is} - @b{begin} - Method1 (This); - This.A_Value := V; - @b{end} Ada_Method2; - - @b{end} Simple_Cpp_Interface; - - @b{package} Simple_Cpp_Interface @b{is} - @b{type} A @b{is} @b{limited} - @b{record} - O_Value : Integer; - A_Value : Integer; - @b{end} @b{record}; - @b{pragma} Convention (C, A); - - @b{procedure} Method1 (This : @b{in} @b{out} A); - @b{pragma} Import (C, Method1); - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer); - @b{pragma} Export (C, Ada_Method2); - - @b{end} Simple_Cpp_Interface; - @end smallexample - - @node Adapting the Run Time to a New C++ Compiler - @subsection Adapting the Run Time to a New C++ Compiler - @noindent - GNAT offers the capability to derive Ada 95 tagged types directly from - preexisting C++ classes and . See "Interfacing with C++" in the GNAT - reference manual. The mechanism used by GNAT for achieving such a goal - has been made user configurable through a GNAT library unit - @code{Interfaces.CPP}. The default version of this file is adapted to - the GNU c++ compiler. Internal knowledge of the virtual - table layout used by the new C++ compiler is needed to configure - properly this unit. The Interface of this unit is known by the compiler - and cannot be changed except for the value of the constants defining the - characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, - CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source - of this unit for more details. - - @node Comparison between GNAT and C/C++ Compilation Models - @section Comparison between GNAT and C/C++ Compilation Models - - @noindent - The GNAT model of compilation is close to the C and C++ models. You can - think of Ada specs as corresponding to header files in C. As in C, you - don't need to compile specs; they are compiled when they are used. The - Ada @code{with} is similar in effect to the @code{#include} of a C - header. - - One notable difference is that, in Ada, you may compile specs separately - to check them for semantic and syntactic accuracy. This is not always - possible with C headers because they are fragments of programs that have - less specific syntactic or semantic rules. - - The other major difference is the requirement for running the binder, - which performs two important functions. First, it checks for - consistency. In C or C++, the only defense against assembling - inconsistent programs lies outside the compiler, in a makefile, for - example. The binder satisfies the Ada requirement that it be impossible - to construct an inconsistent program when the compiler is used in normal - mode. - - @cindex Elaboration order control - The other important function of the binder is to deal with elaboration - issues. There are also elaboration issues in C++ that are handled - automatically. This automatic handling has the advantage of being - simpler to use, but the C++ programmer has no control over elaboration. - Where @code{GNAT BIND} might complain there was no valid order of - elaboration, a C++ compiler would simply construct a program that - malfunctioned at run time. - - @node Comparison between GNAT and Conventional Ada Library Models - @section Comparison between GNAT and Conventional Ada Library Models - - @noindent - This section is intended to be useful to Ada programmers who have - previously used an Ada compiler implementing the traditional Ada library - model, as described in the Ada 95 Language Reference Manual. If you - have not used such a system, please go on to the next section. - - @cindex GNAT library - In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of - source files themselves acts as the library. Compiling Ada programs does - not generate any centralized information, but rather an object file and - a ALI file, which are of interest only to the binder and linker. - In a traditional system, the compiler reads information not only from - the source file being compiled, but also from the centralized library. - This means that the effect of a compilation depends on what has been - previously compiled. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the version of the unit most recently compiled into the library. - - @item - Inlining is effective only if the necessary body has already been - compiled into the library. - - @item - Compiling a unit may obsolete other units in the library. - @end itemize - - @noindent - In GNAT, compiling one unit never affects the compilation of any other - units because the compiler reads only source files. Only changes to source - files can affect the results of a compilation. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the source version of the unit that is currently accessible to the - compiler. - - @item - @cindex Inlining - Inlining requires the appropriate source files for the package or - subprogram bodies to be available to the compiler. Inlining is always - effective, independent of the order in which units are complied. - - @item - Compiling a unit never affects any other compilations. The editing of - sources may cause previous compilations to be out of date if they - depended on the source file being modified. - @end itemize - - @noindent - The most important result of these differences is that order of compilation - is never significant in GNAT. There is no situation in which one is - required to do one compilation before another. What shows up as order of - compilation requirements in the traditional Ada library becomes, in - GNAT, simple source dependencies; in other words, there is only a set - of rules saying what source files must be present when a file is - compiled. - - @node Compiling Using GNAT COMPILE - @chapter Compiling Using @code{GNAT COMPILE} - - @noindent - This chapter discusses how to compile Ada programs using the @code{GNAT COMPILE} - command. It also describes the set of qualifiers - that can be used to control the behavior of the compiler. - @menu - * Compiling Programs:: - * Qualifiers for GNAT COMPILE:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - @end menu - - @node Compiling Programs - @section Compiling Programs - - @noindent - The first step in creating an executable program is to compile the units - of the program using the @code{GNAT COMPILE} command. You must compile the - following files: - - @itemize @bullet - @item - the body file (@file{.ADB}) for a library level subprogram or generic - subprogram - - @item - the spec file (@file{.ADS}) for a library level package or generic - package that has no body - - @item - the body file (@file{.ADB}) for a library level package - or generic package that has a body - - @end itemize - - @noindent - You need @emph{not} compile the following files - - @itemize @bullet - - @item - the spec of a library unit which has a body - - @item - subunits - @end itemize - - @noindent - because they are compiled as part of compiling related units. GNAT - package specs - when the corresponding body is compiled, and subunits when the parent is - compiled. - @cindex No code generated - If you attempt to compile any of these files, you will get one of the - following error messages (where fff is the name of the file you compiled): - - @smallexample - No code generated for file @var{fff} (@var{package spec}) - No code generated for file @var{fff} (@var{subunit}) - @end smallexample - - @noindent - The basic command for compiling a file containing an Ada unit is - - @smallexample - $ GNAT COMPILE [@var{qualifiers}] @file{file name} - @end smallexample - - @noindent - where @var{file name} is the name of the Ada file (usually - having an extension - @file{.ADS} for a spec or @file{.ADB} for a body). - The result of a successful compilation is an object file, which has the - same name as the source file but an extension of @file{.OBJ} and an Ada - Library Information (ALI) file, which also has the same name as the - source file, but with @file{.ALI} as the extension. GNAT creates these - two output files in the current directory, but you may specify a source - file in any directory using an absolute or relative path specification - containing the directory information. - - @findex GNAT1 - @code{GNAT COMPILE} is actually a driver program that looks at the extensions of - the file arguments and loads the appropriate compiler. For example, the - GNU C compiler is @file{CC1}, and the Ada compiler is @file{GNAT1}. - These programs are in directories known to the driver program (in some - configurations via environment variables you set), but need not be in - your path. The @code{GNAT COMPILE} driver also calls the assembler and any other - utilities needed to complete the generation of the required object - files. - - It is possible to supply several file names on the same @code{GNAT COMPILE} - command. This causes @code{GNAT COMPILE} to call the appropriate compiler for - each file. For example, the following command lists three separate - files to be compiled: - - @smallexample - $ GNAT COMPILE X.ADB Y.ADB Z.C - @end smallexample - - @noindent - calls @code{GNAT1} (the Ada compiler) twice to compile @file{X.ADB} and - @file{Y.ADB}, and @code{CC1} (the C compiler) once to compile @file{Z.C}. - The compiler generates three object files @file{X.OBJ}, @file{Y.OBJ} and - @file{Z.OBJ} and the two ALI files @file{X.ALI} and @file{Y.ALI} from the - Ada compilations. Any qualifiers apply to all the files listed. - - @node Qualifiers for GNAT COMPILE - @section Qualifiers for @code{GNAT COMPILE} - - @noindent - The @code{GNAT COMPILE} command accepts qualifiers that control the - compilation process. These qualifiers are fully described in this section. - First we briefly list all the qualifiers, in alphabetical order, then we - describe the qualifiers in more detail in functionally grouped sections. - - @menu - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using GNAT COMPILE for Syntax Checking:: - * Using GNAT COMPILE for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - @end menu - - @table @code - - @item /DEBUG - @cindex @code{/DEBUG} (@code{GNAT COMPILE}) - Generate debugging information. This information is stored in the object - file and copied from there to the final executable file by the linker, - where it can be read by the debugger. You must use the - @code{/DEBUG} qualifier if you plan on using the debugger. - - @item /SEARCH=@var{dir} - @cindex @code{/SEARCH} (@code{GNAT COMPILE}) - @cindex RTL - Direct GNAT to search the @var{dir} directory for source files needed by - the current compilation - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item /NOCURRENT_DIRECTORY - @cindex @code{/NOCURRENT_DIRECTORY} (@code{GNAT COMPILE}) - @cindex RTL - Except for the source file named in the command line, do not look for source files - in the directory containing the source file named in the command line - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - - - @item /NOOPTIMIZE (default) - @itemx /OPTIMIZE[=(keyword[,...])] - Selects the level of optimization for your program. The supported - keywords are as follows: - @table @code - @item ALL (default) - Perform most optimizations, including those that - be expensive. - - @item NONE - Do not do any optimizations. Same as @code{/NOOPTIMIZE}. - - @item SOME - Perform some optimizations, but omit ones that are costly. - - @item DEVELOPMENT - Same as @code{SOME}. - - @item INLINING - Full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - - @item UNROLL_LOOPS - Try to unroll loops. This keyword may be specified together with - any keyword above other than @code{NONE}. Loop unrolling - usually, but not always, improves the performance of programs. - @end table - - @item /RUNTIME_SYSTEM=@var{rts-path} - @cindex @code{/RUNTIME_SYSTEM} (@code{GNAT COMPILE}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{GNAT MAKE} flag (see @ref{Qualifiers for GNAT MAKE}). - - @item /ASM - @cindex @code{/ASM} (@code{GNAT COMPILE}) - Used to - cause the assembler source file to be - generated, using @file{.S} as the extension, - instead of the object file. - This may be useful if you need to examine the generated assembly code. - - @item /VERBOSE - @cindex @code{/VERBOSE} (@code{GNAT COMPILE}) - Show commands generated by the @code{GNAT COMPILE} driver. Normally used only for - debugging purposes or if you need to be sure what version of the - compiler you are executing. - - - @item /CHECKS=ASSERTIONS - Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be - activated. - - @item -gnatA - Avoid processing @file{GNAT.ADC}. If a GNAT.ADC file is present, it will be ignored. - - @item /WARNINGS=BRIEF - Generate brief messages to @file{SYS$ERROR} even if verbose mode set. - - @item /NOLOAD - Check syntax and semantics only (no code generation attempted). - - @item /COMPRESS_NAMES - Compress debug information and external symbol name table entries. - - @item /XDEBUG - Output expanded source files for source level debugging. This qualifier - also suppress generation of cross-reference information (see /XREF=SUPPRESS). - - @item -gnatec@var{path} - Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files}) - - @item -gnatem@var{path} - Specify a mapping file. (see @ref{Units to Sources Mapping Files}) - - @item /CHECKS=ELABORATION - Full dynamic elaboration checks. - - @item /REPORT_ERRORS=FULL - Full errors. Multiple errors per line, all undefined references. - - @item /UPPERCASE_EXTERNALS - Externals names are folded to all uppercase. - - @item /STYLE=GNAT - Internal GNAT implementation mode. This should not be used for - applications programs, it is intended only for use by the compiler - and its run-time library. For documentation, see the GNAT sources. - - @item /EXPAND_SOURCE - List generated expanded code in source form. - - @item /IDENTIFIER_CHARACTER_SET=@var{c} - Identifier character set - For details of the possible selections for @var{c}, - see @xref{Character Set Control}. - - @item /HELP - Output usage information. The output is written to @file{SYS$OUTPUT}. - - @item /FILE_NAME_MAX_LENGTH=@var{n} - Limit file names to @var{n} (1-999) characters . - - @item /LIST - Output full source listing with embedded error messages. - - @item /ERROR_LIMIT=@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item /INLINE=PRAGMA - Activate inlining across unit boundaries for subprograms for which - pragma @code{inline} is specified. - - @item -gnatN - Activate front end inlining. - - @item /INLINE=SUPPRESS - Suppresses all inlining, even if other optimization or inlining qualifiers - are set. - - - @item /CHECKS=OVERFLOW - Enable numeric overflow checking (which is not normally enabled by - default). Not that division by zero is a separate check that is not - controlled by this qualifier (division by zero checking is on by default). - - @item /CHECKS=SUPPRESS_ALL - Suppress all checks. - - @item /TRY_SEMANTICS - Don't quit; try semantics, even if parse errors. - - @item /FORCE_ALI - Don't quit; generate @file{ali} and tree files even if illegalities. - - @item /POLLING_ENABLE - Enable polling. This is required on some systems (notably Windows NT) to - obtain asynchronous abort and asynchronous transfer of control capability. - See the description of pragma Polling in the GNAT Reference Manual for - full details. - - @item /REPRESENTATION_INFO[0/1/2/3][s] - Output representation information for declared types and objects. - - @item /SYNTAX_ONLY - Syntax check only. - - @item /TREE_OUTPUT - Tree output file to be generated. - - @item -gnatT nnn - Set time slice to specified number of microseconds - - @item /UNITS_LIST - List units for this compilation. - - @item /UNIQUE_ERROR_TAG - Tag all error messages with the unique string "error:" - - @item /REPORT_ERRORS=VERBOSE - Verbose mode. Full error output with source lines to @file{SYS$OUTPUT}. - - @item /VALIDITY_CHECKING - Control level of validity checking. See separate section describing - this feature. - - @item /WARNINGS=@var{xxx} - Warning mode where - @var{xxx} is a string of options describing the exact warnings that - are enabled or disabled. See separate section on warning control. - - @item /WIDE_CHARACTER_ENCODING=@var{e} - Wide character encoding method - (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8}) - - @item /XREF=SUPPRESS - Suppress generation of cross-reference information. - - @item /STYLE_CHECKS=(option,option..) - Enable built-in style checks. See separate section describing this feature. - - @item /DISTRIBUTION_STUBS=@var{m} - Distribution stub generation and compilation - (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs - to be generated and compiled). - - @item /83 - Enforce Ada 83 restrictions. - - @end table - - - @noindent - The following restrictions apply to the combination of qualifiers - in this manner: - - @itemize @bullet - @item - The qualifier @option{/NOLOAD} if combined with other qualifiers must come - first in the string. - - @item - The qualifier @option{/SYNTAX_ONLY} if combined with other qualifiers must come - first in the string. - - @item - Once a "y" appears in the string (that is a use of the @option{/STYLE=} - qualifier), then all further characters in the qualifier are interpreted - as style modifiers (see description of @option{/STYLE=}). - - @item - Once a "d" appears in the string (that is a use of the @option{-gnatd} - qualifier), then all further characters in the qualifier are interpreted - as debug flags (see description of @option{-gnatd}). - - @item - Once a "w" appears in the string (that is a use of the @option{-gnatw} - qualifier), then all further characters in the qualifier are interpreted - as warning mode modifiers (see description of @option{-gnatw}). - - @item - Once a "V" appears in the string (that is a use of the @option{/VALIDITY_CHECKING} - qualifier), then all further characters in the qualifier are interpreted - as validity checking options (see description of @option{/VALIDITY_CHECKING}). - - @end itemize - - @node Output and Error Message Control - @subsection Output and Error Message Control - @findex SYS$ERROR - - @noindent - The standard default format for error messages is called "brief format." - Brief format messages are written to @file{SYS$ERROR} (the standard error - file) and have the following form: - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - E.ADB:3:04: Incorrect spelling of keyword "function" - E.ADB:4:20: ";" should be "is" - @end smallexample - - @noindent - The first integer after the file name is the line number in the file, - and the second integer is the column number within the line. - @code{glide} can parse the error messages - and point to the referenced character. - The following qualifiers provide control over the error message - format: - - @table @code - @item /REPORT_ERRORS=VERBOSE - @cindex @option{/REPORT_ERRORS=VERBOSE} (@code{GNAT COMPILE}) - @findex SYS$OUTPUT - The effect of this setting is to write long-format error - messages to @file{SYS$OUTPUT} (the standard output file. - The same program compiled with the - @option{/REPORT_ERRORS=VERBOSE} qualifier would generate: - - @smallexample - @group - @cartouche - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - @end cartouche - @end group - @end smallexample - - @noindent - The vertical bar indicates the location of the error, and the @samp{>>>} - prefix can be used to search for error messages. When this qualifier is - used the only source lines output are those with errors. - - @item /LIST - @cindex @option{/LIST} (@code{GNAT COMPILE}) - This qualifier causes a full listing of - the file to be generated. The output might look as follows: - - @smallexample - @group - @cartouche - 1. procedure E is - 2. V : Integer; - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - 5. begin - 6. return Q + Q; - 7. end; - 8. begin - 9. V := X + X; - 10.end E; - @end cartouche - @end group - @end smallexample - - @noindent - @findex SYS$ERROR - When you specify the @option{/REPORT_ERRORS=VERBOSE} or @option{/LIST} qualifiers and - standard output is redirected, a brief summary is written to - @file{SYS$ERROR} (standard error) giving the number of error messages and - warning messages generated. - - @item /UNIQUE_ERROR_TAG - @cindex @option{/UNIQUE_ERROR_TAG} (@code{GNAT COMPILE}) - This qualifier forces all error messages to be preceded by the unique - string "error:". This means that error messages take a few more - characters in space, but allows easy searching for and identification - of error messages. - - @item /WARNINGS=BRIEF - @cindex @option{/WARNINGS=BRIEF} (@code{GNAT COMPILE}) - This qualifier causes GNAT to generate the - brief format error messages to @file{SYS$ERROR} (the standard error - file) as well as the verbose - format message or full listing (which as usual is written to - @file{SYS$OUTPUT} (the standard output file). - - @item /ERROR_LIMIT=@var{n} - @cindex @option{/ERROR_LIMIT} (@code{GNAT COMPILE}) - @var{n} is a decimal integer in the - range of 1 to 999 and limits the number of error messages to be - generated. For example, using @option{/ERROR_LIMIT=2} might yield - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - E.ADB:3:04: Incorrect spelling of keyword "function" - E.ADB:5:35: missing ".." - fatal error: maximum errors reached - compilation abandoned - @end smallexample - - @item /REPORT_ERRORS=FULL - @cindex @option{/REPORT_ERRORS=FULL} (@code{GNAT COMPILE}) - @cindex Error messages, suppressing - Normally, the compiler suppresses error messages that are likely to be - redundant. This qualifier causes all error - messages to be generated. In particular, in the case of - references to undefined variables. If a given variable is referenced - several times, the normal format of messages is - @smallexample - @iftex - @leftskip=.7cm - @end iftex - E.ADB:7:07: "V" is undefined (more references follow) - @end smallexample - - @noindent - where the parenthetical comment warns that there are additional - references to the variable @code{V}. Compiling the same program with the - @option{/REPORT_ERRORS=FULL} qualifier yields - - @smallexample - E.ADB:7:07: "V" is undefined - E.ADB:8:07: "V" is undefined - E.ADB:8:12: "V" is undefined - E.ADB:8:16: "V" is undefined - E.ADB:9:07: "V" is undefined - E.ADB:9:12: "V" is undefined - @end smallexample - - @item /TRY_SEMANTICS - @cindex @option{/TRY_SEMANTICS} (@code{GNAT COMPILE}) - In normal operation mode, the compiler first parses the program and - determines if there are any syntax errors. If there are, appropriate - error messages are generated and compilation is immediately terminated. - This qualifier tells - GNAT to continue with semantic analysis even if syntax errors have been - found. This may enable the detection of more errors in a single run. On - the other hand, the semantic analyzer is more likely to encounter some - internal fatal error when given a syntactically invalid tree. - - @item /FORCE_ALI - In normal operation mode, the @file{ali} file is not generated if any - illegalities are detected in the program. The use of @option{/FORCE_ALI} forces - generation of the @file{ali} file. This file is marked as being in - error, so it cannot be used for binding purposes, but it does contain - reasonably complete cross-reference information, and thus may be useful - for use by tools (e.g. semantic browsing tools or integrated development - environments) that are driven from the @file{ali} file. - - In addition, if @option{/TREE_OUTPUT} is also specified, then the tree file is - generated even if there are illegalities. It may be useful in this case - to also specify @option{/TRY_SEMANTICS} to ensure that full semantic processing - occurs. The resulting tree file can be processed by ASIS, for the purpose - of providing partial information about illegal units, but if the error - causes the tree to be badly malformed, then ASIS may crash during the - analysis. - - @end table - - @noindent - In addition to error messages, which correspond to illegalities as defined - in the Ada 95 Reference Manual, the compiler detects two kinds of warning - situations. - - @cindex Warning messages - First, the compiler considers some constructs suspicious and generates a - warning message to alert you to a possible error. Second, if the - compiler detects a situation that is sure to raise an exception at - run time, it generates a warning message. The following shows an example - of warning messages: - @smallexample - @iftex - @leftskip=.2cm - @end iftex - E.ADB:4:24: warning: creation of object may raise Storage_Error - E.ADB:10:17: warning: static value out of range - E.ADB:10:17: warning: "Constraint_Error" will be raised at run time - - @end smallexample - - @noindent - GNAT considers a large number of situations as appropriate - for the generation of warning messages. As always, warnings are not - definite indications of errors. For example, if you do an out-of-range - assignment with the deliberate intention of raising a - @code{Constraint_Error} exception, then the warning that may be - issued does not indicate an error. Some of the situations for which GNAT - issues warnings (at least some of the time) are given in the following - list, which is not necessarily complete. - - @itemize @bullet - @item - Possible infinitely recursive calls - - @item - Out-of-range values being assigned - - @item - Possible order of elaboration problems - - @item - Unreachable code - - @item - Fixed-point type declarations with a null range - - @item - Variables that are never assigned a value - - @item - Variables that are referenced before being initialized - - @item - Task entries with no corresponding accept statement - - @item - Duplicate accepts for the same task entry in a select - - @item - Objects that take too much storage - - @item - Unchecked conversion between types of differing sizes - - @item - Missing return statements along some execution paths in a function - - @item - Incorrect (unrecognized) pragmas - - @item - Incorrect external names - - @item - Allocation from empty storage pool - - @item - Potentially blocking operations in protected types - - @item - Suspicious parenthesization of expressions - - @item - Mismatching bounds in an aggregate - - @item - Attempt to return local value by reference - - @item - Unrecognized pragmas - - @item - Premature instantiation of a generic body - - @item - Attempt to pack aliased components - - @item - Out of bounds array subscripts - - @item - Wrong length on string assignment - - @item - Violations of style rules if style checking is enabled - - @item - Unused with clauses - - @item - Bit_Order usage that does not have any effect - - @item - Compile time biased rounding of floating-point constant - - @item - Standard.Duration used to resolve universal fixed expression - - @item - Dereference of possibly null value - - @item - Declaration that is likely to cause storage error - - @item - Internal GNAT unit with'ed by application unit - - @item - Values known to be out of range at compile time - - @item - Unreferenced labels and variables - - @item - Address overlays that could clobber memory - - @item - Unexpected initialization when address clause present - - @item - Bad alignment for address clause - - @item - Useless type conversions - - @item - Redundant assignment statements - - @item - Accidental hiding of name by child unit - - @item - Unreachable code - - @item - Access before elaboration detected at compile time - - @item - A range in a @code{for} loop that is known to be null or might be null - - @end itemize - - @noindent - The following qualifiers are available to control the handling of - warning messages: - - @table @code - @item /WARNINGS=OPTIONAL (activate all optional errors) - @cindex @option{/WARNINGS=OPTIONAL} (@code{GNAT COMPILE}) - This qualifier activates most optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. The warnings that are not turned on by this - qualifier are @option{/WARNINGS=BIASED_ROUNDING} (biased rounding), - @option{/WARNINGS=IMPLICIT_DEREFERENCE} (implicit dereferencing), - and @option{/WARNINGS=HIDING} (hiding). All other optional warnings are - turned on. - - @item /WARNINGS=NOOPTIONAL (suppress all optional errors) - @cindex @option{/WARNINGS=NOOPTIONAL} (@code{GNAT COMPILE}) - This qualifier suppresses all optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. - - @item /WARNINGS=BIASED_ROUNDING (activate warnings on biased rounding) - @cindex @option{/WARNINGS=BIASED_ROUNDING} (@code{GNAT COMPILE}) - @cindex Rounding, biased - @cindex Biased rounding - If a static floating-point expression has a value that is exactly half - way between two adjacent machine numbers, then the rules of Ada - (Ada Reference Manual, section 4.9(38)) require that this rounding - be done away from zero, even if the normal unbiased rounding rules - at run time would require rounding towards zero. This warning message - alerts you to such instances where compile-time rounding and run-time - rounding are not equivalent. If it is important to get proper run-time - rounding, then you can force this by making one of the operands into - a variable. The default is that such warnings are not generated. - Note that @option{/WARNINGS=OPTIONAL} does not affect the setting of - this warning option. - - @item /WARNINGS=NOBIASED_ROUNDING (suppress warnings on biased rounding) - @cindex @option{/WARNINGS=NOBIASED_ROUNDING} (@code{GNAT COMPILE}) - This qualifier disables warnings on biased rounding. - - @item /WARNINGS=CONDITIONALS (activate warnings on conditionals) - @cindex @option{/WARNINGS=CONDITIONALS} (@code{GNAT COMPILE}) - @cindex Conditionals, constant - This qualifier activates warnings for conditional expressions used in - tests that are known to be True or False at compile time. The default - is that such warnings are not generated. - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @item /WARNINGS=NOCONDITIONALS (suppress warnings on conditionals) - @cindex @option{/WARNINGS=NOCONDITIONALS} (@code{GNAT COMPILE}) - This qualifier suppresses warnings for conditional expressions used in - tests that are known to be True or False at compile time. - - @item /WARNINGS=IMPLICIT_DEREFERENCE (activate warnings on implicit dereferencing) - @cindex @option{/WARNINGS=IMPLICIT_DEREFERENCE} (@code{GNAT COMPILE}) - If this qualifier is set, then the use of a prefix of an access type - in an indexed component, slice, or selected component without an - explicit @code{.all} will generate a warning. With this warning - enabled, access checks occur only at points where an explicit - @code{.all} appears in the source code (assuming no warnings are - generated as a result of this qualifier). The default is that such - warnings are not generated. - Note that @option{/WARNINGS=OPTIONAL} does not affect the setting of - this warning option. - - @item /WARNINGS=NOIMPLICIT_DEREFERENCE (suppress warnings on implicit dereferencing) - @cindex @option{/WARNINGS=NOIMPLICIT_DEREFERENCE} (@code{GNAT COMPILE}) - @cindex Implicit dereferencing - @cindex Dereferencing, implicit - This qualifier suppresses warnings for implicit deferences in - indexed components, slices, and selected components. - - @item /WARNINGS=ERROR (treat warnings as errors) - @cindex @option{/WARNINGS=ERROR} (@code{GNAT COMPILE}) - @cindex Warnings, treat as error - This qualifier causes warning messages to be treated as errors. - The warning string still appears, but the warning messages are counted - as errors, and prevent the generation of an object file. - - @item /WARNINGS=UNREFERENCED_FORMALS (activate warnings on unreferenced formals) - @cindex @option{/WARNINGS=UNREFERENCED_FORMALS} (@code{GNAT COMPILE}) - @cindex Formals, unreferenced - This qualifier causes a warning to be generated if a formal parameter - is not referenced in the body of the subprogram. This warning can - also be turned on using @option{/WARNINGS=OPTIONAL} or @option{/WARNINGS=UNUSED}. - - @item /WARNINGS=NOUNREFERENCED_FORMALS (suppress warnings on unreferenced formals) - @cindex @option{/WARNINGS=NOUNREFERENCED_FORMALS} (@code{GNAT COMPILE}) - This qualifier suppresses warnings for unreferenced formal - parameters. Note that the - combination @option{/WARNINGS=UNUSED} followed by @option{/WARNINGS=NOUNREFERENCED_FORMALS} has the - effect of warning on unreferenced entities other than subprogram - formals. - - @item /WARNINGS=HIDING (activate warnings on hiding) - @cindex @option{/WARNINGS=HIDING} (@code{GNAT COMPILE}) - @cindex Hiding of Declarations - This qualifier activates warnings on hiding declarations. - A declaration is considered hiding - if it is for a non-overloadable entity, and it declares an entity with the - same name as some other entity that is directly or use-visible. The default - is that such warnings are not generated. - Note that @option{/WARNINGS=OPTIONAL} does not affect the setting of this warning option. - - @item /WARNINGS=NOHIDING (suppress warnings on hiding) - @cindex @option{/WARNINGS=NOHIDING} (@code{GNAT COMPILE}) - This qualifier suppresses warnings on hiding declarations. - - @item /WARNINGS=IMPLEMENTATION (activate warnings on implementation units). - @cindex @option{/WARNINGS=IMPLEMENTATION} (@code{GNAT COMPILE}) - This qualifier activates warnings for a @code{with} of an internal GNAT - implementation unit, defined as any unit from the @code{Ada}, - @code{Interfaces}, @code{GNAT}, - @code{DEC}, or @code{System} - hierarchies that is not - documented in either the Ada Reference Manual or the GNAT - Programmer's Reference Manual. Such units are intended only - for internal implementation purposes and should not be @code{with}'ed - by user programs. The default is that such warnings are generated - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @item /WARNINGS=NOIMPLEMENTATION (disable warnings on implementation units). - @cindex @option{/WARNINGS=NOIMPLEMENTATION} (@code{GNAT COMPILE}) - This qualifier disables warnings for a @code{with} of an internal GNAT - implementation unit. - - @item /WARNINGS=ELABORATION (activate warnings on elaboration pragmas) - @cindex @option{/WARNINGS=ELABORATION} (@code{GNAT COMPILE}) - @cindex Elaboration, warnings - This qualifier activates warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. The default is that such warnings - are not generated. - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @item /WARNINGS=NOELABORATION (suppress warnings on elaboration pragmas) - @cindex @option{/WARNINGS=NOELABORATION} (@code{GNAT COMPILE}) - This qualifier suppresses warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. - - @item /WARNINGS=OVERLAYS (activate warnings on address clause overlays) - @cindex @option{/WARNINGS=OVERLAYS} (@code{GNAT COMPILE}) - @cindex Address Clauses, warnings - This qualifier activates warnings for possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. The default is that such warnings are generated. - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @item /WARNINGS=NOOVERLAYS (suppress warnings on address clause overlays) - @cindex @option{/WARNINGS=NOOVERLAYS} (@code{GNAT COMPILE}) - This qualifier suppresses warnings on possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. - - @item -gnatwp (activate warnings on ineffective pragma Inlines) - @cindex @option{-gnatwp} (@code{GNAT COMPILE}) - @cindex Inlining, warnings - This qualifier activates warnings for failure of front end inlining - (activated by @option{-gnatN}) to inline a particular call. There are - many reasons for not being able to inline a call, including most - commonly that the call is too complex to inline. - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @item -gnatwP (suppress warnings on ineffective pragma Inlines) - @cindex @option{-gnatwP} (@code{GNAT COMPILE}) - This qualifier suppresses warnings on ineffective pragma Inlines. If the - inlining mechanism cannot inline a call, it will simply ignore the - request silently. - - @item /WARNINGS=REDUNDANT (activate warnings on redundant constructs) - @cindex @option{/WARNINGS=REDUNDANT} (@code{GNAT COMPILE}) - This qualifier activates warnings for redundant constructs. The following - is the current list of constructs regarded as redundant: - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @itemize @bullet - @item - Assignment of an item to itself. - @item - Type conversion that converts an expression to its own type. - @item - Use of the attribute @code{Base} where @code{typ'Base} is the same - as @code{typ}. - @item - Use of pragma @code{Pack} when all components are placed by a record - representation clause. - @end itemize - - @item /WARNINGS=NOREDUNDANT (suppress warnings on redundant constructs) - @cindex @option{/WARNINGS=NOREDUNDANT} (@code{GNAT COMPILE}) - This qualifier suppresses warnings for redundant constructs. - - @item /WARNINGS=SUPPRESS (suppress all warnings) - @cindex @option{/WARNINGS=SUPPRESS} (@code{GNAT COMPILE}) - This qualifier completely suppresses the - output of all warning messages from the GNAT front end. - Note that it does not suppress warnings from the @code{GNAT COMPILE} back end. - To suppress these back end warnings as well, use the qualifier @code{-w} - in addition to @option{/WARNINGS=SUPPRESS}. - - @item /WARNINGS=UNUSED (activate warnings on unused entities) - @cindex @option{/WARNINGS=UNUSED} (@code{GNAT COMPILE}) - This qualifier activates warnings to be generated for entities that - are defined but not referenced, and for units that are @code{with}'ed - and not - referenced. In the case of packages, a warning is also generated if - no entities in the package are referenced. This means that if the package - is referenced but the only references are in @code{use} - clauses or @code{renames} - declarations, a warning is still generated. A warning is also generated - for a generic package that is @code{with}'ed but never instantiated. - In the case where a package or subprogram body is compiled, and there - is a @code{with} on the corresponding spec - that is only referenced in the body, - a warning is also generated, noting that the - @code{with} can be moved to the body. The default is that - such warnings are not generated. - This qualifier also activates warnings on unreferenced formals - (it is includes the effect of @option{/WARNINGS=UNREFERENCED_FORMALS}). - This warning can also be turned on using @option{/WARNINGS=OPTIONAL}. - - @item /WARNINGS=NOUNUSED (suppress warnings on unused entities) - @cindex @option{/WARNINGS=NOUNUSED} (@code{GNAT COMPILE}) - This qualifier suppresses warnings for unused entities and packages. - It also turns off warnings on unreferenced formals (and thus includes - the effect of @option{/WARNINGS=NOUNREFERENCED_FORMALS}). - - @noindent - A string of warning parameters can be used in the same parameter. For example: - - @smallexample - -gnatwaLe - @end smallexample - - @noindent - Would turn on all optional warnings except for elaboration pragma warnings, - and also specify that warnings should be treated as errors. - - @item -w - @cindex @code{-w} - This qualifier suppresses warnings from the @code{GNAT COMPILE} backend. It may be - used in conjunction with @option{/WARNINGS=SUPPRESS} to ensure that all warnings - are suppressed during the entire compilation process. - - @end table - - @node Debugging and Assertion Control - @subsection Debugging and Assertion Control - - @table @code - @item /CHECKS=ASSERTIONS - @cindex @option{/CHECKS=ASSERTIONS} (@code{GNAT COMPILE}) - @findex Assert - @findex Debug - @cindex Assertions - - @noindent - The pragmas @code{Assert} and @code{Debug} normally have no effect and - are ignored. This qualifier, where @samp{a} stands for assert, causes - @code{Assert} and @code{Debug} pragmas to be activated. - - The pragmas have the form: - - @smallexample - @group - @cartouche - @b{pragma} Assert (@var{Boolean-expression} [, - @var{static-string-expression}]) - @b{pragma} Debug (@var{procedure call}) - @end cartouche - @end group - @end smallexample - - @noindent - The @code{Assert} pragma causes @var{Boolean-expression} to be tested. - If the result is @code{True}, the pragma has no effect (other than - possible side effects from evaluating the expression). If the result is - @code{False}, the exception @code{Assert_Failure} declared in the package - @code{System.Assertions} is - raised (passing @var{static-string-expression}, if present, as the - message associated with the exception). If no string expression is - given the default is a string giving the file name and line number - of the pragma. - - The @code{Debug} pragma causes @var{procedure} to be called. Note that - @code{pragma Debug} may appear within a declaration sequence, allowing - debugging procedures to be called between declarations. - - @item /DEBUG[=debug-level] - @itemx /NODEBUG - Specifies how much debugging information is to be included in - the resulting object file where 'debug-level' is one of the following: - @table @code - @item TRACEBACK (default) - Include both debugger symbol records and traceback - the object file. - @item ALL - Include both debugger symbol records and traceback in - object file. - @item NONE - Excludes both debugger symbol records and traceback - the object file. Same as /NODEBUG. - @item SYMBOLS - Includes only debugger symbol records in the object - file. Note that this doesn't include traceback information. - @end table - @end table - - @node Validity Checking - @subsection Validity Checking - @findex Validity Checking - - @noindent - The Ada 95 Reference Manual has specific requirements for checking - for invalid values. In particular, RM 13.9.1 requires that the - evaluation of invalid values (for example from unchecked conversions), - not result in erroneous execution. In GNAT, the result of such an - evaluation in normal default mode is to either use the value - unmodified, or to raise Constraint_Error in those cases where use - of the unmodified value would cause erroneous execution. The cases - where unmodified values might lead to erroneous execution are case - statements (where a wild jump might result from an invalid value), - and subscripts on the left hand side (where memory corruption could - occur as a result of an invalid value). - - The @option{-gnatVx} qualifier allows more control over the validity checking - mode. The @code{x} argument here is a string of letters which control which - validity checks are performed in addition to the default checks described - above. - - @itemize @bullet - @item - @option{-gnatVc} Validity checks for copies - - The right hand side of assignments, and the initializing values of - object declarations are validity checked. - - @item - @option{/VALIDITY_CHECKING=RM} Default (RM) validity checks - - Some validity checks are done by default following normal Ada semantics - (RM 13.9.1 (9-11)). - A check is done in case statements that the expression is within the range - of the subtype. If it is not, Constraint_Error is raised. - For assignments to array components, a check is done that the expression used - as index is within the range. If it is not, Constraint_Error is raised. - Both these validity checks may be turned off using qualifier @option{-gnatVD}. - They are turned on by default. If @option{-gnatVD} is specified, a subsequent - qualifier @option{/VALIDITY_CHECKING=RM} will leave the checks turned on. - Qualifier @option{-gnatVD} should be used only if you are sure that all such - expressions have valid values. If you use this qualifier and invalid values - are present, then the program is erroneous, and wild jumps or memory - overwriting may occur. - - @item - @option{-gnatVi} Validity checks for @code{in} mode parameters - - Arguments for parameters of mode @code{in} are validity checked in function - and procedure calls at the point of call. - - @item - @option{-gnatVm} Validity checks for @code{in out} mode parameters - - Arguments for parameters of mode @code{in out} are validity checked in - procedure calls at the point of call. The @code{'m'} here stands for - modify, since this concerns parameters that can be modified by the call. - Note that there is no specific option to test @code{out} parameters, - but any reference within the subprogram will be tested in the usual - manner, and if an invalid value is copied back, any reference to it - will be subject to validity checking. - - @item - @option{-gnatVo} Validity checks for operator and attribute operands - - Arguments for predefined operators and attributes are validity checked. - This includes all operators in package @code{Standard}, - the shift operators defined as intrinsic in package @code{Interfaces} - and operands for attributes such as @code{Pos}. - - @item - @option{-gnatVr} Validity checks for function returns - - The expression in @code{return} statements in functions is validity - checked. - - @item - @option{-gnatVs} Validity checks for subscripts - - All subscripts expressions are checked for validity, whether they appear - on the right side or left side (in default mode only left side subscripts - are validity checked). - - @item - @option{-gnatVt} Validity checks for tests - - Expressions used as conditions in @code{if}, @code{while} or @code{exit} - statements are checked, as well as guard expressions in entry calls. - - @item - @option{/VALIDITY_CHECKING=FULL} Validity checks for floating-point values - - In the absence of this qualifier, validity checking occurs only for discrete - values. If @option{/VALIDITY_CHECKING=FULL} is specified, then validity checking also applies - for floating-point values, and NaN's and infinities are considered invalid, - as well as out of range values for constrained types. Note that this means - that standard @code{IEEE} infinity mode is not allowed. The exact contexts - in which floating-point values are checked depends on the setting of other - options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does - not matter) specifies that floating-point parameters of mode @code{in} should - be validity checked. - - @item - @option{-gnatVa} All validity checks - - All the above validity checks are turned on. That is @option{-gnatVa} is - equivalent to @code{gnatVcdfimorst}. - - @item - @option{-gnatVn} No validity checks - - This qualifier turns off all validity checking, including the default checking - for case statements and left hand side subscripts. Note that the use of - the qualifier @option{/CHECKS=SUPPRESS_ALL} supresses all run-time checks, including - validity checks, and thus implies @option{-gnatVn}. - - @end itemize - - The @option{/VALIDITY_CHECKING} qualifier may be followed by a string of letters to turn on - a series of validity checking options. For example, @option{-gnatVcr} specifies - that in addition to the default validity checking, copies and function - return expressions be validity checked. In order to make it easier to specify - a set of options, the upper case letters @code{CDFIMORST} may be used to turn - off the corresponding lower case option, so for example @option{-gnatVaM} turns - on all validity checking options except for checking of @code{in out} - procedure arguments. - - The specification of additional validity checking generates extra code (and - in the case of @option{-gnatva} the code expansion can be substantial. However, - these additional checks can be very useful in smoking out cases of - uninitialized variables, incorrect use of unchecked conversion, and other - errors leading to invalid values. The use of pragma @code{Initialize_Scalars} - is useful in conjunction with the extra validity checking, since this - ensures that wherever possible uninitialized variables have invalid values. - - See also the pragma @code{Validity_Checks} which allows modification of - the validity checking mode at the program source level, and also allows for - temporary disabling of validity checks. - - @node Style Checking - @subsection Style Checking - @findex Style checking - - @noindent - The /STYLE=(@var{option},@var{option},..) qualifier causes the compiler to - enforce specified style rules. A limited set of style rules has been used - in writing the GNAT sources themselves. This qualifier allows user programs - to activate all or some of these checks. If the source program fails a - specified style check, an appropriate warning message is given, preceded by - the character sequence "(style)". - (OPTION,OPTION,..) is a sequence of keywords - indicating the particular style - checks to be performed. The following checks are defined: - - @table @code - @item 1-9 (specify indentation level) - If a digit from 1-9 appears in the string after @option{/STYLE=} then proper - indentation is checked, with the digit indicating the indentation level - required. The general style of required indentation is as specified by - the examples in the Ada Reference Manual. Full line comments must be - aligned with the @code{--} starting on a column that is a multiple of - the alignment level. - - @item ATTRIBUTE (check attribute casing) - If the word ATTRIBUTE appears in the string after @option{/STYLE=} then - attribute names, including the case of keywords such as @code{digits} - used as attributes names, must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item BLANKS (blanks not allowed at statement end) - If the word BLANKS appears in the string after @option{/STYLE=} then - trailing blanks are not allowed at the end of statements. The purpose of this - rule, together with h (no horizontal tabs), is to enforce a canonical format - for the use of blanks to separate source tokens. - - @item COMMENTS (check comments) - If the word COMMENTS appears in the string after @option{/STYLE=} then - comments must meet the following set of rules: - - @itemize @bullet - - @item - The "--" that starts the column must either start in column one, or else - at least one blank must precede this sequence. - - @item - Comments that follow other tokens on a line must have at least one blank - following the "--" at the start of the comment. - - @item - Full line comments must have two blanks following the "--" that starts - the comment, with the following exceptions. - - @item - A line consisting only of the "--" characters, possibly preceded by blanks - is permitted. - - @item - A comment starting with "--x" where x is a special character is permitted. - This alows proper processing of the output generated by specialized tools - including @code{GNAT PREPROCESS} (where --! is used) and the SPARK annnotation - language (where --# is used). For the purposes of this rule, a special - character is defined as being in one of the ASCII ranges - 16#21#..16#2F# or 16#3A#..16#3F#. - - @item - A line consisting entirely of minus signs, possibly preceded by blanks, is - permitted. This allows the construction of box comments where lines of minus - signs are used to form the top and bottom of the box. - - @item - If a comment starts and ends with "--" is permitted as long as at least - one blank follows the initial "--". Together with the preceding rule, - this allows the construction of box comments, as shown in the following - example: - @smallexample - --------------------------- - -- This is a box comment -- - -- with two text lines. -- - --------------------------- - @end smallexample - @end itemize - - @item END (check end/exit labels) - If the word END appears in the string after @option{/STYLE=} then - optional labels on @code{end} statements ending subprograms and on - @code{exit} statements exiting named loops, are required to be present. - - @item VTABS (no form feeds or vertical tabs) - If the word VTABS appears in the string after @option{/STYLE=} then - neither form feeds nor vertical tab characters are not permitted - in the source text. - - @item HTABS (no horizontal tabs) - If the word HTABS appears in the string after @option{/STYLE=} then - horizontal tab characters are not permitted in the source text. - Together with the b (no blanks at end of line) check, this - enforces a canonical form for the use of blanks to separate - source tokens. - - @item IF_THEN (check if-then layout) - If the word IF_THEN appears in the string after @option{/STYLE=}, - then the keyword @code{then} must appear either on the same - line as corresponding @code{if}, or on a line on its own, lined - up under the @code{if} with at least one non-blank line in between - containing all or part of the condition to be tested. - - @item KEYWORD (check keyword casing) - If the word KEYWORD appears in the string after @option{/STYLE=} then - all keywords must be in lower case (with the exception of keywords - such as @code{digits} used as attribute names to which this check - does not apply). - - @item LAYOUT (check layout) - If the word LAYOUT appears in the string after @option{/STYLE=} then - layout of statement and declaration constructs must follow the - recommendations in the Ada Reference Manual, as indicated by the - form of the syntax rules. For example an @code{else} keyword must - be lined up with the corresponding @code{if} keyword. - - There are two respects in which the style rule enforced by this check - option are more liberal than those in the Ada Reference Manual. First - in the case of record declarations, it is permissible to put the - @code{record} keyword on the same line as the @code{type} keyword, and - then the @code{end} in @code{end record} must line up under @code{type}. - For example, either of the following two layouts is acceptable: - - @smallexample - @group - @cartouche - @b{type} q @b{is record} - a : integer; - b : integer; - @b{end record}; - - @b{type} q @b{is} - @b{record} - a : integer; - b : integer; - @b{end record}; - @end cartouche - @end group - @end smallexample - - @noindent - Second, in the case of a block statement, a permitted alternative - is to put the block label on the same line as the @code{declare} or - @code{begin} keyword, and then line the @code{end} keyword up under - the block label. For example both the following are permitted: - - @smallexample - @group - @cartouche - Block : @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - - Block : - @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - @end cartouche - @end group - @end smallexample - - @noindent - The same alternative format is allowed for loops. For example, both of - the following are permitted: - - @smallexample - @group - @cartouche - Clear : @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - - Clear : - @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - @end cartouche - @end group - @end smallexample - - @item LINE_LENGTH (check maximum line length) - If the word LINE_LENGTH appears in the string after @option{/STYLE=} - then the length of source lines must not exceed 79 characters, including - any trailing blanks. The value of 79 allows convenient display on an - 80 character wide device or window, allowing for possible special - treatment of 80 character lines. - - @item MAX_LENGTH=nnn (set maximum line length) - If the sequence MAX_LENGTH=nnn, where nnn is a decimal number, appears in - the string after @option{/STYLE=} then the length of lines must not exceed the - given value. - - @item STANDARD_CASING (check casing of entities in Standard) - If the word STANDARD_CASING appears in the string - after @option{/STYLE=} then any identifier from Standard must be cased - to match the presentation in the Ada Reference Manual (for example, - @code{Integer} and @code{ASCII.NUL}). - - @item ORDERED_SUBPROGRAMS (check order of subprogram bodies) - If the word ORDERED_SUBPROGRAMS appears in the string - after @option{/STYLE=} then all subprogram bodies in a given scope - (e.g. a package body) must be in alphabetical order. The ordering - rule uses normal Ada rules for comparing strings, ignoring casing - of letters, except that if there is a trailing numeric suffix, then - the value of this suffix is used in the ordering (e.g. Junk2 comes - before Junk10). - - @item PRAGMA (check pragma casing) - If the word PRAGMA appears in the string after @option{/STYLE=} then - pragma names must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item REFERENCES (check references) - If the word REFERENCES appears in the string after @option{/STYLE=} - then all identifier references must be cased in the same way as the - corresponding declaration. No specific casing style is imposed on - identifiers. The only requirement is for consistency of references - with declarations. - - @item SPECS (check separate specs) - If the word SPECS appears in the string after @option{/STYLE=} then - separate declarations ("specs") are required for subprograms (a - body is not allowed to serve as its own declaration). The only - exception is that parameterless library level procedures are - not required to have a separate declaration. This exception covers - the most frequent form of main program procedures. - - @item TOKEN (check token spacing) - If the word TOKEN appears in the string after @option{/STYLE=} then - the following token spacing rules are enforced: - - @itemize @bullet - - @item - The keywords @code{abs} and @code{not} must be followed by a space. - - @item - The token @code{=>} must be surrounded by spaces. - - @item - The token @code{<>} must be preceded by a space or a left parenthesis. - - @item - Binary operators other than @code{**} must be surrounded by spaces. - There is no restriction on the layout of the @code{**} binary operator. - - @item - Colon must be surrounded by spaces. - - @item - Colon-equal (assignment) must be surrounded by spaces. - - @item - Comma must be the first non-blank character on the line, or be - immediately preceded by a non-blank character, and must be followed - by a space. - - @item - If the token preceding a left paren ends with a letter or digit, then - a space must separate the two tokens. - - @item - A right parenthesis must either be the first non-blank character on - a line, or it must be preceded by a non-blank character. - - @item - A semicolon must not be preceded by a space, and must not be followed by - a non-blank character. - - @item - A unary plus or minus may not be followed by a space. - - @item - A vertical bar must be surrounded by spaces. - @end itemize - - @noindent - In the above rules, appearing in column one is always permitted, that is, - counts as meeting either a requirement for a required preceding space, - or as meeting a requirement for no preceding space. - - Appearing at the end of a line is also always permitted, that is, counts - as meeting either a requirement for a following space, or as meeting - a requirement for no following space. - - @end table - - @noindent - If any of these style rules is violated, a message is generated giving - details on the violation. The initial characters of such messages are - always "(style)". Note that these messages are treated as warning - messages, so they normally do not prevent the generation of an object - file. The @option{/WARNINGS=ERROR} qualifier can be used to treat warning messages, - including style messages, as fatal errors. - - @noindent - The qualifier - /STYLE_CHECKS=ALL_BUILTIN - is equivalent to all checking - options enabled with - the exception of ORDERED_SUBPROGRAMS, - with an indentation level of 3. This is the standard - checking option that is used for the GNAT sources. - - @node Run-Time Checks - @subsection Run-Time Checks - @cindex Division by zero - @cindex Access before elaboration - @cindex Checks, division by zero - @cindex Checks, access before elaboration - - @noindent - If you compile with the default options, GNAT will insert many run-time - checks into the compiled code, including code that performs range - checking against constraints, but not arithmetic overflow checking for - integer operations (including division by zero) or checks for access - before elaboration on subprogram calls. All other run-time checks, as - required by the Ada 95 Reference Manual, are generated by default. - The following @code{GNAT COMPILE} qualifiers refine this default behavior: - - @table @code - @item /CHECKS=SUPPRESS_ALL - @cindex @option{/CHECKS=SUPPRESS_ALL} (@code{GNAT COMPILE}) - @cindex Suppressing checks - @cindex Checks, suppressing - @findex Suppress - Suppress all run-time checks as though @code{pragma Suppress (all_checks}) - had been present in the source. Validity checks are also suppressed (in - other words @option{/CHECKS=SUPPRESS_ALL} also implies @option{-gnatVn}. - Use this qualifier to improve the performance - of the code at the expense of safety in the presence of invalid data or - program bugs. - - @item /CHECKS=OVERFLOW - @cindex @option{/CHECKS=OVERFLOW} (@code{GNAT COMPILE}) - @cindex Overflow checks - @cindex Check, overflow - Enables overflow checking for integer operations. - This causes GNAT to generate slower and larger executable - programs by adding code to check for overflow (resulting in raising - @code{Constraint_Error} as required by standard Ada - semantics). These overflow checks correspond to situations in which - the true value of the result of an operation may be outside the base - range of the result type. The following example shows the distinction: - - @smallexample - X1 : Integer := Integer'Last; - X2 : Integer range 1 .. 5 := 5; - ... - X1 := X1 + 1; -- @option{/CHECKS=OVERFLOW} required to catch the Constraint_Error - X2 := X2 + 1; -- range check, @option{/CHECKS=OVERFLOW} has no effect here - @end smallexample - - @noindent - Here the first addition results in a value that is outside the base range - of Integer, and hence requires an overflow check for detection of the - constraint error. The second increment operation results in a violation - of the explicit range constraint, and such range checks are always - performed. Basically the compiler can assume that in the absence of - the @option{/CHECKS=OVERFLOW} qualifier that any value of type @code{xxx} is - in range of the base type of @code{xxx}. - - @findex Machine_Overflows - Note that the @option{/CHECKS=OVERFLOW} qualifier does not affect the code generated - for any floating-point operations; it applies only to integer - semantics). - For floating-point, GNAT has the @code{Machine_Overflows} - attribute set to @code{False} and the normal mode of operation is to - generate IEEE NaN and infinite values on overflow or invalid operations - (such as dividing 0.0 by 0.0). - - The reason that we distinguish overflow checking from other kinds of - range constraint checking is that a failure of an overflow check can - generate an incorrect value, but cannot cause erroneous behavior. This - is unlike the situation with a constraint check on an array subscript, - where failure to perform the check can result in random memory description, - or the range check on a case statement, where failure to perform the check - can cause a wild jump. - - Note again that @option{/CHECKS=OVERFLOW} is off by default, so overflow checking is - not performed in default mode. This means that out of the box, with the - default settings, GNAT does not do all the checks expected from the - language description in the Ada Reference Manual. If you want all constraint - checks to be performed, as described in this Manual, then you must - explicitly use the /CHECKS=OVERFLOW qualifier either on the @code{GNAT MAKE} or - @code{GNAT COMPILE} command. - - @item /CHECKS=ELABORATION - @cindex @option{/CHECKS=ELABORATION} (@code{GNAT COMPILE}) - @cindex Elaboration checks - @cindex Check, elaboration - Enables dynamic checks for access-before-elaboration - on subprogram calls and generic instantiations. - For full details of the effect and use of this qualifier, - @xref{Compiling Using GNAT COMPILE}. - @end table - - @findex Unsuppress - @noindent - The setting of these qualifiers only controls the default setting of the - checks. You may modify them using either @code{Suppress} (to remove - checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in - the program source. - - @node Stack Overflow Checking - @subsection Stack Overflow Checking - @cindex Stack Overflow Checking - @cindex -fstack-check - - @noindent - For most operating systems, @code{GNAT COMPILE} does not perform stack overflow - checking by default. This means that if the main environment task or - some other task exceeds the available stack space, then unpredictable - behavior will occur. - - To activate stack checking, compile all units with the GNAT COMPILE option - @code{-fstack-check}. For example: - - @smallexample - GNAT COMPILE -fstack-check PACKAGE1.ADB - @end smallexample - - @noindent - Units compiled with this option will generate extra instructions to check - that any use of the stack (for procedure calls or for declaring local - variables in declare blocks) do not exceed the available stack space. - If the space is exceeded, then a @code{Storage_Error} exception is raised. - - For declared tasks, the stack size is always controlled by the size - given in an applicable @code{Storage_Size} pragma (or is set to - the default size if no pragma is used. - - For the environment task, the stack size depends on - system defaults and is unknown to the compiler. The stack - may even dynamically grow on some systems, precluding the - normal Ada semantics for stack overflow. In the worst case, - unbounded stack usage, causes unbounded stack expansion - resulting in the system running out of virtual memory. - - The stack checking may still work correctly if a fixed - size stack is allocated, but this cannot be guaranteed. - To ensure that a clean exception is signalled for stack - overflow, set the environment variable - @code{GNAT_STACK_LIMIT} to indicate the maximum - stack area that can be used, as in: - @cindex GNAT_STACK_LIMIT - - @smallexample - SET GNAT_STACK_LIMIT 1600 - @end smallexample - - @noindent - The limit is given in kilobytes, so the above declaration would - set the stack limit of the environment task to 1.6 megabytes. - Note that the only purpose of this usage is to limit the amount - of stack used by the environment task. If it is necessary to - increase the amount of stack for the environment task, then this - is an operating systems issue, and must be addressed with the - appropriate operating systems commands. - - @node Run-Time Control - @subsection Run-Time Control - - @table @code - @item -gnatT nnn - @cindex @option{-gnatT} (@code{GNAT COMPILE}) - @cindex Time Slicing - - @noindent - The @code{gnatT} qualifier can be used to specify the time-slicing value - to be used for task switching between equal priority tasks. The value - @code{nnn} is given in microseconds as a decimal integer. - - Setting the time-slicing value is only effective if the underlying thread - control system can accommodate time slicing. Check the documentation of - your operating system for details. Note that the time-slicing value can - also be set by use of pragma @code{Time_Slice} or by use of the - @code{t} qualifier in the GNAT BIND step. The pragma overrides a command - line argument if both are present, and the @code{t} qualifier for GNAT BIND - overrides both the pragma and the @code{GNAT COMPILE} command line qualifier. - @end table - - @node Using GNAT COMPILE for Syntax Checking - @subsection Using @code{GNAT COMPILE} for Syntax Checking - @table @code - @item /SYNTAX_ONLY - @cindex @option{/SYNTAX_ONLY} (@code{GNAT COMPILE}) - - Run GNAT in syntax checking only mode. For - example, the command - - @smallexample - $ GNAT COMPILE /SYNTAX_ONLY X.ADB - @end smallexample - - @noindent - compiles file @file{X.ADB} in syntax-check-only mode. You can check a - series of files in a single command - . - - You may use other qualifiers in conjunction with @option{/SYNTAX_ONLY}. In - particular, @option{/LIST} and @option{/REPORT_ERRORS=VERBOSE} are useful to control the - format of any generated error messages. - - The output is simply the error messages, if any. No object file or ALI - file is generated by a syntax-only compilation. Also, no units other - than the one specified are accessed. For example, if a unit @code{X} - @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax - check only mode does not access the source file containing unit - @code{Y}. - - @cindex Multiple units, syntax checking - Normally, GNAT allows only a single unit in a source file. However, this - restriction does not apply in syntax-check-only mode, and it is possible - to check a file containing multiple compilation units concatenated - together. This is primarily used by the @code{GNAT CHOP} utility - (@pxref{Renaming Files Using GNAT CHOP}). - @end table - - @node Using GNAT COMPILE for Semantic Checking - @subsection Using @code{GNAT COMPILE} for Semantic Checking - @table @code - @item /NOLOAD - @cindex @option{/NOLOAD} (@code{GNAT COMPILE}) - - Causes the compiler to operate in semantic check mode, - with full checking for all illegalities specified in the - Ada 95 Reference Manual, but without generation of any object code - (no object file is generated). - - Because dependent files must be accessed, you must follow the GNAT - semantic restrictions on file structuring to operate in this mode: - - @itemize @bullet - @item - The needed source files must be accessible - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item - Each file must contain only one compilation unit. - - @item - The file name and unit name must match (@pxref{File Naming Rules}). - @end itemize - - The output consists of error messages as appropriate. No object file is - generated. An @file{ALI} file is generated for use in the context of - cross-reference tools, but this file is marked as not being suitable - for binding (since no object file is generated). - The checking corresponds exactly to the notion of - legality in the Ada 95 Reference Manual. - - Any unit can be compiled in semantics-checking-only mode, including - units that would not normally be compiled (subunits, - and specifications where a separate body is present). - @end table - - @node Compiling Ada 83 Programs - @subsection Compiling Ada 83 Programs - @table @code - @cindex Ada 83 compatibility - @item /83 - @cindex @option{/83} (@code{GNAT COMPILE}) - @cindex ACVC, Ada 83 tests - - @noindent - Although GNAT is primarily an Ada 95 compiler, it accepts this qualifier to - specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify - this qualifier, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics - where this can be done easily. - It is not possible to guarantee this qualifier does a perfect - job; for example, some subtle tests, such as are - found in earlier ACVC tests (that have been removed from the ACVC suite for Ada - 95), may not compile correctly. However, for most purposes, using - this qualifier should help to ensure that programs that compile correctly - under the @option{/83} qualifier can be ported easily to an Ada 83 - compiler. This is the main use of the qualifier. - - With few exceptions (most notably the need to use @code{<>} on - @cindex Generic formal parameters - unconstrained generic formal parameters, the use of the new Ada 95 - keywords, and the use of packages - with optional bodies), it is not necessary to use the - @option{/83} qualifier when compiling Ada 83 programs, because, with rare - exceptions, Ada 95 is upwardly compatible with Ada 83. This - means that a correct Ada 83 program is usually also a correct Ada 95 - program. - - @end table - - @node Character Set Control - @subsection Character Set Control - @table @code - @item /IDENTIFIER_CHARACTER_SET=@var{c} - @cindex @code{/IDENTIFIER_CHARACTER_SET} (@code{GNAT COMPILE}) - - @noindent - Normally GNAT recognizes the Latin-1 character set in source program - identifiers, as described in the Ada 95 Reference Manual. - This qualifier causes - GNAT to recognize alternate character sets in identifiers. @var{c} is a - single character or word indicating the character set, as follows: - - @table @code - @item 1 - Latin-1 identifiers - - @item 2 - Latin-2 letters allowed in identifiers - - @item 3 - Latin-3 letters allowed in identifiers - - @item 4 - Latin-4 letters allowed in identifiers - - @item 5 - Latin-5 (Cyrillic) letters allowed in identifiers - - @item 9 - Latin-9 letters allowed in identifiers - - @item PC - IBM PC letters (code page 437) allowed in identifiers - - @item PC850 - IBM PC letters (code page 850) allowed in identifiers - - @item FULL_UPPER - Full upper-half codes allowed in identifiers - - @item NO_UPPER - No upper-half codes allowed in identifiers - - @item WIDE - Wide-character codes (that is, codes greater than 255) - allowed in identifiers - @end table - - @xref{Foreign Language Representation}, for full details on the - implementation of these character sets. - - @item /WIDE_CHARACTER_ENCODING=@var{e} - @cindex @code{/WIDE_CHARACTER_ENCODING} (@code{GNAT COMPILE}) - Specify the method of encoding for wide characters. - @var{e} is one of the following: - - @table @code - - @item HEX - Hex encoding (brackets coding also recognized) - - @item UPPER - Upper half encoding (brackets encoding also recognized) - - @item SHIFT_JIS - Shift/JIS encoding (brackets encoding also recognized) - - @item EUC - EUC encoding (brackets encoding also recognized) - - @item UTF8 - UTF-8 encoding (brackets encoding also recognized) - - @item BRACKETS - Brackets encoding only (default value) - @end table - For full details on the these encoding - methods see @xref{Wide Character Encodings}. - Note that brackets coding is always accepted, even if one of the other - options is specified, so for example @option{/WIDE_CHARACTER_ENCODING=UTF8} specifies that both - brackets and @code{UTF-8} encodings will be recognized. The units that are - with'ed directly or indirectly will be scanned using the specified - representation scheme, and so if one of the non-brackets scheme is - used, it must be used consistently throughout the program. However, - since brackets encoding is always recognized, it may be conveniently - used in standard libraries, allowing these libraries to be used with - any of the available coding schemes. - scheme. If no @option{/WIDE_CHARACTER_ENCODING=?} parameter is present, then the default - representation is Brackets encoding only. - - Note that the wide character representation that is specified (explicitly - or by default) for the main program also acts as the default encoding used - for Wide_Text_IO files if not specifically overridden by a WCEM form - parameter. - - @end table - @node File Naming Control - @subsection File Naming Control - - @table @code - @item /FILE_NAME_MAX_LENGTH=@var{n} - @cindex @option{/FILE_NAME_MAX_LENGTH} (@code{GNAT COMPILE}) - Activates file name "krunching". @var{n}, a decimal integer in the range - 1-999, indicates the maximum allowable length of a file name (not - including the @file{.ADS} or @file{.ADB} extension). The default is not - to enable file name krunching. - - For the source file naming rules, @xref{File Naming Rules}. - @end table - - @node Subprogram Inlining Control - @subsection Subprogram Inlining Control - - @table @code - @item /INLINE=PRAGMA - @cindex @option{/INLINE=PRAGMA} (@code{GNAT COMPILE}) - GNAT recognizes and processes @code{Inline} pragmas. However, for the - inlining to actually occur, optimization must be enabled. To enable - inlining across unit boundaries, this is, inlining a call in one unit of - a subprogram declared in a @code{with}'ed unit, you must also specify - this qualifier. - In the absence of this qualifier, GNAT does not attempt - inlining across units and does not need to access the bodies of - subprograms for which @code{pragma Inline} is specified if they are not - in the current unit. - - If you specify this qualifier the compiler will access these bodies, - creating an extra source dependency for the resulting object file, and - where possible, the call will be inlined. - For further details on when inlining is possible - see @xref{Inlining of Subprograms}. - - @item -gnatN - @cindex @option{-gnatN} (@code{GNAT COMPILE}) - The front end inlining activated by this qualifier is generally more extensive, - and quite often more effective than the standard @option{/INLINE=PRAGMA} inlining mode. - It will also generate additional dependencies. - - @end table - - @node Auxiliary Output Control - @subsection Auxiliary Output Control - - @table @code - @item /TREE_OUTPUT - @cindex @option{/TREE_OUTPUT} (@code{GNAT COMPILE}) - @cindex Writing internal trees - @cindex Internal trees, writing to file - Causes GNAT to write the internal tree for a unit to a file (with the - extension @file{.adt}. - This not normally required, but is used by separate analysis tools. - Typically - these tools do the necessary compilations automatically, so you should - not have to specify this qualifier in normal operation. - - @item /UNITS_LIST - @cindex @option{/UNITS_LIST} (@code{GNAT COMPILE}) - Print a list of units required by this compilation on @file{SYS$OUTPUT}. - The listing includes all units on which the unit being compiled depends - either directly or indirectly. - - @end table - - @node Debugging Control - @subsection Debugging Control - - @table @code - @cindex Debugging options - - @item /EXPAND_SOURCE - @cindex @option{/EXPAND_SOURCE} (@code{GNAT COMPILE}) - This qualifier causes the compiler to generate auxiliary output containing - a pseudo-source listing of the generated expanded code. Like most Ada - compilers, GNAT works by first transforming the high level Ada code into - lower level constructs. For example, tasking operations are transformed - into calls to the tasking run-time routines. A unique capability of GNAT - is to list this expanded code in a form very close to normal Ada source. - This is very useful in understanding the implications of various Ada - usage on the efficiency of the generated code. There are many cases in - Ada (e.g. the use of controlled types), where simple Ada statements can - generate a lot of run-time code. By using @option{/EXPAND_SOURCE} you can identify - these cases, and consider whether it may be desirable to modify the coding - approach to improve efficiency. - - The format of the output is very similar to standard Ada source, and is - easily understood by an Ada programmer. The following special syntactic - additions correspond to low level features used in the generated code that - do not have any exact analogies in pure Ada source form. The following - is a partial list of these special constructions. See the specification - of package @code{Sprint} in file @file{SPRINT.ADS} for a full list. - - @table @code - @item new @var{xxx} [storage_pool = @var{yyy}] - Shows the storage pool being used for an allocator. - - @item at end @var{procedure-name}; - Shows the finalization (cleanup) procedure for a scope. - - @item (if @var{expr} then @var{expr} else @var{expr}) - Conditional expression equivalent to the @code{x?y:z} construction in C. - - @item @var{target}^(@var{source}) - A conversion with floating-point truncation instead of rounding. - - @item @var{target}?(@var{source}) - A conversion that bypasses normal Ada semantic checking. In particular - enumeration types and fixed-point types are treated simply as integers. - - @item @var{target}?^(@var{source}) - Combines the above two cases. - - @item @var{x} #/ @var{y} - @itemx @var{x} #mod @var{y} - @itemx @var{x} #* @var{y} - @itemx @var{x} #rem @var{y} - A division or multiplication of fixed-point values which are treated as - integers without any kind of scaling. - - @item free @var{expr} [storage_pool = @var{xxx}] - Shows the storage pool associated with a @code{free} statement. - - @item freeze @var{typename} [@var{actions}] - Shows the point at which @var{typename} is frozen, with possible - associated actions to be performed at the freeze point. - - @item reference @var{itype} - Reference (and hence definition) to internal type @var{itype}. - - @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) - Intrinsic function call. - - @item @var{labelname} : label - Declaration of label @var{labelname}. - - @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr} - A multiple concatenation (same effect as @var{expr} & @var{expr} & - @var{expr}, but handled more efficiently). - - @item [constraint_error] - Raise the @code{Constraint_Error} exception. - - @item @var{expression}'reference - A pointer to the result of evaluating @var{expression}. - - @item @var{target-type}!(@var{source-expression}) - An unchecked conversion of @var{source-expression} to @var{target-type}. - - @item [@var{numerator}/@var{denominator}] - Used to represent internal real literals (that) have no exact - representation in base 2-16 (for example, the result of compile time - evaluation of the expression 1.0/27.0). - - @item /XDEBUG - @cindex @option{/XDEBUG} (@code{GNAT COMPILE}) - This qualifier is used in conjunction with @option{/EXPAND_SOURCE} to cause the expanded - source, as described above to be written to files with names - @file{XXX_DG}, where @file{xxx} is the normal file name, - for example, if the source file name is @file{HELLO.ADB}, - then a file @file{HELLO.ADB_DG} will be written. - The debugging information generated - by the @code{GNAT COMPILE} @code{/DEBUG} qualifier will refer to the generated - @file{XXX_DG} file. This allows you to do source level debugging using - the generated code which is sometimes useful for complex code, for example - to find out exactly which part of a complex construction raised an - exception. This qualifier also suppress generation of cross-reference - information (see /XREF=SUPPRESS). - - @item /COMPRESS_NAMES - @cindex @option{/CHECKS=ELABORATION} (@code{GNAT COMPILE}) - In the generated debugging information, and also in the case of long external - names, the compiler uses a compression mechanism if the name is very long. - This compression method uses a checksum, and avoids trouble on some operating - systems which have difficulty with very long names. The @option{/COMPRESS_NAMES} qualifier - forces this compression approach to be used on all external names and names - in the debugging information tables. This reduces the size of the generated - executable, at the expense of making the naming scheme more complex. The - compression only affects the qualification of the name. Thus a name in - the source: - - @smallexample - Very_Long_Package.Very_Long_Inner_Package.Var - @end smallexample - - @noindent - would normally appear in these tables as: - - @smallexample - very_long_package__very_long_inner_package__var - @end smallexample - - @noindent - but if the @option{/COMPRESS_NAMES} qualifier is used, then the name appears as - - @smallexample - XCb7e0c705__var - @end smallexample - - @noindent - Here b7e0c705 is a compressed encoding of the qualification prefix. - The GNAT Ada aware version of GDB understands these encoded prefixes, so if this - debugger is used, the encoding is largely hidden from the user of the compiler. - - @end table - - @item /REPRESENTATION_INFO[0|1|2|3][s] - @cindex @option{/REPRESENTATION_INFO} (@code{GNAT COMPILE}) - This qualifier controls output from the compiler of a listing showing - representation information for declared types and objects. For - @option{/REPRESENTATION_INFO=NONE}, no information is output (equivalent to omitting - the @option{/REPRESENTATION_INFO} qualifier). For @option{/REPRESENTATION_INFO=ARRAYS} (which is the default, - so @option{/REPRESENTATION_INFO} with no parameter has the same effect), size and alignment - information is listed for declared array and record types. For - @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information is listed for all - expression information for values that are computed at run time for - variant records. These symbolic expressions have a mostly obvious - format with #n being used to represent the value of the n'th - discriminant. See source files @file{REPINFO.ADS/adb} in the - @code{GNAT} sources for full detalis on the format of @option{/REPRESENTATION_INFO=SYMBOLIC} - output. If the qualifier is followed by an s (e.g. @option{-gnatR2s}), then - the output is to a file with the name @file{file_REP} where - file is the name of the corresponding source file. - - @item /XREF=SUPPRESS - @cindex @option{/XREF=SUPPRESS} (@code{GNAT COMPILE}) - Normally the compiler generates full cross-referencing information in - the @file{ALI} file. This information is used by a number of tools, - including @code{GNAT FIND} and @code{GNAT XREF}. The /XREF=SUPPRESS qualifier - suppresses this information. This saves some space and may slightly - speed up compilation, but means that these tools cannot be used. - @end table - - @node Units to Sources Mapping Files - @subsection Units to Sources Mapping Files - - @table @code - - @item -gnatem@var{path} - @cindex @option{-gnatem} (@code{GNAT COMPILE}) - A mapping file is a way to communicate to the compiler two mappings: - from unit names to file names (without any directory information) and from - file names to path names (with full directory information). These mappings - are used by the compiler to short-circuit the path search. - - A mapping file is a sequence of sets of three lines. In each set, - the first line is the unit name, in lower case, with "%s" appended for - specifications and "%b" appended for bodies; the second line is the file - name; and the third line is the path name. - - Example: - @smallexample - main%b - main.2.ADA - /gnat/project1/sources/main.2.ADA - @end smallexample - - When the qualifier @option{-gnatem} is specified, the compiler will create - in memory the two mappings from the specified file. If there is any problem - (non existent file, truncated file or duplicate entries), no mapping - will be created. - - Several @option{-gnatem} qualifiers may be specified; however, only the last - one on the command line will be taken into account. - - When using a project file, @code{GNAT MAKE} create a temporary mapping file - and communicates it to the compiler using this qualifier. - - @end table - - @node Search Paths and the Run-Time Library (RTL) - @section Search Paths and the Run-Time Library (RTL) - - @noindent - With the GNAT source-based library system, the compiler must be able to - find source files for units that are needed by the unit being compiled. - Search paths are used to guide this process. - - The compiler compiles one source file whose name must be given - explicitly on the command line. In other words, no searching is done - for this file. To find all other source files that are needed (the most - common being the specs of units), the compiler examines the following - directories, in the following order: - - @enumerate - @item - The directory containing the source file of the main unit being compiled - (the file name on the command line). - - @item - Each directory named by an @code{/SOURCE_SEARCH} qualifier given on the @code{GNAT COMPILE} - command line, in the order given. - - @item - @findex ADA_INCLUDE_PATH - Each of the directories listed in the value of the - @code{ADA_INCLUDE_PATH} logical name. - Normally, define this value as a logical name containing a comma separated - list of directory names. - - This variable can also be defined by means of an environment string - (an argument to the DEC C exec* set of functions). - - Logical Name: - @smallexample - DEFINE ANOTHER_PATH FOO:[BAG] - DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] - @end smallexample - - By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] - first, followed by the standard Ada 95 - libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE]. - If this is not redefined, the user will obtain the DEC Ada83 IO packages - (Text_IO, Sequential_IO, etc) - instead of the Ada95 packages. Thus, in order to get the Ada 95 - packages by default, ADA_INCLUDE_PATH must be redefined. - @item - The content of the "ada_source_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) source files. - @end enumerate - - @noindent - Specifying the qualifier @code{/NOCURRENT_DIRECTORY} - inhibits the use of the directory - containing the source file named in the command line. You can still - have this directory on your search path, but in this case it must be - explicitly requested with a @code{/SOURCE_SEARCH} qualifier. - - Specifying the qualifier @code{/NOSTD_INCLUDES} - inhibits the search of the default location for the GNAT Run Time - Library (RTL) source files. - - The compiler outputs its object files and ALI files in the current - working directory. - - @findex System.IO - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT RTL, together with the simple @code{System.IO} - package used in the "Hello World" example. The sources for these units - are needed by the compiler and are kept together in one directory. Not - all of the bodies are needed, but all of the sources are kept together - anyway. In a normal installation, you need not specify these directory - names when compiling or binding. Either the environment variables or - the built-in defaults cause these files to be found. - - In addition to the language-defined hierarchies (System, Ada and - Interfaces), the GNAT distribution provides a fourth hierarchy, - consisting of child units of GNAT. This is a collection of generally - useful routines. See the GNAT Reference Manual for further details. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Order of Compilation Issues - @section Order of Compilation Issues - - @noindent - If, in our earlier example, there was a spec for the @code{hello} - procedure, it would be contained in the file @file{HELLO.ADS}; yet this - file would not have to be explicitly compiled. This is the result of the - model we chose to implement library management. Some of the consequences - of this model are as follows: - - @itemize @bullet - @item - There is no point in compiling specs (except for package - specs with no bodies) because these are compiled as needed by clients. If - you attempt a useless compilation, you will receive an error message. - It is also useless to compile subunits because they are compiled as needed - by the parent. - - @item - There are no order of compilation requirements: performing a - compilation never obsoletes anything. The only way you can obsolete - something and require recompilations is to modify one of the - source files on which it depends. - - @item - There is no library as such, apart from the ALI files - (@pxref{The Ada Library Information Files}, for information on the format of these - files). For now we find it convenient to create separate ALI files, but - eventually the information therein may be incorporated into the object - file directly. - - @item - When you compile a unit, the source files for the specs of all units - that it @code{with}'s, all its subunits, and the bodies of any generics it - instantiates must be available (reachable by the search-paths mechanism - described above), or you will receive a fatal error message. - @end itemize - - @node Examples - @section Examples - - @noindent - The following are some typical Ada compilation command line examples: - - @table @code - @item $ GNAT COMPILE XYZ.ADB - Compile body in file @file{XYZ.ADB} with all default options. - - @item $ GNAT COMPILE /OPTIMIZE=ALL /CHECKS=ASSERTIONS XYZ-DEF.ADB - - Compile the child unit package in file @file{XYZ-DEF.ADB} with extensive - optimizations, and pragma @code{Assert}/@code{Debug} statements - enabled. - - @item $ GNAT COMPILE /NOLOAD ABC-DEF.ADB - Compile the subunit in file @file{ABC-DEF.ADB} in semantic-checking-only - mode. - @end table - - @node Binding Using GNAT BIND - @chapter Binding Using @code{GNAT BIND} - @findex GNAT BIND - - @menu - * Running GNAT BIND:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Qualifiers:: - * Command-Line Access:: - * Search Paths for GNAT BIND:: - * Examples of GNAT BIND Usage:: - @end menu - - @noindent - This chapter describes the GNAT binder, @code{GNAT BIND}, which is used - to bind compiled GNAT objects. The @code{GNAT BIND} program performs - four separate functions: - - @enumerate - @item - Checks that a program is consistent, in accordance with the rules in - Chapter 10 of the Ada 95 Reference Manual. In particular, error - messages are generated if a program uses inconsistent versions of a - given unit. - - @item - Checks that an acceptable order of elaboration exists for the program - and issues an error message if it cannot find an order of elaboration - that satisfies the rules in Chapter 10 of the Ada 95 Language Manual. - - @item - Generates a main program incorporating the given elaboration order. - This program is a small Ada package (body and spec) that - must be subsequently compiled - using the GNAT compiler. The necessary compilation step is usually - performed automatically by @code{GNAT LINK}. The two most important - functions of this program - are to call the elaboration routines of units in an appropriate order - and to call the main program. - - @item - Determines the set of object files required by the given main program. - This information is output in the forms of comments in the generated program, - to be read by the @code{GNAT LINK} utility used to link the Ada application. - @end enumerate - - @node Running GNAT BIND - @section Running @code{GNAT BIND} - - @noindent - The form of the @code{GNAT BIND} command is - - @smallexample - $ GNAT BIND [@var{qualifiers}] @var{mainprog}[.ALI] [@var{qualifiers}] - @end smallexample - - @noindent - where @var{mainprog}.ADB is the Ada file containing the main program - unit body. If no qualifiers are specified, @code{GNAT BIND} constructs an Ada - package in two files which names are - @file{B$@var{ada_main}.ADS}, and @file{B$@var{ada_main}.ADB}. - For example, if given the - parameter @samp{HELLO.ALI}, for a main program contained in file - @file{HELLO.ADB}, the binder output files would be @file{B~HELLO.ADS} - and @file{B~HELLO.ADB}. - - When doing consistency checking, the binder takes into consideration - any source files it can locate. For example, if the binder determines - that the given main program requires the package @code{Pack}, whose - @file{.ALI} - file is @file{PACK.ALI} and whose corresponding source spec file is - @file{PACK.ADS}, it attempts to locate the source file @file{PACK.ADS} - (using the same search path conventions as previously described for the - @code{GNAT COMPILE} command). If it can locate this source file, it checks that - the time stamps - or source checksums of the source and its references to in @file{ali} files - match. In other words, any @file{ali} files that mentions this spec must have - resulted from compiling this version of the source file (or in the case - where the source checksums match, a version close enough that the - difference does not matter). - - @cindex Source files, use by binder - The effect of this consistency checking, which includes source files, is - that the binder ensures that the program is consistent with the latest - version of the source files that can be located at bind time. Editing a - source file without compiling files that depend on the source file cause - error messages to be generated by the binder. - - For example, suppose you have a main program @file{HELLO.ADB} and a - package @code{P}, from file @file{P.ADS} and you perform the following - steps: - - @enumerate - @item - Enter @code{GNAT COMPILE HELLO.ADB} to compile the main program. - - @item - Enter @code{GNAT COMPILE P.ADS} to compile package @code{P}. - - @item - Edit file @file{P.ADS}. - - @item - Enter @code{GNAT BIND hello}. - @end enumerate - - At this point, the file @file{P.ALI} contains an out-of-date time stamp - because the file @file{P.ADS} has been edited. The attempt at binding - fails, and the binder generates the following error messages: - - @smallexample - error: "HELLO.ADB" must be recompiled ("P.ADS" has been modified) - error: "P.ADS" has been modified and must be recompiled - @end smallexample - - @noindent - Now both files must be recompiled as indicated, and then the bind can - succeed, generating a main program. You need not normally be concerned - with the contents of this file, but it is similar to the following which - is the binder file generated for a simple "hello world" program. - - @smallexample - @iftex - @leftskip=0cm - @end iftex - -- The package is called Ada_Main unless this name is actually used - -- as a unit name in the partition, in which case some other unique - -- name is used. - - with System; - package ada_main is - - Elab_Final_Code : Integer; - pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); - - -- The main program saves the parameters (argument count, - -- argument values, environment pointer) in global variables - -- for later access by other units including - -- Ada.Command_Line. - - gnat_argc : Integer; - gnat_argv : System.Address; - gnat_envp : System.Address; - - -- The actual variables are stored in a library routine. This - -- is useful for some shared library situations, where there - -- are problems if variables are not in the library. - - pragma Import (C, gnat_argc); - pragma Import (C, gnat_argv); - pragma Import (C, gnat_envp); - - -- The exit status is similarly an external location - - gnat_exit_status : Integer; - pragma Import (C, gnat_exit_status); - - GNAT_Version : constant String := - "GNAT Version: 3.15w (20010315)"; - pragma Export (C, GNAT_Version, "__gnat_version"); - - -- This is the generated adafinal routine that performs - -- finalization at the end of execution. In the case where - -- Ada is the main program, this main program makes a call - -- to adafinal at program termination. - - procedure adafinal; - pragma Export (C, adafinal, "adafinal"); - - -- This is the generated adainit routine that performs - -- initialization at the start of execution. In the case - -- where Ada is the main program, this main program makes - -- a call to adainit at program startup. - - procedure adainit; - pragma Export (C, adainit, "adainit"); - - -- This routine is called at the start of execution. It is - -- a dummy routine that is used by the debugger to breakpoint - -- at the start of execution. - - procedure Break_Start; - pragma Import (C, Break_Start, "__gnat_break_start"); - - -- This is the actual generated main program (it would be - -- suppressed if the no main program qualifier were used). As - -- required by standard system conventions, this program has - -- the external name main. - - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer; - pragma Export (C, main, "main"); - - -- The following set of constants give the version - -- identification values for every unit in the bound - -- partition. This identification is computed from all - -- dependent semantic units, and corresponds to the - -- string that would be returned by use of the - -- Body_Version or Version attributes. - - type Version_32 is mod 2 ** 32; - u00001 : constant Version_32 := 16#7880BEB3#; - u00002 : constant Version_32 := 16#0D24CBD0#; - u00003 : constant Version_32 := 16#3283DBEB#; - u00004 : constant Version_32 := 16#2359F9ED#; - u00005 : constant Version_32 := 16#664FB847#; - u00006 : constant Version_32 := 16#68E803DF#; - u00007 : constant Version_32 := 16#5572E604#; - u00008 : constant Version_32 := 16#46B173D8#; - u00009 : constant Version_32 := 16#156A40CF#; - u00010 : constant Version_32 := 16#033DABE0#; - u00011 : constant Version_32 := 16#6AB38FEA#; - u00012 : constant Version_32 := 16#22B6217D#; - u00013 : constant Version_32 := 16#68A22947#; - u00014 : constant Version_32 := 16#18CC4A56#; - u00015 : constant Version_32 := 16#08258E1B#; - u00016 : constant Version_32 := 16#367D5222#; - u00017 : constant Version_32 := 16#20C9ECA4#; - u00018 : constant Version_32 := 16#50D32CB6#; - u00019 : constant Version_32 := 16#39A8BB77#; - u00020 : constant Version_32 := 16#5CF8FA2B#; - u00021 : constant Version_32 := 16#2F1EB794#; - u00022 : constant Version_32 := 16#31AB6444#; - u00023 : constant Version_32 := 16#1574B6E9#; - u00024 : constant Version_32 := 16#5109C189#; - u00025 : constant Version_32 := 16#56D770CD#; - u00026 : constant Version_32 := 16#02F9DE3D#; - u00027 : constant Version_32 := 16#08AB6B2C#; - u00028 : constant Version_32 := 16#3FA37670#; - u00029 : constant Version_32 := 16#476457A0#; - u00030 : constant Version_32 := 16#731E1B6E#; - u00031 : constant Version_32 := 16#23C2E789#; - u00032 : constant Version_32 := 16#0F1BD6A1#; - u00033 : constant Version_32 := 16#7C25DE96#; - u00034 : constant Version_32 := 16#39ADFFA2#; - u00035 : constant Version_32 := 16#571DE3E7#; - u00036 : constant Version_32 := 16#5EB646AB#; - u00037 : constant Version_32 := 16#4249379B#; - u00038 : constant Version_32 := 16#0357E00A#; - u00039 : constant Version_32 := 16#3784FB72#; - u00040 : constant Version_32 := 16#2E723019#; - u00041 : constant Version_32 := 16#623358EA#; - u00042 : constant Version_32 := 16#107F9465#; - u00043 : constant Version_32 := 16#6843F68A#; - u00044 : constant Version_32 := 16#63305874#; - u00045 : constant Version_32 := 16#31E56CE1#; - u00046 : constant Version_32 := 16#02917970#; - u00047 : constant Version_32 := 16#6CCBA70E#; - u00048 : constant Version_32 := 16#41CD4204#; - u00049 : constant Version_32 := 16#572E3F58#; - u00050 : constant Version_32 := 16#20729FF5#; - u00051 : constant Version_32 := 16#1D4F93E8#; - u00052 : constant Version_32 := 16#30B2EC3D#; - u00053 : constant Version_32 := 16#34054F96#; - u00054 : constant Version_32 := 16#5A199860#; - u00055 : constant Version_32 := 16#0E7F912B#; - u00056 : constant Version_32 := 16#5760634A#; - u00057 : constant Version_32 := 16#5D851835#; - - -- The following Export pragmas export the version numbers - -- with symbolic names ending in B (for body) or S - -- (for spec) so that they can be located in a link. The - -- information provided here is sufficient to track down - -- the exact versions of units used in a given build. - - pragma Export (C, u00001, "helloB"); - pragma Export (C, u00002, "system__standard_libraryB"); - pragma Export (C, u00003, "system__standard_libraryS"); - pragma Export (C, u00004, "adaS"); - pragma Export (C, u00005, "ada__text_ioB"); - pragma Export (C, u00006, "ada__text_ioS"); - pragma Export (C, u00007, "ada__exceptionsB"); - pragma Export (C, u00008, "ada__exceptionsS"); - pragma Export (C, u00009, "gnatS"); - pragma Export (C, u00010, "gnat__heap_sort_aB"); - pragma Export (C, u00011, "gnat__heap_sort_aS"); - pragma Export (C, u00012, "systemS"); - pragma Export (C, u00013, "system__exception_tableB"); - pragma Export (C, u00014, "system__exception_tableS"); - pragma Export (C, u00015, "gnat__htableB"); - pragma Export (C, u00016, "gnat__htableS"); - pragma Export (C, u00017, "system__exceptionsS"); - pragma Export (C, u00018, "system__machine_state_operationsB"); - pragma Export (C, u00019, "system__machine_state_operationsS"); - pragma Export (C, u00020, "system__machine_codeS"); - pragma Export (C, u00021, "system__storage_elementsB"); - pragma Export (C, u00022, "system__storage_elementsS"); - pragma Export (C, u00023, "system__secondary_stackB"); - pragma Export (C, u00024, "system__secondary_stackS"); - pragma Export (C, u00025, "system__parametersB"); - pragma Export (C, u00026, "system__parametersS"); - pragma Export (C, u00027, "system__soft_linksB"); - pragma Export (C, u00028, "system__soft_linksS"); - pragma Export (C, u00029, "system__stack_checkingB"); - pragma Export (C, u00030, "system__stack_checkingS"); - pragma Export (C, u00031, "system__tracebackB"); - pragma Export (C, u00032, "system__tracebackS"); - pragma Export (C, u00033, "ada__streamsS"); - pragma Export (C, u00034, "ada__tagsB"); - pragma Export (C, u00035, "ada__tagsS"); - pragma Export (C, u00036, "system__string_opsB"); - pragma Export (C, u00037, "system__string_opsS"); - pragma Export (C, u00038, "interfacesS"); - pragma Export (C, u00039, "interfaces__c_streamsB"); - pragma Export (C, u00040, "interfaces__c_streamsS"); - pragma Export (C, u00041, "system__file_ioB"); - pragma Export (C, u00042, "system__file_ioS"); - pragma Export (C, u00043, "ada__finalizationB"); - pragma Export (C, u00044, "ada__finalizationS"); - pragma Export (C, u00045, "system__finalization_rootB"); - pragma Export (C, u00046, "system__finalization_rootS"); - pragma Export (C, u00047, "system__finalization_implementationB"); - pragma Export (C, u00048, "system__finalization_implementationS"); - pragma Export (C, u00049, "system__string_ops_concat_3B"); - pragma Export (C, u00050, "system__string_ops_concat_3S"); - pragma Export (C, u00051, "system__stream_attributesB"); - pragma Export (C, u00052, "system__stream_attributesS"); - pragma Export (C, u00053, "ada__io_exceptionsS"); - pragma Export (C, u00054, "system__unsigned_typesS"); - pragma Export (C, u00055, "system__file_control_blockS"); - pragma Export (C, u00056, "ada__finalization__list_controllerB"); - pragma Export (C, u00057, "ada__finalization__list_controllerS"); - - -- BEGIN ELABORATION ORDER - -- ada (spec) - -- gnat (spec) - -- gnat.heap_sort_a (spec) - -- gnat.heap_sort_a (body) - -- gnat.htable (spec) - -- gnat.htable (body) - -- interfaces (spec) - -- system (spec) - -- system.machine_code (spec) - -- system.parameters (spec) - -- system.parameters (body) - -- interfaces.c_streams (spec) - -- interfaces.c_streams (body) - -- system.standard_library (spec) - -- ada.exceptions (spec) - -- system.exception_table (spec) - -- system.exception_table (body) - -- ada.io_exceptions (spec) - -- system.exceptions (spec) - -- system.storage_elements (spec) - -- system.storage_elements (body) - -- system.machine_state_operations (spec) - -- system.machine_state_operations (body) - -- system.secondary_stack (spec) - -- system.stack_checking (spec) - -- system.soft_links (spec) - -- system.soft_links (body) - -- system.stack_checking (body) - -- system.secondary_stack (body) - -- system.standard_library (body) - -- system.string_ops (spec) - -- system.string_ops (body) - -- ada.tags (spec) - -- ada.tags (body) - -- ada.streams (spec) - -- system.finalization_root (spec) - -- system.finalization_root (body) - -- system.string_ops_concat_3 (spec) - -- system.string_ops_concat_3 (body) - -- system.traceback (spec) - -- system.traceback (body) - -- ada.exceptions (body) - -- system.unsigned_types (spec) - -- system.stream_attributes (spec) - -- system.stream_attributes (body) - -- system.finalization_implementation (spec) - -- system.finalization_implementation (body) - -- ada.finalization (spec) - -- ada.finalization (body) - -- ada.finalization.list_controller (spec) - -- ada.finalization.list_controller (body) - -- system.file_control_block (spec) - -- system.file_io (spec) - -- system.file_io (body) - -- ada.text_io (spec) - -- ada.text_io (body) - -- hello (body) - -- END ELABORATION ORDER - - end ada_main; - - -- The following source file name pragmas allow the generated file - -- names to be unique for different main programs. They are needed - -- since the package name will always be Ada_Main. - - pragma Source_File_Name (ada_main, Spec_File_Name => "B~HELLO.ADS"); - pragma Source_File_Name (ada_main, Body_File_Name => "B~HELLO.ADB"); - - -- Generated package body for Ada_Main starts here - - package body ada_main is - - -- The actual finalization is performed by calling the - -- library routine in System.Standard_Library.Adafinal - - procedure Do_Finalize; - pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); - - ------------- - -- adainit -- - ------------- - - @findex adainit - procedure adainit is - - -- These booleans are set to True once the associated unit has - -- been elaborated. It is also used to avoid elaborating the - -- same unit twice. - - E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E"); - E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E"); - E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E"); - E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E"); - E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E"); - E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E"); - E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E"); - E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E"); - E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E"); - E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E"); - E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E"); - E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E"); - E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E"); - E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E"); - E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E"); - E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E"); - E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E"); - - -- Set_Globals is a library routine that stores away the - -- value of the indicated set of global values in global - -- variables within the library. - - procedure Set_Globals - (Main_Priority : Integer; - Time_Slice_Value : Integer; - WC_Encoding : Character; - Locking_Policy : Character; - Queuing_Policy : Character; - Task_Dispatching_Policy : Character; - Adafinal : System.Address; - Unreserve_All_Interrupts : Integer; - Exception_Tracebacks : Integer); - @findex __gnat_set_globals - pragma Import (C, Set_Globals, "__gnat_set_globals"); - - -- SDP_Table_Build is a library routine used to build the - -- exception tables. See unit Ada.Exceptions in files - -- A-EXCEPT.ADS/adb for full details of how zero cost - -- exception handling works. This procedure, the call to - -- it, and the two following tables are all omitted if the - -- build is in longjmp/setjump exception mode. - - @findex SDP_Table_Build - @findex Zero Cost Exceptions - procedure SDP_Table_Build - (SDP_Addresses : System.Address; - SDP_Count : Natural; - Elab_Addresses : System.Address; - Elab_Addr_Count : Natural); - pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); - - -- Table of Unit_Exception_Table addresses. Used for zero - -- cost exception handling to build the top level table. - - ST : aliased constant array (1 .. 23) of System.Address := ( - Hello'UET_Address, - Ada.Text_Io'UET_Address, - Ada.Exceptions'UET_Address, - Gnat.Heap_Sort_A'UET_Address, - System.Exception_Table'UET_Address, - System.Machine_State_Operations'UET_Address, - System.Secondary_Stack'UET_Address, - System.Parameters'UET_Address, - System.Soft_Links'UET_Address, - System.Stack_Checking'UET_Address, - System.Traceback'UET_Address, - Ada.Streams'UET_Address, - Ada.Tags'UET_Address, - System.String_Ops'UET_Address, - Interfaces.C_Streams'UET_Address, - System.File_Io'UET_Address, - Ada.Finalization'UET_Address, - System.Finalization_Root'UET_Address, - System.Finalization_Implementation'UET_Address, - System.String_Ops_Concat_3'UET_Address, - System.Stream_Attributes'UET_Address, - System.File_Control_Block'UET_Address, - Ada.Finalization.List_Controller'UET_Address); - - -- Table of addresses of elaboration routines. Used for - -- zero cost exception handling to make sure these - -- addresses are included in the top level procedure - -- address table. - - EA : aliased constant array (1 .. 23) of System.Address := ( - adainit'Code_Address, - Do_Finalize'Code_Address, - Ada.Exceptions'Elab_Spec'Address, - System.Exceptions'Elab_Spec'Address, - Interfaces.C_Streams'Elab_Spec'Address, - System.Exception_Table'Elab_Body'Address, - Ada.Io_Exceptions'Elab_Spec'Address, - System.Stack_Checking'Elab_Spec'Address, - System.Soft_Links'Elab_Body'Address, - System.Secondary_Stack'Elab_Body'Address, - Ada.Tags'Elab_Spec'Address, - Ada.Tags'Elab_Body'Address, - Ada.Streams'Elab_Spec'Address, - System.Finalization_Root'Elab_Spec'Address, - Ada.Exceptions'Elab_Body'Address, - System.Finalization_Implementation'Elab_Spec'Address, - System.Finalization_Implementation'Elab_Body'Address, - Ada.Finalization'Elab_Spec'Address, - Ada.Finalization.List_Controller'Elab_Spec'Address, - System.File_Control_Block'Elab_Spec'Address, - System.File_Io'Elab_Body'Address, - Ada.Text_Io'Elab_Spec'Address, - Ada.Text_Io'Elab_Body'Address); - - -- Start of processing for adainit - - begin - - -- Call SDP_Table_Build to build the top level procedure - -- table for zero cost exception handling (omitted in - -- longjmp/setjump mode). - - SDP_Table_Build (ST'Address, 23, EA'Address, 23); - - -- Call Set_Globals to record various information for - -- this partition. The values are derived by the binder - -- from information stored in the ali files by the compiler. - - @findex __gnat_set_globals - Set_Globals - (Main_Priority => -1, - -- Priority of main program, -1 if no pragma Priority used - - Time_Slice_Value => -1, - -- Time slice from Time_Slice pragma, -1 if none used - - WC_Encoding => 'b', - -- Wide_Character encoding used, default is brackets - - Locking_Policy => ' ', - -- Locking_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Queuing_Policy => ' ', - -- Queuing_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Task_Dispatching_Policy => ' ', - -- Task_Dispatching_Policy used, default of space means - -- not specified, otherwise first character of the - -- policy name. - - Adafinal => System.Null_Address, - -- Address of Adafinal routine, not used anymore - - Unreserve_All_Interrupts => 0, - -- Set true if pragma Unreserve_All_Interrupts was used - - Exception_Tracebacks => 0); - -- Indicates if exception tracebacks are enabled - - Elab_Final_Code := 1; - - -- Now we have the elaboration calls for all units in the partition. - -- The Elab_Spec and Elab_Body attributes generate references to the - -- implicit elaboration procedures generated by the compiler for - -- each unit that requires elaboration. - - if not E040 then - Interfaces.C_Streams'Elab_Spec; - end if; - E040 := True; - if not E008 then - Ada.Exceptions'Elab_Spec; - end if; - if not E014 then - System.Exception_Table'Elab_Body; - E014 := True; - end if; - if not E053 then - Ada.Io_Exceptions'Elab_Spec; - E053 := True; - end if; - if not E017 then - System.Exceptions'Elab_Spec; - E017 := True; - end if; - if not E030 then - System.Stack_Checking'Elab_Spec; - end if; - if not E028 then - System.Soft_Links'Elab_Body; - E028 := True; - end if; - E030 := True; - if not E024 then - System.Secondary_Stack'Elab_Body; - E024 := True; - end if; - if not E035 then - Ada.Tags'Elab_Spec; - end if; - if not E035 then - Ada.Tags'Elab_Body; - E035 := True; - end if; - if not E033 then - Ada.Streams'Elab_Spec; - E033 := True; - end if; - if not E046 then - System.Finalization_Root'Elab_Spec; - end if; - E046 := True; - if not E008 then - Ada.Exceptions'Elab_Body; - E008 := True; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Spec; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Body; - E048 := True; - end if; - if not E044 then - Ada.Finalization'Elab_Spec; - end if; - E044 := True; - if not E057 then - Ada.Finalization.List_Controller'Elab_Spec; - end if; - E057 := True; - if not E055 then - System.File_Control_Block'Elab_Spec; - E055 := True; - end if; - if not E042 then - System.File_Io'Elab_Body; - E042 := True; - end if; - if not E006 then - Ada.Text_Io'Elab_Spec; - end if; - if not E006 then - Ada.Text_Io'Elab_Body; - E006 := True; - end if; - - Elab_Final_Code := 0; - end adainit; - - -------------- - -- adafinal -- - -------------- - - @findex adafinal - procedure adafinal is - begin - Do_Finalize; - end adafinal; - - ---------- - -- main -- - ---------- - - -- main is actually a function, as in the ANSI C standard, - -- defined to return the exit status. The three parameters - -- are the argument count, argument values and environment - -- pointer. - - @findex Main Program - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer - is - -- The initialize routine performs low level system - -- initialization using a standard library routine which - -- sets up signal handling and performs any other - -- required setup. The routine can be found in file - -- A-INIT.C. - - @findex __gnat_initialize - procedure initialize; - pragma Import (C, initialize, "__gnat_initialize"); - - -- The finalize routine performs low level system - -- finalization using a standard library routine. The - -- routine is found in file A-FINAL.C and in the standard - -- distribution is a dummy routine that does nothing, so - -- really this is a hook for special user finalization. - - @findex __gnat_finalize - procedure finalize; - pragma Import (C, finalize, "__gnat_finalize"); - - -- We get to the main program of the partition by using - -- pragma Import because if we try to with the unit and - -- call it Ada style, then not only do we waste time - -- recompiling it, but also, we don't really know the right - -- qualifiers (e.g. identifier character set) to be used - -- to compile it. - - procedure Ada_Main_Program; - pragma Import (Ada, Ada_Main_Program, "_ada_hello"); - - -- Start of processing for main - - begin - -- Save global variables - - gnat_argc := argc; - gnat_argv := argv; - gnat_envp := envp; - - -- Call low level system initialization - - Initialize; - - -- Call our generated Ada initialization routine - - adainit; - - -- This is the point at which we want the debugger to get - -- control - - Break_Start; - - -- Now we call the main program of the partition - - Ada_Main_Program; - - -- Perform Ada finalization - - adafinal; - - -- Perform low level system finalization - - Finalize; - - -- Return the proper exit status - return (gnat_exit_status); - end; - - -- This section is entirely comments, so it has no effect on the - -- compilation of the Ada_Main package. It provides the list of - -- object files and linker options, as well as some standard - -- libraries needed for the link. The GNAT LINK utility parses - -- this B~HELLO.ADB file to read these comment lines to generate - -- the appropriate command line arguments for the call to the - -- system linker. The BEGIN/END lines are used for sentinels for - -- this parsing operation. - - -- The exact file names will of course depend on the environment, - -- host/target and location of files on the host system. - - @findex Object file list - -- BEGIN Object file/option list - -- ./HELLO.OBJ - -- -L./ - -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ - -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a - -- END Object file/option list - - end ada_main; - - @end smallexample - - @noindent - The Ada code in the above example is exactly what is generated by the - binder. We have added comments to more clearly indicate the function - of each part of the generated @code{Ada_Main} package. - - The code is standard Ada in all respects, and can be processed by any - tools that handle Ada. In particular, it is possible to use the debugger - in Ada mode to debug the generated Ada_Main package. For example, suppose - that for reasons that you do not understand, your program is blowing up - during elaboration of the body of @code{Ada.Text_IO}. To chase this bug - down, you can place a breakpoint on the call: - - @smallexample - Ada.Text_Io'Elab_Body; - @end smallexample - - @noindent - and trace the elaboration routine for this package to find out where - the problem might be (more usually of course you would be debugging - elaboration code in your own application). - - @node Generating the Binder Program in C - @section Generating the Binder Program in C - @noindent - In most normal usage, the default mode of @code{GNAT BIND} which is to - generate the main package in Ada, as described in the previous section. - In particular, this means that any Ada programmer can read and understand - the generated main program. It can also be debugged just like any other - Ada code provided the @code{-g} qualifier is used for @code{GNAT BIND} - and @code{GNAT LINK}. - - However for some purposes it may be convenient to generate the main - program in C rather than Ada. This may for example be helpful when you - are generating a mixed language program with the main program in C. The - GNAT compiler itself is an example. The use of the @code{-C} qualifier - for both @code{GNAT BIND} and @code{GNAT LINK} will cause the program to - be generated in C (and compiled using the gnu C compiler). The - following shows the C code generated for the same "Hello World" - program: - - @smallexample - - #ifdef __STDC__ - #define PARAMS(paramlist) paramlist - #else - #define PARAMS(paramlist) () - #endif - - extern void __gnat_set_globals - PARAMS ((int, int, int, int, int, int, - void (*) PARAMS ((void)), int, int)); - extern void adafinal PARAMS ((void)); - extern void adainit PARAMS ((void)); - extern void system__standard_library__adafinal PARAMS ((void)); - extern int main PARAMS ((int, char **, char **)); - extern void exit PARAMS ((int)); - extern void __gnat_break_start PARAMS ((void)); - extern void _ada_hello PARAMS ((void)); - extern void __gnat_initialize PARAMS ((void)); - extern void __gnat_finalize PARAMS ((void)); - - extern void ada__exceptions___elabs PARAMS ((void)); - extern void system__exceptions___elabs PARAMS ((void)); - extern void interfaces__c_streams___elabs PARAMS ((void)); - extern void system__exception_table___elabb PARAMS ((void)); - extern void ada__io_exceptions___elabs PARAMS ((void)); - extern void system__stack_checking___elabs PARAMS ((void)); - extern void system__soft_links___elabb PARAMS ((void)); - extern void system__secondary_stack___elabb PARAMS ((void)); - extern void ada__tags___elabs PARAMS ((void)); - extern void ada__tags___elabb PARAMS ((void)); - extern void ada__streams___elabs PARAMS ((void)); - extern void system__finalization_root___elabs PARAMS ((void)); - extern void ada__exceptions___elabb PARAMS ((void)); - extern void system__finalization_implementation___elabs PARAMS ((void)); - extern void system__finalization_implementation___elabb PARAMS ((void)); - extern void ada__finalization___elabs PARAMS ((void)); - extern void ada__finalization__list_controller___elabs PARAMS ((void)); - extern void system__file_control_block___elabs PARAMS ((void)); - extern void system__file_io___elabb PARAMS ((void)); - extern void ada__text_io___elabs PARAMS ((void)); - extern void ada__text_io___elabb PARAMS ((void)); - - extern int __gnat_inside_elab_final_code; - - extern int gnat_argc; - extern char **gnat_argv; - extern char **gnat_envp; - extern int gnat_exit_status; - - char __gnat_version[] = "GNAT Version: 3.15w (20010315)"; - void adafinal () @{ - system__standard_library__adafinal (); - @} - - void adainit () - @{ - extern char ada__exceptions_E; - extern char system__exceptions_E; - extern char interfaces__c_streams_E; - extern char system__exception_table_E; - extern char ada__io_exceptions_E; - extern char system__secondary_stack_E; - extern char system__stack_checking_E; - extern char system__soft_links_E; - extern char ada__tags_E; - extern char ada__streams_E; - extern char system__finalization_root_E; - extern char system__finalization_implementation_E; - extern char ada__finalization_E; - extern char ada__finalization__list_controller_E; - extern char system__file_control_block_E; - extern char system__file_io_E; - extern char ada__text_io_E; - - extern void *__gnat_hello__SDP; - extern void *__gnat_ada__text_io__SDP; - extern void *__gnat_ada__exceptions__SDP; - extern void *__gnat_gnat__heap_sort_a__SDP; - extern void *__gnat_system__exception_table__SDP; - extern void *__gnat_system__machine_state_operations__SDP; - extern void *__gnat_system__secondary_stack__SDP; - extern void *__gnat_system__parameters__SDP; - extern void *__gnat_system__soft_links__SDP; - extern void *__gnat_system__stack_checking__SDP; - extern void *__gnat_system__traceback__SDP; - extern void *__gnat_ada__streams__SDP; - extern void *__gnat_ada__tags__SDP; - extern void *__gnat_system__string_ops__SDP; - extern void *__gnat_interfaces__c_streams__SDP; - extern void *__gnat_system__file_io__SDP; - extern void *__gnat_ada__finalization__SDP; - extern void *__gnat_system__finalization_root__SDP; - extern void *__gnat_system__finalization_implementation__SDP; - extern void *__gnat_system__string_ops_concat_3__SDP; - extern void *__gnat_system__stream_attributes__SDP; - extern void *__gnat_system__file_control_block__SDP; - extern void *__gnat_ada__finalization__list_controller__SDP; - - void **st[23] = @{ - &__gnat_hello__SDP, - &__gnat_ada__text_io__SDP, - &__gnat_ada__exceptions__SDP, - &__gnat_gnat__heap_sort_a__SDP, - &__gnat_system__exception_table__SDP, - &__gnat_system__machine_state_operations__SDP, - &__gnat_system__secondary_stack__SDP, - &__gnat_system__parameters__SDP, - &__gnat_system__soft_links__SDP, - &__gnat_system__stack_checking__SDP, - &__gnat_system__traceback__SDP, - &__gnat_ada__streams__SDP, - &__gnat_ada__tags__SDP, - &__gnat_system__string_ops__SDP, - &__gnat_interfaces__c_streams__SDP, - &__gnat_system__file_io__SDP, - &__gnat_ada__finalization__SDP, - &__gnat_system__finalization_root__SDP, - &__gnat_system__finalization_implementation__SDP, - &__gnat_system__string_ops_concat_3__SDP, - &__gnat_system__stream_attributes__SDP, - &__gnat_system__file_control_block__SDP, - &__gnat_ada__finalization__list_controller__SDP@}; - - extern void ada__exceptions___elabs (); - extern void system__exceptions___elabs (); - extern void interfaces__c_streams___elabs (); - extern void system__exception_table___elabb (); - extern void ada__io_exceptions___elabs (); - extern void system__stack_checking___elabs (); - extern void system__soft_links___elabb (); - extern void system__secondary_stack___elabb (); - extern void ada__tags___elabs (); - extern void ada__tags___elabb (); - extern void ada__streams___elabs (); - extern void system__finalization_root___elabs (); - extern void ada__exceptions___elabb (); - extern void system__finalization_implementation___elabs (); - extern void system__finalization_implementation___elabb (); - extern void ada__finalization___elabs (); - extern void ada__finalization__list_controller___elabs (); - extern void system__file_control_block___elabs (); - extern void system__file_io___elabb (); - extern void ada__text_io___elabs (); - extern void ada__text_io___elabb (); - - void (*ea[23]) () = @{ - adainit, - system__standard_library__adafinal, - ada__exceptions___elabs, - system__exceptions___elabs, - interfaces__c_streams___elabs, - system__exception_table___elabb, - ada__io_exceptions___elabs, - system__stack_checking___elabs, - system__soft_links___elabb, - system__secondary_stack___elabb, - ada__tags___elabs, - ada__tags___elabb, - ada__streams___elabs, - system__finalization_root___elabs, - ada__exceptions___elabb, - system__finalization_implementation___elabs, - system__finalization_implementation___elabb, - ada__finalization___elabs, - ada__finalization__list_controller___elabs, - system__file_control_block___elabs, - system__file_io___elabb, - ada__text_io___elabs, - ada__text_io___elabb@}; - - __gnat_SDP_Table_Build (&st, 23, ea, 23); - __gnat_set_globals ( - -1, /* Main_Priority */ - -1, /* Time_Slice_Value */ - 'b', /* WC_Encoding */ - ' ', /* Locking_Policy */ - ' ', /* Queuing_Policy */ - ' ', /* Tasking_Dispatching_Policy */ - 0, /* Finalization routine address, not used anymore */ - 0, /* Unreserve_All_Interrupts */ - 0); /* Exception_Tracebacks */ - - __gnat_inside_elab_final_code = 1; - - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabs (); - @} - if (system__exceptions_E == 0) @{ - system__exceptions___elabs (); - system__exceptions_E++; - @} - if (interfaces__c_streams_E == 0) @{ - interfaces__c_streams___elabs (); - @} - interfaces__c_streams_E = 1; - if (system__exception_table_E == 0) @{ - system__exception_table___elabb (); - system__exception_table_E++; - @} - if (ada__io_exceptions_E == 0) @{ - ada__io_exceptions___elabs (); - ada__io_exceptions_E++; - @} - if (system__stack_checking_E == 0) @{ - system__stack_checking___elabs (); - @} - if (system__soft_links_E == 0) @{ - system__soft_links___elabb (); - system__soft_links_E++; - @} - system__stack_checking_E = 1; - if (system__secondary_stack_E == 0) @{ - system__secondary_stack___elabb (); - system__secondary_stack_E++; - @} - if (ada__tags_E == 0) @{ - ada__tags___elabs (); - @} - if (ada__tags_E == 0) @{ - ada__tags___elabb (); - ada__tags_E++; - @} - if (ada__streams_E == 0) @{ - ada__streams___elabs (); - ada__streams_E++; - @} - if (system__finalization_root_E == 0) @{ - system__finalization_root___elabs (); - @} - system__finalization_root_E = 1; - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabb (); - ada__exceptions_E++; - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabs (); - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabb (); - system__finalization_implementation_E++; - @} - if (ada__finalization_E == 0) @{ - ada__finalization___elabs (); - @} - ada__finalization_E = 1; - if (ada__finalization__list_controller_E == 0) @{ - ada__finalization__list_controller___elabs (); - @} - ada__finalization__list_controller_E = 1; - if (system__file_control_block_E == 0) @{ - system__file_control_block___elabs (); - system__file_control_block_E++; - @} - if (system__file_io_E == 0) @{ - system__file_io___elabb (); - system__file_io_E++; - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabs (); - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabb (); - ada__text_io_E++; - @} - - __gnat_inside_elab_final_code = 0; - @} - int main (argc, argv, envp) - int argc; - char **argv; - char **envp; - @{ - gnat_argc = argc; - gnat_argv = argv; - gnat_envp = envp; - - __gnat_initialize (); - adainit (); - __gnat_break_start (); - - _ada_hello (); - - system__standard_library__adafinal (); - __gnat_finalize (); - exit (gnat_exit_status); - @} - unsigned helloB = 0x7880BEB3; - unsigned system__standard_libraryB = 0x0D24CBD0; - unsigned system__standard_libraryS = 0x3283DBEB; - unsigned adaS = 0x2359F9ED; - unsigned ada__text_ioB = 0x47C85FC4; - unsigned ada__text_ioS = 0x496FE45C; - unsigned ada__exceptionsB = 0x74F50187; - unsigned ada__exceptionsS = 0x6736945B; - unsigned gnatS = 0x156A40CF; - unsigned gnat__heap_sort_aB = 0x033DABE0; - unsigned gnat__heap_sort_aS = 0x6AB38FEA; - unsigned systemS = 0x0331C6FE; - unsigned system__exceptionsS = 0x20C9ECA4; - unsigned system__exception_tableB = 0x68A22947; - unsigned system__exception_tableS = 0x394BADD5; - unsigned gnat__htableB = 0x08258E1B; - unsigned gnat__htableS = 0x367D5222; - unsigned system__machine_state_operationsB = 0x4F3B7492; - unsigned system__machine_state_operationsS = 0x182F5CF4; - unsigned system__storage_elementsB = 0x2F1EB794; - unsigned system__storage_elementsS = 0x102C83C7; - unsigned system__secondary_stackB = 0x1574B6E9; - unsigned system__secondary_stackS = 0x708E260A; - unsigned system__parametersB = 0x56D770CD; - unsigned system__parametersS = 0x237E39BE; - unsigned system__soft_linksB = 0x08AB6B2C; - unsigned system__soft_linksS = 0x1E2491F3; - unsigned system__stack_checkingB = 0x476457A0; - unsigned system__stack_checkingS = 0x5299FCED; - unsigned system__tracebackB = 0x2971EBDE; - unsigned system__tracebackS = 0x2E9C3122; - unsigned ada__streamsS = 0x7C25DE96; - unsigned ada__tagsB = 0x39ADFFA2; - unsigned ada__tagsS = 0x769A0464; - unsigned system__string_opsB = 0x5EB646AB; - unsigned system__string_opsS = 0x63CED018; - unsigned interfacesS = 0x0357E00A; - unsigned interfaces__c_streamsB = 0x3784FB72; - unsigned interfaces__c_streamsS = 0x2E723019; - unsigned system__file_ioB = 0x623358EA; - unsigned system__file_ioS = 0x31F873E6; - unsigned ada__finalizationB = 0x6843F68A; - unsigned ada__finalizationS = 0x63305874; - unsigned system__finalization_rootB = 0x31E56CE1; - unsigned system__finalization_rootS = 0x23169EF3; - unsigned system__finalization_implementationB = 0x6CCBA70E; - unsigned system__finalization_implementationS = 0x604AA587; - unsigned system__string_ops_concat_3B = 0x572E3F58; - unsigned system__string_ops_concat_3S = 0x01F57876; - unsigned system__stream_attributesB = 0x1D4F93E8; - unsigned system__stream_attributesS = 0x30B2EC3D; - unsigned ada__io_exceptionsS = 0x34054F96; - unsigned system__unsigned_typesS = 0x7B9E7FE3; - unsigned system__file_control_blockS = 0x2FF876A8; - unsigned ada__finalization__list_controllerB = 0x5760634A; - unsigned ada__finalization__list_controllerS = 0x5D851835; - - /* BEGIN ELABORATION ORDER - ada (spec) - gnat (spec) - gnat.heap_sort_a (spec) - gnat.htable (spec) - gnat.htable (body) - interfaces (spec) - system (spec) - system.parameters (spec) - system.standard_library (spec) - ada.exceptions (spec) - system.exceptions (spec) - system.parameters (body) - gnat.heap_sort_a (body) - interfaces.c_streams (spec) - interfaces.c_streams (body) - system.exception_table (spec) - system.exception_table (body) - ada.io_exceptions (spec) - system.storage_elements (spec) - system.storage_elements (body) - system.machine_state_operations (spec) - system.machine_state_operations (body) - system.secondary_stack (spec) - system.stack_checking (spec) - system.soft_links (spec) - system.soft_links (body) - system.stack_checking (body) - system.secondary_stack (body) - system.standard_library (body) - system.string_ops (spec) - system.string_ops (body) - ada.tags (spec) - ada.tags (body) - ada.streams (spec) - system.finalization_root (spec) - system.finalization_root (body) - system.string_ops_concat_3 (spec) - system.string_ops_concat_3 (body) - system.traceback (spec) - system.traceback (body) - ada.exceptions (body) - system.unsigned_types (spec) - system.stream_attributes (spec) - system.stream_attributes (body) - system.finalization_implementation (spec) - system.finalization_implementation (body) - ada.finalization (spec) - ada.finalization (body) - ada.finalization.list_controller (spec) - ada.finalization.list_controller (body) - system.file_control_block (spec) - system.file_io (spec) - system.file_io (body) - ada.text_io (spec) - ada.text_io (body) - hello (body) - END ELABORATION ORDER */ - - /* BEGIN Object file/option list - ./HELLO.OBJ - -L./ - -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/ - /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a - -lexc - END Object file/option list */ - - @end smallexample - - @noindent - Here again, the C code is exactly what is generated by the binder. The - functions of the various parts of this code correspond in an obvious - manner with the commented Ada code shown in the example in the previous - section. - - @node Consistency-Checking Modes - @section Consistency-Checking Modes - - @noindent - As described in the previous section, by default @code{GNAT BIND} checks - that object files are consistent with one another and are consistent - with any source files it can locate. The following qualifiers control binder - access to sources. - - @table @code - @item /READ_SOURCES=ALL - @cindex @code{/READ_SOURCES=ALL} (@code{GNAT BIND}) - Require source files to be present. In this mode, the binder must be - able to locate all source files that are referenced, in order to check - their consistency. In normal mode, if a source file cannot be located it - is simply ignored. If you specify this qualifier, a missing source - file is an error. - - @item /READ_SOURCES=NONE - @cindex @code{/READ_SOURCES=NONE} (@code{GNAT BIND}) - Exclude source files. In this mode, the binder only checks that ALI - files are consistent with one another. Source files are not accessed. - The binder runs faster in this mode, and there is still a guarantee that - the resulting program is self-consistent. - If a source file has been edited since it was last compiled, and you - specify this qualifier, the binder will not detect that the object - file is out of date with respect to the source file. Note that this is the - mode that is automatically used by @code{GNAT MAKE} because in this - case the checking against sources has already been performed by - @code{GNAT MAKE} in the course of compilation (i.e. before binding). - - @item /READ_SOURCES=AVAILABLE - This is the default mode in which source files are checked if they are - available, and ignored if they are not available. - @end table - - @node Binder Error Message Control - @section Binder Error Message Control - - @noindent - The following qualifiers provide control over the generation of error - messages from the binder: - - @table @code - @item /REPORT_ERRORS=VERBOSE - @cindex @code{/REPORT_ERRORS=VERBOSE} (@code{GNAT BIND}) - Verbose mode. In the normal mode, brief error messages are generated to - @file{SYS$ERROR}. If this qualifier is present, a header is written - to @file{SYS$OUTPUT} and any error messages are directed to @file{SYS$OUTPUT}. - All that is written to @file{SYS$ERROR} is a brief summary message. - - @item /REPORT_ERRORS=BRIEF - @cindex @code{/REPORT_ERRORS=BRIEF} (@code{GNAT BIND}) - Generate brief error messages to @file{SYS$ERROR} even if verbose mode is - specified. This is relevant only when used with the - @code{/REPORT_ERRORS=VERBOSE} qualifier. - - - @item /WARNINGS=SUPPRESS - @cindex @code{/WARNINGS=SUPPRESS} (@code{GNAT BIND}) - @cindex Warnings - Suppress all warning messages. - - @item /WARNINGS=ERROR - @cindex @code{/WARNINGS=ERROR} (@code{GNAT BIND}) - Treat any warning messages as fatal errors. - - @item /WARNINGS=NORMAL - Standard mode with warnings generated, but warnings do not get treated - as errors. - - @item /NOTIME_STAMP_CHECK - @cindex @code{/NOTIME_STAMP_CHECK} (@code{GNAT BIND}) - @cindex Time stamp checks, in binder - @cindex Binder consistency checks - @cindex Consistency checks, in binder - The binder performs a number of consistency checks including: - - @itemize @bullet - @item - Check that time stamps of a given source unit are consistent - @item - Check that checksums of a given source unit are consistent - @item - Check that consistent versions of @code{GNAT} were used for compilation - @item - Check consistency of configuration pragmas as required - @end itemize - - @noindent - Normally failure of such checks, in accordance with the consistency - requirements of the Ada Reference Manual, causes error messages to be - generated which abort the binder and prevent the output of a binder - file and subsequent link to obtain an executable. - - The @code{/NOTIME_STAMP_CHECK} qualifier converts these error messages - into warnings, so that - binding and linking can continue to completion even in the presence of such - errors. The result may be a failed link (due to missing symbols), or a - non-functional executable which has undefined semantics. - @emph{This means that - @code{/NOTIME_STAMP_CHECK} should be used only in unusual situations, - with extreme care.} - @end table - - @node Elaboration Control - @section Elaboration Control - - @noindent - The following qualifiers provide additional control over the elaboration - order. For full details see @xref{Elaboration Order Handling in GNAT}. - - @table @code - @item /PESSIMISTIC_ELABORATION - @cindex @code{/PESSIMISTIC_ELABORATION} (@code{GNAT BIND}) - Normally the binder attempts to choose an elaboration order that is - likely to minimize the likelihood of an elaboration order error resulting - in raising a @code{Program_Error} exception. This qualifier reverses the - action of the binder, and requests that it deliberately choose an order - that is likely to maximize the likelihood of an elaboration error. - This is useful in ensuring portability and avoiding dependence on - accidental fortuitous elaboration ordering. - - Normally it only makes sense to use the @code{-p} qualifier if dynamic - elaboration checking is used (@option{/CHECKS=ELABORATION} qualifier used for compilation). - This is because in the default static elaboration mode, all necessary - @code{Elaborate_All} pragmas are implicitly inserted. These implicit - pragmas are still respected by the binder in @code{-p} mode, so a - safe elaboration order is assured. - @end table - - @node Output Control - @section Output Control - - @noindent - The following qualifiers allow additional control over the output - generated by the binder. - - @table @code - - @item /BIND_FILE=ADA - @cindex @code{/BIND_FILE=ADA} (@code{GNAT BIND}) - Generate binder program in Ada (default). The binder program is named - @file{B$@var{mainprog}.ADB} by default. This can be changed with - @code{-o} @code{GNAT BIND} option. - - @item /NOOUTPUT - @cindex @code{/NOOUTPUT} (@code{GNAT BIND}) - Check only. Do not generate the binder output file. In this mode the - binder performs all error checks but does not generate an output file. - - @item /BIND_FILE=C - @cindex @code{/BIND_FILE=C} (@code{GNAT BIND}) - Generate binder program in C. The binder program is named - @file{B_@var{mainprog}.C}. This can be changed with @code{-o} @code{GNAT BIND} - option. - - @item /ELABORATION_DEPENDENCIES - @cindex @code{/ELABORATION_DEPENDENCIES} (@code{GNAT BIND}) - Output complete list of elaboration-order dependencies, showing the - reason for each dependency. This output can be rather extensive but may - be useful in diagnosing problems with elaboration order. The output is - written to @file{SYS$OUTPUT}. - - @item /HELP - @cindex @code{/HELP} (@code{GNAT BIND}) - Output usage information. The output is written to @file{SYS$OUTPUT}. - - @item /LINKER_OPTION_LIST - @cindex @code{/LINKER_OPTION_LIST} (@code{GNAT BIND}) - Output linker options to @file{SYS$OUTPUT}. Includes library search paths, - contents of pragmas Ident and Linker_Options, and libraries added - by @code{GNAT BIND}. - - @item /ORDER_OF_ELABORATION - @cindex @code{/ORDER_OF_ELABORATION} (@code{GNAT BIND}) - Output chosen elaboration order. The output is written to @file{SYS$OUTPUT}. - - @item /OBJECT_LIST - @cindex @code{/OBJECT_LIST} (@code{GNAT BIND}) - Output full names of all the object files that must be linked to provide - the Ada component of the program. The output is written to @file{SYS$OUTPUT}. - This list includes the files explicitly supplied and referenced by the user - as well as implicitly referenced run-time unit files. The latter are - omitted if the corresponding units reside in shared libraries. The - directory names for the run-time units depend on the system configuration. - - @item /OUTPUT=@var{file} - @cindex @code{/OUTPUT} (@code{GNAT BIND}) - Set name of output file to @var{file} instead of the normal - @file{B$@var{mainprog}.ADB} default. Note that @var{file} denote the Ada - binder generated body filename. In C mode you would normally give - @var{file} an extension of @file{.C} because it will be a C source program. - Note that if this option is used, then linking must be done manually. - It is not possible to use GNAT LINK in this case, since it cannot locate - the binder file. - - @item /RESTRICTION_LIST - @cindex @code{/RESTRICTION_LIST} (@code{GNAT BIND}) - Generate list of @code{pragma Rerstrictions} that could be applied to - the current unit. This is useful for code audit purposes, and also may - be used to improve code generation in some cases. - - @end table - - @node Binding with Non-Ada Main Programs - @section Binding with Non-Ada Main Programs - - @noindent - In our description so far we have assumed that the main - program is in Ada, and that the task of the binder is to generate a - corresponding function @code{main} that invokes this Ada main - program. GNAT also supports the building of executable programs where - the main program is not in Ada, but some of the called routines are - written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). - The following qualifier is used in this situation: - - @table @code - @item /NOMAIN - @cindex @code{/NOMAIN} (@code{GNAT BIND}) - No main program. The main program is not in Ada. - @end table - - @noindent - In this case, most of the functions of the binder are still required, - but instead of generating a main program, the binder generates a file - containing the following callable routines: - - @table @code - @item adainit - @findex adainit - You must call this routine to initialize the Ada part of the program by - calling the necessary elaboration routines. A call to @code{adainit} is - required before the first call to an Ada subprogram. - - Note that it is assumed that the basic execution environment must be setup - to be appropriate for Ada execution at the point where the first Ada - subprogram is called. In particular, if the Ada code will do any - floating-point operations, then the FPU must be setup in an appropriate - manner. For the case of the x86, for example, full precision mode is - required. The procedure GNAT.Float_Control.Reset may be used to ensure - that the FPU is in the right state. - - @item adafinal - @findex adafinal - You must call this routine to perform any library-level finalization - required by the Ada subprograms. A call to @code{adafinal} is required - after the last call to an Ada subprogram, and before the program - terminates. - @end table - - @noindent - If the @code{/NOMAIN} qualifier - @cindex Binder, multiple input files - is given, more than one ALI file may appear on - the command line for @code{GNAT BIND}. The normal @dfn{closure} - calculation is performed for each of the specified units. Calculating - the closure means finding out the set of units involved by tracing - @code{with} references. The reason it is necessary to be able to - specify more than one ALI file is that a given program may invoke two or - more quite separate groups of Ada units. - - The binder takes the name of its output file from the last specified ALI - file, unless overridden by the use of the @code{/OUTPUT=file}. - The output is an Ada unit in source form that can - be compiled with GNAT unless the -C qualifier is used in which case the - output is a C source file, which must be compiled using the C compiler. - This compilation occurs automatically as part of the @code{GNAT LINK} - processing. - - Currently the GNAT run time requires a FPU using 80 bits mode - precision. Under targets where this is not the default it is required to - call GNAT.Float_Control.Reset before using floating point numbers (this - include float computation, float input and output) in the Ada code. A - side effect is that this could be the wrong mode for the foreign code - where floating point computation could be broken after this call. - - @node Binding Programs with No Main Subprogram - @section Binding Programs with No Main Subprogram - - @noindent - It is possible to have an Ada program which does not have a main - subprogram. This program will call the elaboration routines of all the - packages, then the finalization routines. - - The following qualifier is used to bind programs organized in this manner: - - @table @code - @item /ZERO_MAIN - @cindex @code{/ZERO_MAIN} (@code{GNAT BIND}) - Normally the binder checks that the unit name given on the command line - corresponds to a suitable main subprogram. When this qualifier is used, - a list of ALI files can be given, and the execution of the program - consists of elaboration of these units in an appropriate order. - @end table - - @node Summary of Binder Qualifiers - @section Summary of Binder Qualifiers - - @noindent - The following are the qualifiers available with @code{GNAT BIND}: - - @table @code - @item /OBJECT_SEARCH - Specify directory to be searched for ALI files. - - @item /SOURCE_SEARCH - Specify directory to be searched for source file. - - @item /BIND_FILE=ADA - Generate binder program in Ada (default) - - @item /REPORT_ERRORS=BRIEF - Generate brief messages to @file{SYS$ERROR} even if verbose mode set. - - @item /NOOUTPUT - Check only, no generation of binder output file. - - @item /BIND_FILE=C - Generate binder program in C - - @item /ELABORATION_DEPENDENCIES - Output complete list of elaboration-order dependencies. - - @item -E - Store tracebacks in exception occurrences when the target supports it. - This is the default with the zero cost exception mechanism. - This option is currently supported on the following targets: - all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. - See also the packages @code{GNAT.Traceback} and - @code{GNAT.Traceback.Symbolic} for more information. - Note that on x86 ports, you must not use @code{-fomit-frame-pointer} - @code{GNAT COMPILE} option. - - @item -h - Output usage (help) information - - @item /SEARCH - Specify directory to be searched for source and ALI files. - - @item /NOCURRENT_DIRECTORY - Do not look for sources in the current directory where @code{GNAT BIND} was - invoked, and do not look for ALI files in the directory containing the - ALI file named in the @code{GNAT BIND} command line. - - @item /ORDER_OF_ELABORATION - Output chosen elaboration order. - - @item -Lxxx - Binds the units for library building. In this case the adainit and - adafinal procedures (See @pxref{Binding with Non-Ada Main Programs}) - are renamed to xxxinit and xxxfinal. Implies -n. - - @item -Mxyz - Rename generated main program from main to xyz - - @item /ERROR_LIMIT=@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item /NOMAIN - No main program. - - @item /NOSTD_INCLUDES - Do not look for sources in the system default directory. - - @item /NOSTD_LIBRARIES - Do not look for library files in the system default directory. - - @item /RUNTIME_SYSTEM=@var{rts-path} - @cindex @code{/RUNTIME_SYSTEM} (@code{GNAT BIND}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{GNAT MAKE} flag (see @ref{Qualifiers for GNAT MAKE}). - - @item /OUTPUT=@var{file} - Name the output file @var{file} (default is @file{B$@var{xxx}.ADB}). - Note that if this option is used, then linking must be done manually, - GNAT LINK cannot be used. - - @item /OBJECT_LIST - Output object list. - - @item -p - Pessimistic (worst-case) elaboration order - - @item /READ_SOURCES=ALL - Require all source files to be present. - - - @item /NOTIME_STAMP_CHECK - Tolerate time stamp and other consistency errors - - @item -T@var{n} - Set the time slice value to n microseconds. A value of zero means no time - slicing and also indicates to the tasking run time to match as close as - possible to the annex D requirements of the RM. - - @item /REPORT_ERRORS=VERBOSE - Verbose mode. Write error messages, header, summary output to - @file{SYS$OUTPUT}. - - - @item /WARNINGS=NORMAL - Normal warnings mode. Warnings are issued but ignored - - @item /WARNINGS=SUPPRESS - All warning messages are suppressed - - @item /WARNINGS=ERROR - Warning messages are treated as fatal errors - - @item /READ_SOURCES=NONE - Exclude source files (check object consistency only). - - @item /READ_SOURCES=AVAILABLE - Default mode, in which sources are checked for consistency only if - they are available. - - @item /ZERO_MAIN - No main subprogram. - - @end table - - - @node Command-Line Access - @section Command-Line Access - - @noindent - The package @code{Ada.Command_Line} provides access to the command-line - arguments and program name. In order for this interface to operate - correctly, the two variables - - @smallexample - @group - @cartouche - int gnat_argc; - char **gnat_argv; - @end cartouche - @end group - @end smallexample - - @noindent - @findex gnat_argv - @findex gnat_argc - are declared in one of the GNAT library routines. These variables must - be set from the actual @code{argc} and @code{argv} values passed to the - main program. With no @code{/NOMAIN} present, @code{GNAT BIND} - generates the C main program to automatically set these variables. - If the @code{/NOMAIN} qualifier is used, there is no automatic way to - set these variables. If they are not set, the procedures in - @code{Ada.Command_Line} will not be available, and any attempt to use - them will raise @code{Constraint_Error}. If command line access is - required, your main program must set @code{gnat_argc} and - @code{gnat_argv} from the @code{argc} and @code{argv} values passed to - it. - - @node Search Paths for GNAT BIND - @section Search Paths for @code{GNAT BIND} - - @noindent - The binder takes the name of an ALI file as its argument and needs to - locate source files as well as other ALI files to verify object consistency. - - For source files, it follows exactly the same search rules as @code{GNAT COMPILE} - (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the - directories searched are: - - @enumerate - @item - The directory containing the ALI file named in the command line, unless - the qualifier @code{/NOCURRENT_DIRECTORY} is specified. - - @item - All directories specified by @code{/SEARCH} - qualifiers on the @code{GNAT BIND} - command line, in the order given. - - @item - @findex ADA_OBJECTS_PATH - Each of the directories listed in the value of the - @code{ADA_OBJECTS_PATH} logical name. - Normally, define this value as a logical name containing a comma separated - list of directory names. - - This variable can also be defined by means of an environment string - (an argument to the DEC C exec* set of functions). - - Logical Name: - @smallexample - DEFINE ANOTHER_PATH FOO:[BAG] - DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] - @end smallexample - - By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] - first, followed by the standard Ada 95 - libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB]. - If this is not redefined, the user will obtain the DEC Ada83 IO packages - (Text_IO, Sequential_IO, etc) - instead of the Ada95 packages. Thus, in order to get the Ada 95 - packages by default, ADA_OBJECTS_PATH must be redefined. - - @item - The content of the "ada_object_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) unless the qualifier @code{/NOSTD_LIBRARIES} is - specified. - @end enumerate - - @noindent - In the binder the qualifier @code{/SEARCH} - is used to specify both source and - library file paths. Use @code{/SOURCE_SEARCH} - instead if you want to specify - source paths only, and @code{/LIBRARY_SEARCH} - if you want to specify library paths - only. This means that for the binder - @code{/SEARCH=}@var{dir} is equivalent to - @code{/SOURCE_SEARCH=}@var{dir} - @code{/OBJECT_SEARCH=}@var{dir}. - The binder generates the bind file (a C language source file) in the - current working directory. - - @findex Ada - @findex System - @findex Interfaces - @findex GNAT - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT Run-Time Library, together with the package - GNAT and its children, which contain a set of useful additional - library functions provided by GNAT. The sources for these units are - needed by the compiler and are kept together in one directory. The ALI - files and object files generated by compiling the RTL are needed by the - binder and the linker and are kept together in one directory, typically - different from the directory containing the sources. In a normal - installation, you need not specify these directory names when compiling - or binding. Either the environment variables or the built-in defaults - cause these files to be found. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Examples of GNAT BIND Usage - @section Examples of @code{GNAT BIND} Usage - - @noindent - This section contains a number of examples of using the GNAT binding - utility @code{GNAT BIND}. - - @table @code - @item GNAT BIND hello - The main program @code{Hello} (source program in @file{HELLO.ADB}) is - bound using the standard qualifier settings. The generated main program is - @file{B~HELLO.ADB}. This is the normal, default use of the binder. - - @item GNAT BIND HELLO.ALI /OUTPUT=Mainprog.ADB - The main program @code{Hello} (source program in @file{HELLO.ADB}) is - bound using the standard qualifier settings. The generated main program is - @file{MAINPROG.ADB} with the associated spec in - @file{MAINPROG.ADS}. Note that you must specify the body here not the - spec, in the case where the output is in Ada. Note that if this option - is used, then linking must be done manually, since GNAT LINK will not - be able to find the generated file. - - @item GNAT BIND MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE - The main program @code{Main} (source program in - @file{MAIN.ADB}) is bound, excluding source files from the - consistency checking, generating - the file @file{MAINPROG.C}. - - - @item GNAT BIND /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ADA-CONTROL.C - The main program is in a language other than Ada, but calls to - subprograms in packages @code{Math} and @code{Dbase} appear. This call - to @code{GNAT BIND} generates the file @file{ADA-CONTROL.C} containing - the @code{adainit} and @code{adafinal} routines to be called before and - after accessing the Ada units. - @end table - - @node Linking Using GNAT LINK - @chapter Linking Using @code{GNAT LINK} - @findex GNAT LINK - - @noindent - This chapter discusses @code{GNAT LINK}, a utility program used to link - Ada programs and build an executable file. This is a simple program - that invokes the Unix linker (via the @code{GNAT COMPILE} - command) with a correct list of object files and library references. - @code{GNAT LINK} automatically determines the list of files and - references for the Ada part of a program. It uses the binder file - generated by the binder to determine this list. - - @menu - * Running GNAT LINK:: - * Qualifiers for GNAT LINK:: - * Setting Stack Size from GNAT LINK:: - * Setting Heap Size from GNAT LINK:: - @end menu - - @node Running GNAT LINK - @section Running @code{GNAT LINK} - - @noindent - The form of the @code{GNAT LINK} command is - - @smallexample - $ GNAT LINK [@var{qualifiers}] @var{mainprog}[.ALI] [@var{non-Ada objects}] - [@var{linker options}] - @end smallexample - - @noindent - @file{@var{mainprog}.ALI} references the ALI file of the main program. - The @file{.ALI} extension of this file can be omitted. From this - reference, @code{GNAT LINK} locates the corresponding binder file - @file{B$@var{mainprog}.ADB} and, using the information in this file along - with the list of non-Ada objects and linker options, constructs a Unix - linker command file to create the executable. - - The arguments following @file{@var{mainprog}.ALI} are passed to the - linker uninterpreted. They typically include the names of object files - for units written in other languages than Ada and any library references - required to resolve references in any of these foreign language units, - or in @code{pragma Import} statements in any Ada units. - - @var{linker options} is an optional list of linker specific - qualifiers. The default linker called by GNAT LINK is @var{GNAT COMPILE} which in - turn calls the appropriate system linker usually called - @var{ld}. Standard options for the linker such as @code{-lmy_lib} or - @code{-Ldir} can be added as is. For options that are not recognized by - @var{GNAT COMPILE} as linker options, the @var{GNAT COMPILE} qualifiers @code{-Xlinker} or - @code{-Wl,} shall be used. Refer to the GCC documentation for - details. Here is an example showing how to generate a linker map - assuming that the underlying linker is GNU ld: - - @smallexample - $ GNAT LINK my_prog -Wl,-Map,MAPFILE - @end smallexample - - Using @var{linker options} it is possible to set the program stack and - heap size. See @pxref{Setting Stack Size from GNAT LINK} and - @pxref{Setting Heap Size from GNAT LINK}. - - @code{GNAT LINK} determines the list of objects required by the Ada - program and prepends them to the list of objects passed to the linker. - @code{GNAT LINK} also gathers any arguments set by the use of - @code{pragma Linker_Options} and adds them to the list of arguments - presented to the linker. - - @code{GNAT LINK} accepts the following types of extra files on the command - line: objects (.OBJ), libraries (.OLB), shareable images (.EXE), and - options files (.OPT). These are recognized and handled according to their - extension. - - @node Qualifiers for GNAT LINK - @section Qualifiers for @code{GNAT LINK} - - @noindent - The following qualifiers are available with the @code{GNAT LINK} utility: - - @table @code - - @item /BIND_FILE=ADA - @cindex @code{/BIND_FILE=ADA} (@code{GNAT LINK}) - The binder has generated code in Ada. This is the default. - - @item /BIND_FILE=C - @cindex @code{/BIND_FILE=C} (@code{GNAT LINK}) - If instead of generating a file in Ada, the binder has generated one in - C, then the linker needs to know about it. Use this qualifier to signal - to @code{GNAT LINK} that the binder has generated C code rather than - Ada code. - - @item -f - @cindex Command line length - @cindex @code{-f} (@code{GNAT LINK}) - On some targets, the command line length is limited, and @code{GNAT LINK} - will generate a separate file for the linker if the list of object files - is too long. The @code{-f} flag forces this file to be generated even if - the limit is not exceeded. This is useful in some cases to deal with - special situations where the command line length is exceeded. - - @item /DEBUG - @cindex Debugging information, including - @cindex @code{/DEBUG} (@code{GNAT LINK}) - The option to include debugging information causes the Ada bind file (in - other words, @file{B$@var{mainprog}.ADB}) to be compiled with - @code{/DEBUG}. - In addition, the binder does not delete the @file{B$@var{mainprog}.ADB}, - @file{B$@var{mainprog}.OBJ} and @file{B$@var{mainprog}.ALI} files. - Without @code{/DEBUG}, the binder removes these files by - default. The same procedure apply if a C bind file was generated using - @code{/BIND_FILE=C} @code{GNAT BIND} option, in this case the filenames are - @file{B_@var{mainprog}.C} and @file{B_@var{mainprog}.OBJ}. - - - @item /VERBOSE - @cindex @code{/VERBOSE} (@code{GNAT LINK}) - Causes additional information to be output, including a full list of the - included object files. This qualifier option is most useful when you want - to see what set of object files are being used in the link step. - - - @item /EXECUTABLE=@var{exec-name} - @cindex @code{/EXECUTABLE} (@code{GNAT LINK}) - @var{exec-name} specifies an alternate name for the generated - executable program. If this qualifier is omitted, the executable has the same - name as the main unit. For example, @code{GNAT LINK TRY.ALI} creates - an executable called @file{TRY.EXE}. - - - @item /DEBUG=TRACEBACK - @cindex @code{/DEBUG=TRACEBACK} (@code{GNAT LINK}) - This qualifier causes sufficient information to be included in the - executable file to allow a traceback, but does not include the full - symbol information needed by the debugger. - - @item /IDENTIFICATION="" - "" specifies the string to be stored in the image file identification - field in the image header. It overrides any pragma Ident specified string. - - @item /NOINHIBIT-EXEC - Generate the executable file even if there are linker warnings. - - @item /NOSTART_FILES - Don't link in the object file containing the "main" transfer address. - Used when linking with a foreign language main program compiled with a - Digital compiler. - - @item /STATIC - Prefer linking with object libraries over shareable images, even without - /DEBUG. - - @end table - - @node Setting Stack Size from GNAT LINK - @section Setting Stack Size from @code{GNAT LINK} - - @noindent - It is possible to specify the program stack size from @code{GNAT LINK}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ GNAT LINK hello -Xlinker --stack=0x10000,0x1000 - @end smallexample - - This set the stack reserve size to 0x10000 bytes and the stack commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ GNAT LINK hello -Wl,--stack=0x1000000 - @end smallexample - - This set the stack reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the stack commit size - because the coma is a separator for this option. - - @end itemize - - @node Setting Heap Size from GNAT LINK - @section Setting Heap Size from @code{GNAT LINK} - - @noindent - It is possible to specify the program heap size from @code{GNAT LINK}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ GNAT LINK hello -Xlinker --heap=0x10000,0x1000 - @end smallexample - - This set the heap reserve size to 0x10000 bytes and the heap commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ GNAT LINK hello -Wl,--heap=0x1000000 - @end smallexample - - This set the heap reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the heap commit size - because the coma is a separator for this option. - - @end itemize - - @node The GNAT Make Program GNAT MAKE - @chapter The GNAT Make Program @code{GNAT MAKE} - @findex GNAT MAKE - - @menu - * Running GNAT MAKE:: - * Qualifiers for GNAT MAKE:: - * Mode Qualifiers for GNAT MAKE:: - * Notes on the Command Line:: - * How GNAT MAKE Works:: - * Examples of GNAT MAKE Usage:: - @end menu - @noindent - A typical development cycle when working on an Ada program consists of - the following steps: - - @enumerate - @item - Edit some sources to fix bugs. - - @item - Add enhancements. - - @item - Compile all sources affected. - - @item - Rebind and relink. - - @item - Test. - @end enumerate - - @noindent - The third step can be tricky, because not only do the modified files - @cindex Dependency rules - have to be compiled, but any files depending on these files must also be - recompiled. The dependency rules in Ada can be quite complex, especially - in the presence of overloading, @code{use} clauses, generics and inlined - subprograms. - - @code{GNAT MAKE} automatically takes care of the third and fourth steps - of this process. It determines which sources need to be compiled, - compiles them, and binds and links the resulting object files. - - Unlike some other Ada make programs, the dependencies are always - accurately recomputed from the new sources. The source based approach of - the GNAT compilation model makes this possible. This means that if - changes to the source program cause corresponding changes in - dependencies, they will always be tracked exactly correctly by - @code{GNAT MAKE}. - - @node Running GNAT MAKE - @section Running @code{GNAT MAKE} - - @noindent - The usual form of the @code{GNAT MAKE} command is - - @smallexample - $ GNAT MAKE [@var{qualifiers}] @var{file_name} [@var{file_names}] [@var{mode_qualifiers}] - @end smallexample - - @noindent - The only required argument is one @var{file_name}, which specifies - a compilation unit that is a main program. Several @var{file_names} can be - specified: this will result in several executables being built. - If @code{qualifiers} are present, they can be placed before the first - @var{file_name}, between @var{file_names} or after the last @var{file_name}. - If @var{mode_qualifiers} are present, they must always be placed after - the last @var{file_name} and all @code{qualifiers}. - - If you are using standard file extensions (.ADB and .ADS), then the - extension may be omitted from the @var{file_name} arguments. However, if - you are using non-standard extensions, then it is required that the - extension be given. A relative or absolute directory path can be - specified in a @var{file_name}, in which case, the input source file will - be searched for in the specified directory only. Otherwise, the input - source file will first be searched in the directory where - @code{GNAT MAKE} was invoked and if it is not found, it will be search on - the source path of the compiler as described in - @ref{Search Paths and the Run-Time Library (RTL)}. - - When several @var{file_names} are specified, if an executable needs to be - rebuilt and relinked, all subsequent executables will be rebuilt and - relinked, even if this would not be absolutely necessary. - - All @code{GNAT MAKE} output (except when you specify - @code{/DEPENDENCIES_LIST}) is to - @file{SYS$ERROR}. The output produced by the - @code{/DEPENDENCIES_LIST} qualifier is send to - @file{SYS$OUTPUT}. - - @node Qualifiers for GNAT MAKE - @section Qualifiers for @code{GNAT MAKE} - - @noindent - You may specify any of the following qualifiers to @code{GNAT MAKE}: - - @table @code - - @item /ALL_FILES - @cindex @code{/ALL_FILES} (@code{GNAT MAKE}) - Consider all files in the make process, even the GNAT internal system - files (for example, the predefined Ada library files), as well as any - locked files. Locked files are files whose ALI file is write-protected. - By default, - @code{GNAT MAKE} does not check these files, - because the assumption is that the GNAT internal files are properly up - to date, and also that any write protected ALI files have been properly - installed. Note that if there is an installation problem, such that one - of these files is not up to date, it will be properly caught by the - binder. - You may have to specify this qualifier if you are working on GNAT - itself. @code{/ALL_FILES} is also useful in conjunction with - @code{/FORCE_COMPILE} - if you need to recompile an entire application, - including run-time files, using special configuration pragma settings, - such as a non-standard @code{Float_Representation} pragma. - By default - @code{GNAT MAKE /ALL_FILES} compiles all GNAT - internal files with - the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} qualifier. - - @item /ACTIONS=BIND - @cindex @code{/ACTIONS=BIND} (@code{GNAT MAKE}) - Bind only. Can be combined with @code{/ACTIONS=COMPILE} to do compilation - and binding, but no link. Can be combined with @code{/ACTIONS=LINK} - to do binding and linking. When not combined with @code{/ACTIONS=COMPILE} - all the units in the closure of the main program must have been previously - compiled and must be up to date. The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item /ACTIONS=COMPILE - @cindex @code{/ACTIONS=COMPILE} (@code{GNAT MAKE}) - Compile only. Do not perform binding, except when @code{/ACTIONS=BIND} - is also specified. Do not perform linking, except if both - @code{/ACTIONS=BIND} and - @code{/ACTIONS=LINK} are also specified. - If the root unit specified by @var{file_name} is not a main unit, this is the - default. Otherwise @code{GNAT MAKE} will attempt binding and linking - unless all objects are up to date and the executable is more recent than - the objects. - - @item /MAPPING - @cindex @code{/MAPPING} (@code{GNAT MAKE}) - Use a mapping file. A mapping file is a way to communicate to the compiler - two mappings: from unit names to file names (without any directory information) - and from file names to path names (with full directory information). - These mappings are used by the compiler to short-circuit the path search. - When @code{GNAT MAKE} is invoked with this qualifier, it will create a mapping - file, initially populated by the project manager, if @code{-P} is used, - otherwise initially empty. Each invocation of the compiler will add the newly - accessed sources to the mapping file. This will improve the source search - during the next invocation of the compiler. - - @item /FORCE_COMPILE - @cindex @code{/FORCE_COMPILE} (@code{GNAT MAKE}) - Force recompilations. Recompile all sources, even though some object - files may be up to date, but don't recompile predefined or GNAT internal - files or locked files (files with a write-protected ALI file), - unless the @code{/ALL_FILES} qualifier is also specified. - - @item - @item /IN_PLACE - @cindex @code{/IN_PLACE} (@code{GNAT MAKE}) - In normal mode, @code{GNAT MAKE} compiles all object files and ALI files - into the current directory. If the @code{/IN_PLACE} qualifier is used, - then instead object files and ALI files that already exist are overwritten - in place. This means that once a large project is organized into separate - directories in the desired manner, then @code{GNAT MAKE} will automatically - maintain and update this organization. If no ALI files are found on the - Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), - the new object and ALI files are created in the - directory containing the source being compiled. If another organization - is desired, where objects and sources are kept in different directories, - a useful technique is to create dummy ALI files in the desired directories. - When detecting such a dummy file, @code{GNAT MAKE} will be forced to recompile - the corresponding source file, and it will be put the resulting object - and ALI files in the directory where it found the dummy file. - - @item /PROCESSES=@var{n} - @cindex @code{/PROCESSES} (@code{GNAT MAKE}) - @cindex Parallel make - Use @var{n} processes to carry out the (re)compilations. On a - multiprocessor machine compilations will occur in parallel. In the - event of compilation errors, messages from various compilations might - get interspersed (but @code{GNAT MAKE} will give you the full ordered - list of failing compiles at the end). If this is problematic, rerun - the make process with n set to 1 to get a clean list of messages. - - @item /CONTINUE_ON_ERROR - @cindex @code{/CONTINUE_ON_ERROR} (@code{GNAT MAKE}) - Keep going. Continue as much as possible after a compilation error. To - ease the programmer's task in case of compilation errors, the list of - sources for which the compile fails is given when @code{GNAT MAKE} - terminates. - - If @code{GNAT MAKE} is invoked with several @file{file_names} and with this - qualifier, if there are compilation errors when building an executable, - @code{GNAT MAKE} will not attempt to build the following executables. - - @item /ACTIONS=LINK - @cindex @code{/ACTIONS=LINK} (@code{GNAT MAKE}) - Link only. Can be combined with @code{/ACTIONS=BIND} to binding - and linking. Linking will not be performed if combined with - @code{/ACTIONS=COMPILE} - but not with @code{/ACTIONS=BIND}. - When not combined with @code{/ACTIONS=BIND} - all the units in the closure of the main program must have been previously - compiled and must be up to date, and the main program need to have been bound. - The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item /MINIMAL_RECOMPILATION - @cindex @code{/MINIMAL_RECOMPILATION} (@code{GNAT MAKE}) - Specifies that the minimum necessary amount of recompilations - be performed. In this mode @code{GNAT MAKE} ignores time - stamp differences when the only - modifications to a source file consist in adding/removing comments, - empty lines, spaces or tabs. This means that if you have changed the - comments in a source file or have simply reformatted it, using this - qualifier will tell GNAT MAKE not to recompile files that depend on it - (provided other sources on which these files depend have undergone no - semantic modifications). Note that the debugging information may be - out of date with respect to the sources if the @code{-m} qualifier causes - a compilation to be switched, so the use of this qualifier represents a - trade-off between compilation time and accurate debugging information. - - @item /DEPENDENCIES_LIST - @cindex Dependencies, producing list - @cindex @code{/DEPENDENCIES_LIST} (@code{GNAT MAKE}) - Check if all objects are up to date. If they are, output the object - dependences to @file{SYS$OUTPUT} in a form that can be directly exploited in - a @file{Makefile}. By default, each source file is prefixed with its - (relative or absolute) directory name. This name is whatever you - specified in the various @code{/SOURCE_SEARCH} - and @code{/SEARCH} qualifiers. If you use - @code{GNAT MAKE /DEPENDENCIES_LIST} - @code{/QUIET} - (see below), only the source file names, - without relative paths, are output. If you just specify the - @code{/DEPENDENCIES_LIST} - qualifier, dependencies of the GNAT internal system files are omitted. This - is typically what you want. If you also specify - the @code{/ALL_FILES} qualifier, - dependencies of the GNAT internal files are also listed. Note that - dependencies of the objects in external Ada libraries (see qualifier - @code{/SKIP_MISSING=}@var{dir} in the following list) are never reported. - - @item /DO_OBJECT_CHECK - @cindex @code{/DO_OBJECT_CHECK} (@code{GNAT MAKE}) - Don't compile, bind, or link. Checks if all objects are up to date. - If they are not, the full name of the first file that needs to be - recompiled is printed. - Repeated use of this option, followed by compiling the indicated source - file, will eventually result in recompiling all required units. - - @item /EXECUTABLE=@var{exec_name} - @cindex @code{/EXECUTABLE} (@code{GNAT MAKE}) - Output executable name. The name of the final executable program will be - @var{exec_name}. If the @code{/EXECUTABLE} qualifier is omitted the default - name for the executable will be the name of the input file in appropriate form - for an executable file on the host system. - - This qualifier cannot be used when invoking @code{GNAT MAKE} with several - @file{file_names}. - - @item /QUIET - @cindex @code{/QUIET} (@code{GNAT MAKE}) - Quiet. When this flag is not set, the commands carried out by - @code{GNAT MAKE} are displayed. - - @item /SWITCH_CHECK/ - @cindex @code{/SWITCH_CHECK} (@code{GNAT MAKE}) - Recompile if compiler qualifiers have changed since last compilation. - All compiler qualifiers but -I and -o are taken into account in the - following way: - orders between different ``first letter'' qualifiers are ignored, but - orders between same qualifiers are taken into account. For example, - @code{-O /OPTIMIZE=ALL} is different than @code{/OPTIMIZE=ALL -O}, but @code{-g -O} is equivalent - to @code{-O -g}. - - @item /UNIQUE - @cindex @code{/UNIQUE} (@code{GNAT MAKE}) - Unique. Recompile at most the main file. It implies -c. Combined with - -f, it is equivalent to calling the compiler directly. - - @item /REASONS - @cindex @code{/REASONS} (@code{GNAT MAKE}) - Verbose. Displays the reason for all recompilations @code{GNAT MAKE} - decides are necessary. - - @item /NOMAIN - @cindex @code{/NOMAIN} (@code{GNAT MAKE}) - No main subprogram. Bind and link the program even if the unit name - given on the command line is a package name. The resulting executable - will execute the elaboration routines of the package and its closure, - then the finalization routines. - - @item @code{GNAT COMPILE} @asis{qualifiers} - Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE} - but is recognizable as a valid qualifier for @code{GNAT COMPILE} is - automatically treated as a compiler qualifier, and passed on to all - compilations that are carried out. - @end table - - @noindent - Source and library search path qualifiers: - - @table @code - @item /SOURCE_SEARCH=@var{dir} - @cindex @code{/SOURCE_SEARCH} (@code{GNAT MAKE}) - When looking for source files also look in directory @var{dir}. - The order in which source files search is undertaken is - described in @ref{Search Paths and the Run-Time Library (RTL)}. - - @item /SKIP_MISSING=@var{dir} - @cindex @code{/SKIP_MISSING} (@code{GNAT MAKE}) - Consider @var{dir} as being an externally provided Ada library. - Instructs @code{GNAT MAKE} to skip compilation units whose @file{.ALI} - files have been located in directory @var{dir}. This allows you to have - missing bodies for the units in @var{dir} and to ignore out of date bodies - for the same units. You still need to specify - the location of the specs for these units by using the qualifiers - @code{/SOURCE_SEARCH=@var{dir}} - or @code{/SEARCH=@var{dir}}. - Note: this qualifier is provided for compatibility with previous versions - of @code{GNAT MAKE}. The easier method of causing standard libraries - to be excluded from consideration is to write-protect the corresponding - ALI files. - - @item /OBJECT_SEARCH=@var{dir} - @cindex @code{/OBJECT_SEARCH} (@code{GNAT MAKE}) - When searching for library and object files, look in directory - @var{dir}. The order in which library files are searched is described in - @ref{Search Paths for GNAT BIND}. - - @item /CONDITIONAL_SOURCE_SEARCH=@var{dir} - @cindex Search paths, for @code{GNAT MAKE} - @cindex @code{/CONDITIONAL_SOURCE_SEARCH} (@code{GNAT MAKE}) - Equivalent to @code{/SKIP_MISSING=@var{dir} - /SOURCE_SEARCH=@var{dir}}. - - @item /SEARCH=@var{dir} - @cindex @code{/SEARCH} (@code{GNAT MAKE}) - Equivalent to @code{/OBJECT_SEARCH=@var{dir} - /SOURCE_SEARCH=@var{dir}}. - - @item /NOCURRENT_DIRECTORY - @cindex @code{/NOCURRENT_DIRECTORY} (@code{GNAT MAKE}) - @cindex Source files, suppressing search - Do not look for source files in the directory containing the source - file named in the command line. - Do not look for ALI or object files in the directory - where @code{GNAT MAKE} was invoked. - - @item /LIBRARY_SEARCH=@var{dir} - @cindex @code{/LIBRARY_SEARCH} (@code{GNAT MAKE}) - @cindex Linker libraries - Add directory @var{dir} to the list of directories in which the linker - will search for libraries. This is equivalent to - @code{/LINKER_QUALIFIERS /LIBRARY_SEARCH=}@var{dir}. - - @item /NOSTD_INCLUDES - @cindex @code{/NOSTD_INCLUDES} (@code{GNAT MAKE}) - Do not look for source files in the system default directory. - - @item /NOSTD_LIBRARIES - @cindex @code{/NOSTD_LIBRARIES} (@code{GNAT MAKE}) - Do not look for library files in the system default directory. - - @item /RUNTIME_SYSTEM=@var{rts-path} - @cindex @code{/RUNTIME_SYSTEM} (@code{GNAT MAKE}) - Specifies the default location of the runtime library. We look for the runtime - in the following directories, and stop as soon as a valid runtime is found - ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present): - - @itemize @bullet - @item /$rts_path - - @item /$rts_path - - @item /rts-$rts_path - @end itemize - - @noindent - The selected path is handled like a normal RTS path. - - @end table - - @node Mode Qualifiers for GNAT MAKE - @section Mode Qualifiers for @code{GNAT MAKE} - - @noindent - The mode qualifiers (referred to as @code{mode_qualifiers}) allow the - inclusion of qualifiers that are to be passed to the compiler itself, the - binder or the linker. The effect of a mode qualifier is to cause all - subsequent qualifiers up to the end of the qualifier list, or up to the next - mode qualifier, to be interpreted as qualifiers to be passed on to the - designated component of GNAT. - - @table @code - @item /COMPILER_QUALIFIERS @var{qualifiers} - @cindex @code{/COMPILER_QUALIFIERS} (@code{GNAT MAKE}) - Compiler qualifiers. Here @var{qualifiers} is a list of qualifiers - that are valid qualifiers for @code{GNAT COMPILE}. They will be passed on to - all compile steps performed by @code{GNAT MAKE}. - - @item /BINDER_QUALIFIERS @var{qualifiers} - @cindex @code{/BINDER_QUALIFIERS} (@code{GNAT MAKE}) - Binder qualifiers. Here @var{qualifiers} is a list of qualifiers - that are valid qualifiers for @code{GNAT COMPILE}. They will be passed on to - all bind steps performed by @code{GNAT MAKE}. - - @item /LINKER_QUALIFIERS @var{qualifiers} - @cindex @code{/LINKER_QUALIFIERS} (@code{GNAT MAKE}) - Linker qualifiers. Here @var{qualifiers} is a list of qualifiers - that are valid qualifiers for @code{GNAT COMPILE}. They will be passed on to - all link steps performed by @code{GNAT MAKE}. - @end table - - @node Notes on the Command Line - @section Notes on the Command Line - - @noindent - This section contains some additional useful notes on the operation - of the @code{GNAT MAKE} command. - - @itemize @bullet - @item - @cindex Recompilation, by @code{GNAT MAKE} - If @code{GNAT MAKE} finds no ALI files, it recompiles the main program - and all other units required by the main program. - This means that @code{GNAT MAKE} - can be used for the initial compile, as well as during subsequent steps of - the development cycle. - - @item - If you enter @code{GNAT MAKE @var{file}.ADB}, where @file{@var{file}.ADB} - is a subunit or body of a generic unit, @code{GNAT MAKE} recompiles - @file{@var{file}.ADB} (because it finds no ALI) and stops, issuing a - warning. - - @item - In @code{GNAT MAKE} the qualifier @code{/SEARCH} - is used to specify both source and - library file paths. Use @code{/SOURCE_SEARCH} - instead if you just want to specify - source paths only and @code{/OBJECT_SEARCH} - if you want to specify library paths - only. - - @item - @code{GNAT MAKE} examines both an ALI file and its corresponding object file - for consistency. If an ALI is more recent than its corresponding object, - or if the object file is missing, the corresponding source will be recompiled. - Note that @code{GNAT MAKE} expects an ALI and the corresponding object file - to be in the same directory. - - @item - @code{GNAT MAKE} will ignore any files whose ALI file is write-protected. - This may conveniently be used to exclude standard libraries from - consideration and in particular it means that the use of the - @code{/FORCE_COMPILE} qualifier will not recompile these files - unless @code{/ALL_FILES} is also specified. - - @item - @code{GNAT MAKE} has been designed to make the use of Ada libraries - particularly convenient. Assume you have an Ada library organized - as follows: [@var{OBJ_DIR}] contains the objects and ALI files for - of your Ada compilation units, - whereas [@var{INCLUDE_DIR}] contains the - specs of these units, but no bodies. Then to compile a unit - stored in @code{MAIN.ADB}, which uses this Ada library you would just type - - @smallexample - $ GNAT MAKE /SOURCE_SEARCH=[@var{INCLUDE_DIR}] - /SKIP_MISSING=[@var{OBJ_DIR}] main - @end smallexample - - @item - Using @code{GNAT MAKE} along with the - @code{/MINIMAL_RECOMPILATION} - qualifier provides a mechanism for avoiding unnecessary rcompilations. Using - this qualifier, - you can update the comments/format of your - source files without having to recompile everything. Note, however, that - adding or deleting lines in a source files may render its debugging - info obsolete. If the file in question is a spec, the impact is rather - limited, as that debugging info will only be useful during the - elaboration phase of your program. For bodies the impact can be more - significant. In all events, your debugger will warn you if a source file - is more recent than the corresponding object, and alert you to the fact - that the debugging information may be out of date. - @end itemize - - @node How GNAT MAKE Works - @section How @code{GNAT MAKE} Works - - @noindent - Generally @code{GNAT MAKE} automatically performs all necessary - recompilations and you don't need to worry about how it works. However, - it may be useful to have some basic understanding of the @code{GNAT MAKE} - approach and in particular to understand how it uses the results of - previous compilations without incorrectly depending on them. - - First a definition: an object file is considered @dfn{up to date} if the - corresponding ALI file exists and its time stamp predates that of the - object file and if all the source files listed in the - dependency section of this ALI file have time stamps matching those in - the ALI file. This means that neither the source file itself nor any - files that it depends on have been modified, and hence there is no need - to recompile this file. - - @code{GNAT MAKE} works by first checking if the specified main unit is up - to date. If so, no compilations are required for the main unit. If not, - @code{GNAT MAKE} compiles the main program to build a new ALI file that - reflects the latest sources. Then the ALI file of the main unit is - examined to find all the source files on which the main program depends, - and @code{GNAT MAKE} recursively applies the above procedure on all these files. - - This process ensures that @code{GNAT MAKE} only trusts the dependencies - in an existing ALI file if they are known to be correct. Otherwise it - always recompiles to determine a new, guaranteed accurate set of - dependencies. As a result the program is compiled "upside down" from what may - be more familiar as the required order of compilation in some other Ada - systems. In particular, clients are compiled before the units on which - they depend. The ability of GNAT to compile in any order is critical in - allowing an order of compilation to be chosen that guarantees that - @code{GNAT MAKE} will recompute a correct set of new dependencies if - necessary. - - When invoking @code{GNAT MAKE} with several @var{file_names}, if a unit is - imported by several of the executables, it will be recompiled at most once. - - @node Examples of GNAT MAKE Usage - @section Examples of @code{GNAT MAKE} Usage - - @table @code - @item GNAT MAKE HELLO.ADB - Compile all files necessary to bind and link the main program - @file{HELLO.ADB} (containing unit @code{Hello}) and bind and link the - resulting object files to generate an executable file @file{HELLO.EXE}. - - @item GNAT MAKE main1 main2 main3 - Compile all files necessary to bind and link the main programs - @file{MAIN1.ADB} (containing unit @code{Main1}), @file{MAIN2.ADB} - (containing unit @code{Main2}) and @file{MAIN3.ADB} - (containing unit @code{Main3}) and bind and link the resulting object files - to generate three executable files @file{MAIN1.EXE}, - @file{MAIN2.EXE} - and @file{MAIN3.EXE}. - - - @item GNAT MAKE Main_Unit /QUIET /COMPILER_QUALIFIERS /OPTIMIZE=ALL /BINDER_QUALIFIERS /ORDER_OF_ELABORATION - Compile all files necessary to bind and link the main program unit - @code{Main_Unit} (from file @file{MAIN_UNIT.ADB}). All compilations will - be done with optimization level 2 and the order of elaboration will be - listed by the binder. @code{GNAT MAKE} will operate in quiet mode, not - displaying commands it is executing. - @end table - - @node Renaming Files Using GNAT CHOP - @chapter Renaming Files Using @code{GNAT CHOP} - @findex GNAT CHOP - - @noindent - This chapter discusses how to handle files with multiple units by using - the @code{GNAT CHOP} utility. This utility is also useful in renaming - files to meet the standard GNAT default file naming conventions. - - @menu - * Handling Files with Multiple Units:: - * Operating GNAT CHOP in Compilation Mode:: - * Command Line for GNAT CHOP:: - * Qualifiers for GNAT CHOP:: - * Examples of GNAT CHOP Usage:: - @end menu - - @node Handling Files with Multiple Units - @section Handling Files with Multiple Units - - @noindent - The basic compilation model of GNAT requires that a file submitted to the - compiler have only one unit and there be a strict correspondence - between the file name and the unit name. - - The @code{GNAT CHOP} utility allows both of these rules to be relaxed, - allowing GNAT to process files which contain multiple compilation units - and files with arbitrary file names. @code{GNAT CHOP} - reads the specified file and generates one or more output files, - containing one unit per file. The unit and the file name correspond, - as required by GNAT. - - If you want to permanently restructure a set of "foreign" files so that - they match the GNAT rules, and do the remaining development using the - GNAT structure, you can simply use @code{GNAT CHOP} once, generate the - new set of files and work with them from that point on. - - Alternatively, if you want to keep your files in the "foreign" format, - perhaps to maintain compatibility with some other Ada compilation - system, you can set up a procedure where you use @code{GNAT CHOP} each - time you compile, regarding the source files that it writes as temporary - files that you throw away. - - @node Operating GNAT CHOP in Compilation Mode - @section Operating GNAT CHOP in Compilation Mode - - @noindent - The basic function of @code{GNAT CHOP} is to take a file with multiple units - and split it into separate files. The boundary between files is reasonably - clear, except for the issue of comments and pragmas. In default mode, the - rule is that any pragmas between units belong to the previous unit, except - that configuration pragmas always belong to the following unit. Any comments - belong to the following unit. These rules - almost always result in the right choice of - the split point without needing to mark it explicitly and most users will - find this default to be what they want. In this default mode it is incorrect to - submit a file containing only configuration pragmas, or one that ends in - configuration pragmas, to @code{GNAT CHOP}. - - However, using a special option to activate "compilation mode", - @code{GNAT CHOP} - can perform another function, which is to provide exactly the semantics - required by the RM for handling of configuration pragmas in a compilation. - In the absence of configuration pragmas (at the main file level), this - option has no effect, but it causes such configuration pragmas to be handled - in a quite different manner. - - First, in compilation mode, if @code{GNAT CHOP} is given a file that consists of - only configuration pragmas, then this file is appended to the - @file{GNAT.ADC} file in the current directory. This behavior provides - the required behavior described in the RM for the actions to be taken - on submitting such a file to the compiler, namely that these pragmas - should apply to all subsequent compilations in the same compilation - environment. Using GNAT, the current directory, possibly containing a - @file{GNAT.ADC} file is the representation - of a compilation environment. For more information on the - @file{GNAT.ADC} file, see the section on handling of configuration - pragmas @pxref{Handling of Configuration Pragmas}. - - Second, in compilation mode, if @code{GNAT CHOP} - is given a file that starts with - configuration pragmas, and contains one or more units, then these - configuration pragmas are prepended to each of the chopped files. This - behavior provides the required behavior described in the RM for the - actions to be taken on compiling such a file, namely that the pragmas - apply to all units in the compilation, but not to subsequently compiled - units. - - Finally, if configuration pragmas appear between units, they are appended - to the previous unit. This results in the previous unit being illegal, - since the compiler does not accept configuration pragmas that follow - a unit. This provides the required RM behavior that forbids configuration - pragmas other than those preceding the first compilation unit of a - compilation. - - For most purposes, @code{GNAT CHOP} will be used in default mode. The - compilation mode described above is used only if you need exactly - accurate behavior with respect to compilations, and you have files - that contain multiple units and configuration pragmas. In this - circumstance the use of @code{GNAT CHOP} with the compilation mode - qualifier provides the required behavior, and is for example the mode - in which GNAT processes the ACVC tests. - - @node Command Line for GNAT CHOP - @section Command Line for @code{GNAT CHOP} - - @noindent - The @code{GNAT CHOP} command has the form: - - @smallexample - $ GNAT CHOP qualifiers @var{file name} [@var{file name} @var{file name} ...] - [@var{directory}] - @end smallexample - - @noindent - The only required argument is the file name of the file to be chopped. - There are no restrictions on the form of this file name. The file itself - contains one or more Ada units, in normal GNAT format, concatenated - together. As shown, more than one file may be presented to be chopped. - - When run in default mode, @code{GNAT CHOP} generates one output file in - the current directory for each unit in each of the files. - - @var{directory}, if specified, gives the name of the directory to which - the output files will be written. If it is not specified, all files are - written to the current directory. - - For example, given a - file called @file{hellofiles} containing - - @smallexample - @group - @cartouche - @b{procedure} hello; - - @b{with} Text_IO; @b{use} Text_IO; - @b{procedure} hello @b{is} - @b{begin} - Put_Line ("Hello"); - @b{end} hello; - @end cartouche - @end group - @end smallexample - - @noindent - the command - - @smallexample - $ GNAT CHOP HELLOFILES. - @end smallexample - - @noindent - generates two files in the current directory, one called - @file{HELLO.ADS} containing the single line that is the procedure spec, - and the other called @file{HELLO.ADB} containing the remaining text. The - original file is not affected. The generated files can be compiled in - the normal manner. - - @node Qualifiers for GNAT CHOP - @section Qualifiers for @code{GNAT CHOP} - - @noindent - @code{GNAT CHOP} recognizes the following qualifiers: - - @table @code - - @item /COMPILATION - @cindex @code{/COMPILATION} (@code{GNAT CHOP}) - Causes @code{GNAT CHOP} to operate in compilation mode, in which - configuration pragmas are handled according to strict RM rules. See - previous section for a full description of this mode. - - - @item /HELP - Causes @code{GNAT CHOP} to generate a brief help summary to the standard - output file showing usage information. - - @item /FILE_NAME_MAX_LENGTH=@var{mm} - @cindex @code{/FILE_NAME_MAX_LENGTH} (@code{GNAT CHOP}) - Limit generated file names to the specified number @code{mm} - of characters. - This is useful if the - resulting set of files is required to be interoperable with systems - which limit the length of file names. - If no value is given, or - if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given, - a default of 39, suitable for OpenVMS Alpha - Systems, is assumed - - @item /PRESERVE - @cindex @code{/PRESERVE} (@code{GNAT CHOP}) - Causes the file creation time stamp of the input file to be - preserved and used for the time stamp of the output file(s). This may be - useful for preserving coherency of time stamps in an enviroment where - @code{GNAT CHOP} is used as part of a standard build process. - - @item /QUIET - @cindex @code{/QUIET} (@code{GNAT CHOP}) - Causes output of informational messages indicating the set of generated - files to be suppressed. Warnings and error messages are unaffected. - - @item /REFERENCE - @cindex @code{/REFERENCE} (@code{GNAT CHOP}) - @findex Source_Reference - Generate @code{Source_Reference} pragmas. Use this qualifier if the output - files are regarded as temporary and development is to be done in terms - of the original unchopped file. This qualifier causes - @code{Source_Reference} pragmas to be inserted into each of the - generated files to refers back to the original file name and line number. - The result is that all error messages refer back to the original - unchopped file. - In addition, the debugging information placed into the object file (when - the @code{/DEBUG} qualifier of @code{GNAT COMPILE} or @code{GNAT MAKE} is specified) also - refers back to this original file so that tools like profilers and - debuggers will give information in terms of the original unchopped file. - - If the original file to be chopped itself contains - a @code{Source_Reference} - pragma referencing a third file, then GNAT CHOP respects - this pragma, and the generated @code{Source_Reference} pragmas - in the chopped file refer to the original file, with appropriate - line numbers. This is particularly useful when @code{GNAT CHOP} - is used in conjunction with @code{GNAT PREPROCESS} to compile files that - contain preprocessing statements and multiple units. - - @item /VERBOSE - @cindex @code{/VERBOSE} (@code{GNAT CHOP}) - Causes @code{GNAT CHOP} to operate in verbose mode. The version - number and copyright notice are output, as well as exact copies of - the GNAT1 commands spawned to obtain the chop control information. - - @item /OVERWRITE - @cindex @code{/OVERWRITE} (@code{GNAT CHOP}) - Overwrite existing file names. Normally @code{GNAT CHOP} regards it as a - fatal error if there is already a file with the same name as a - file it would otherwise output, in other words if the files to be - chopped contain duplicated units. This qualifier bypasses this - check, and causes all but the last instance of such duplicated - units to be skipped. - - @end table - - @node Examples of GNAT CHOP Usage - @section Examples of @code{GNAT CHOP} Usage - - @table @code - @item GNAT CHOP /OVERWRITE HELLO_S.ADA [ICHBIAH.FILES] - - Chops the source file @file{HELLO_S.ADA}. The output files will be - placed in the directory @file{[ICHBIAH.FILES]}, - overwriting any - files with matching names in that directory (no files in the current - directory are modified). - - @item GNAT CHOP ARCHIVE. - Chops the source file @file{ARCHIVE.} - into the current directory. One - useful application of @code{GNAT CHOP} is in sending sets of sources - around, for example in email messages. The required sources are simply - concatenated (for example, using a VMS @code{APPEND/NEW} - command), and then - @code{GNAT CHOP} is used at the other end to reconstitute the original - file names. - - @item GNAT CHOP file1 file2 file3 direc - Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing - the resulting files in the directory @file{direc}. Note that if any units - occur more than once anywhere within this set of files, an error message - is generated, and no files are written. To override this check, use the - @code{/OVERWRITE} qualifier, - in which case the last occurrence in the last file will - be the one that is output, and earlier duplicate occurrences for a given - unit will be skipped. - @end table - - @node Configuration Pragmas - @chapter Configuration Pragmas - @cindex Configuration pragmas - @cindex Pragmas, configuration - - @noindent - In Ada 95, configuration pragmas include those pragmas described as - such in the Ada 95 Reference Manual, as well as - implementation-dependent pragmas that are configuration pragmas. See the - individual descriptions of pragmas in the GNAT Reference Manual for - details on these additional GNAT-specific configuration pragmas. Most - notably, the pragma @code{Source_File_Name}, which allows - specifying non-default names for source files, is a configuration - pragma. The following is a complete list of configuration pragmas - recognized by @code{GNAT}: - - @smallexample - Ada_83 - Ada_95 - C_Pass_By_Copy - Component_Alignment - Discard_Names - Elaboration_Checks - Eliminate - Extend_System - Extensions_Allowed - External_Name_Casing - Float_Representation - Initialize_Scalars - License - Locking_Policy - Long_Float - No_Run_Time - Normalize_Scalars - Polling - Propagate_Exceptions - Queuing_Policy - Ravenscar - Restricted_Run_Time - Restrictions - Reviewable - Source_File_Name - Style_Checks - Suppress - Task_Dispatching_Policy - Unsuppress - Use_VADS_Size - Warnings - Validity_Checks - @end smallexample - - @menu - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - @end menu - - @node Handling of Configuration Pragmas - @section Handling of Configuration Pragmas - - Configuration pragmas may either appear at the start of a compilation - unit, in which case they apply only to that unit, or they may apply to - all compilations performed in a given compilation environment. - - GNAT also provides the @code{GNAT CHOP} utility to provide an automatic - way to handle configuration pragmas following the semantics for - compilations (that is, files with multiple units), described in the RM. - See section @pxref{Operating GNAT CHOP in Compilation Mode} for details. - However, for most purposes, it will be more convenient to edit the - @file{GNAT.ADC} file that contains configuration pragmas directly, - as described in the following section. - - @node The Configuration Pragmas Files - @section The Configuration Pragmas Files - @cindex @file{GNAT.ADC} - - @noindent - In GNAT a compilation environment is defined by the current - directory at the time that a compile command is given. This current - directory is searched for a file whose name is @file{GNAT.ADC}. If - this file is present, it is expected to contain one or more - configuration pragmas that will be applied to the current compilation. - However, if the qualifier @option{-gnatA} is used, @file{GNAT.ADC} is not - considered. - - Configuration pragmas may be entered into the @file{GNAT.ADC} file - either by running @code{GNAT CHOP} on a source file that consists only of - configuration pragmas, or more conveniently by - direct editing of the @file{GNAT.ADC} file, which is a standard format - source file. - - In addition to @file{GNAT.ADC}, one additional file containing configuration - pragmas may be applied to the current compilation using the qualifier - @option{-gnatec}@var{path}. @var{path} must designate an existing file that - contains only configuration pragmas. These configuration pragmas are - in addition to those found in @file{GNAT.ADC} (provided @file{GNAT.ADC} - is present and qualifier @option{-gnatA} is not used). - - It is allowed to specify several qualifiers @option{-gnatec}, however only - the last one on the command line will be taken into account. - - Of special interest to GNAT OpenVMS Alpha is the following configuration pragma: - - @smallexample - @cartouche - @b{pragma} Extend_System (Aux_DEC); - @end cartouche - @end smallexample - - @noindent - In the presence of this pragma, GNAT adds to the definition of the - predefined package SYSTEM all the additional types and subprograms that are - defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details. - - @node Handling Arbitrary File Naming Conventions Using gnatname - @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} - @cindex Arbitrary File Naming Conventions - - @menu - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Qualifiers for gnatname:: - * Examples of gnatname Usage:: - @end menu - - @node Arbitrary File Naming Conventions - @section Arbitrary File Naming Conventions - - @noindent - The GNAT compiler must be able to know the source file name of a compilation unit. - When using the standard GNAT default file naming conventions (@code{.ADS} for specs, - @code{.ADB} for bodies), the GNAT compiler does not need additional information. - - @noindent - When the source file names do not follow the standard GNAT default file naming - conventions, the GNAT compiler must be given additional information through - a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file. - When the non standard file naming conventions are well-defined, a small number of - pragmas @code{Source_File_Name} specifying a naming pattern - (see @ref{Alternative File Naming Schemes}) may be sufficient. However, - if the file naming conventions are irregular or arbitrary, a number - of pragma @code{Source_File_Name} for individual compilation units must be defined. - To help maintain the correspondence between compilation unit names and - source file names within the compiler, - GNAT provides a tool @code{gnatname} to generate the required pragmas for a - set of files. - - @node Running gnatname - @section Running @code{gnatname} - - @noindent - The usual form of the @code{gnatname} command is - - @smallexample - $ gnatname [@var{qualifiers}] @var{naming_pattern} [@var{naming_patterns}] - @end smallexample - - @noindent - All of the arguments are optional. If invoked without any argument, - @code{gnatname} will display its usage. - - @noindent - When used with at least one naming pattern, @code{gnatname} will attempt to - find all the compilation units in files that follow at least one of the - naming patterns. To find these compilation units, - @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all - regular files. - - @noindent - One or several Naming Patterns may be given as arguments to @code{gnatname}. - Each Naming Pattern is enclosed between double quotes. - A Naming Pattern is a regular expression similar to the wildcard patterns - used in file names by the Unix shells or the DOS prompt. - - @noindent - Examples of Naming Patterns are - - @smallexample - "*.[12].ADA" - "*.ad[sb]*" - "body_*" "spec_*" - @end smallexample - - @noindent - For a more complete description of the syntax of Naming Patterns, see the second kind - of regular expressions described in @file{G-REGEXP.ADS} (the "Glob" regular - expressions). - - @noindent - When invoked with no qualifiers, @code{gnatname} will create a configuration - pragmas file @file{GNAT.ADC} in the current working directory, with pragmas - @code{Source_File_Name} for each file that contains a valid Ada unit. - - @node Qualifiers for gnatname - @section Qualifiers for @code{gnatname} - - @noindent - Qualifiers for @code{gnatname} must precede any specified Naming Pattern. - - @noindent - You may specify any of the following qualifiers to @code{gnatname}: - - @table @code - - @item -c@file{file} - @cindex @code{-c} (@code{gnatname}) - Create a configuration pragmas file @file{file} (instead of the default - @file{GNAT.ADC}). There may be zero, one or more space between @code{-c} and - @file{file}. @file{file} may include directory information. @file{file} must be - writeable. There may be only one qualifier @code{-c}. When a qualifier @code{-c} is - specified, no qualifier @code{-P} may be specified (see below). - - @item -d@file{dir} - @cindex @code{-d} (@code{gnatname}) - Look for source files in directory @file{dir}. There may be zero, one or more spaces - between @code{-d} and @file{dir}. When a qualifier @code{-d} is specified, - the current working directory will not be searched for source files, unless it - is explictly - specified with a @code{-d} or @code{-D} qualifier. Several qualifiers @code{-d} may be - specified. If @file{dir} is a relative path, it is relative to the directory of - the configuration pragmas file specified with qualifier @code{-c}, or to the directory - of the project file specified with qualifier @code{-P} or, if neither qualifier @code{-c} - nor qualifier @code{-P} are specified, it is relative to the current working - directory. The directory - specified with qualifier @code{-c} must exist and be readable. - - @item -D@file{file} - @cindex @code{-D} (@code{gnatname}) - Look for source files in all directories listed in text file @file{file}. There may be - zero, one or more spaces between @code{-d} and @file{dir}. @file{file} - must be an existing, readable text file. Each non empty line in @file{file} must be - a directory. Specifying qualifier @code{-D} is equivalent to specifying as many qualifiers - @code{-d} as there are non empty lines in @file{file}. - - @item -h - @cindex @code{-h} (@code{gnatname}) - Output usage (help) information. The output is written to @file{SYS$OUTPUT}. - - @item -P@file{proj} - @cindex @code{-P} (@code{gnatname}) - Create or update project file @file{proj}. There may be zero, one or more space - between @code{-P} and @file{proj}. @file{proj} may include directory information. - @file{proj} must be writeable. There may be only one qualifier @code{-P}. - When a qualifier @code{-P} is specified, no qualifier @code{-c} may be specified. - - @item -v - @cindex @code{-v} (@code{gnatname}) - Verbose mode. Output detailed explanation of behavior to @file{SYS$OUTPUT}. This includes - name of the file written, the name of the directories to search and, for each file - in those directories whose name matches at least one of the Naming Patterns, an - indication of whether the file contains a unit, and if so the name of the unit. - - @item -v -v - Very Verbose mode. In addition to the output produced in verbose mode, for each file - in the searched directories whose name matches none of the Naming Patterns, an - indication is given that there is no match. - - @item -x@file{pattern} - Excluded patterns. Using this qualifier, it is possible to exclude some files - that would match the name patterns. For example, - @code{"gnatname -x "*_NT.ADA" "*.ADA"} will look for Ada units in all files - with the @file{.ADA} extension, except those whose names end with - @file{_NT.ADA}. - - @end table - - @node Examples of gnatname Usage - @section Examples of @code{gnatname} Usage - - @smallexample - $ gnatname -c /home/me/NAMES.ADC -d sources "[a-z]*.ADA*" - @end smallexample - - In this example, the directory @file{/home/me} must already exist and be - writeable. In addition, the directory @file{/home/me/sources} (specified by - @code{-d sources}) must exist and be readable. Note the optional spaces after - @code{-c} and @code{-d}. - - @smallexample - $ gnatname -P/home/me/proj -x "*_NT_BODY.ADA" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" - @end smallexample - - Note that several qualifiers @code{-d} may be used, even in conjunction with one - or several qualifiers @code{-D}. Several Naming Patterns and one excluded pattern - are used in this example. - - - @c ***************************************** - @c * G N A T P r o j e c t M a n a g e r * - @c ***************************************** - @node GNAT Project Manager - @chapter GNAT Project Manager - - @menu - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Qualifiers Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - @end menu - - - @c **************** - @c * Introduction * - @c **************** - - @node Introduction - @section Introduction - - @noindent - This chapter describes GNAT's @emph{Project Manager}, a facility that - lets you configure various properties for a collection of source files. In - particular, you can specify: - @itemize @bullet - @item - The directory or set of directories containing the source files, and/or the - names of the specific source files themselves - @item - The directory in which the compiler's output - (@file{ALI} files, object files, tree files) will be placed - @item - The directory in which the executable programs will be placed - @item - Qualifier settings for any of the project-enabled tools (@command{GNAT MAKE}, - compiler, binder, linker, @code{GNAT LIST}, @code{GNAT XREF}, @code{GNAT FIND}); - you can apply these settings either globally or to individual units - @item - The source files containing the main subprogram(s) to be built - @item - The source programming language(s) (currently Ada and/or C) - @item - Source file naming conventions; you can specify these either globally or for - individual units - @end itemize - - @menu - * Project Files:: - @end menu - - @node Project Files - @subsection Project Files - - @noindent - A @dfn{project} is a specific set of values for these properties. You can - define a project's settings in a @dfn{project file}, a text file with an - Ada-like syntax; a property value is either a string or a list of strings. - Properties that are not explicitly set receive default values. A project - file may interrogate the values of @dfn{external variables} (user-defined - command-line qualifiers or environment variables), and it may specify property - settings conditionally, based on the value of such variables. - - In simple cases, a project's source files depend only on other source files - in the same project, or on the predefined libraries. ("Dependence" is in - the technical sense; for example, one Ada unit "with"ing another.) However, - the Project Manager also allows much more sophisticated arrangements, - with the source files in one project depending on source files in other - projects: - @itemize @bullet - @item - One project can @emph{import} other projects containing needed source files. - @item - You can organize GNAT projects in a hierarchy: a @emph{child} project - can extend a @emph{parent} project, inheriting the parent's source files and - optionally overriding any of them with alternative versions - @end itemize - - @noindent - More generally, the Project Manager lets you structure large development - efforts into hierarchical subsystems, with build decisions deferred to the - subsystem level and thus different compilation environments (qualifier settings) - used for different subsystems. - - The Project Manager is invoked through the @option{-P@emph{projectfile}} - qualifier to @command{GNAT MAKE} or to the @command{gnat} front driver. - If you want to define (on the command line) an external variable that is - queried by the project file, additionally use the - @option{-X@emph{vbl}=@emph{value}} qualifier. - The Project Manager parses and interprets the project file, and drives the - invoked tool based on the project settings. - - The Project Manager supports a wide range of development strategies, - for systems of all sizes. Some typical practices that are easily handled: - @itemize @bullet - @item - Using a common set of source files, but generating object files in different - directories via different qualifier settings - @item - Using a mostly-shared set of source files, but with different versions of - some unit or units - @end itemize - - @noindent - The destination of an executable can be controlled inside a project file - using the @option{-o} qualifier. In the absence of such a qualifier either inside - the project file or on the command line, any executable files generated by - @command{GNAT MAKE} will be placed in the directory @code{Exec_Dir} specified - in the project file. If no @code{Exec_Dir} is specified, they will be placed - in the object directory of the project. - - You can use project files to achieve some of the effects of a source - versioning system (for example, defining separate projects for - the different sets of sources that comprise different releases) but the - Project Manager is independent of any source configuration management tools - that might be used by the developers. - - The next section introduces the main features of GNAT's project facility - through a sequence of examples; subsequent sections will present the syntax - and semantics in more detail. - - - @c ***************************** - @c * Examples of Project Files * - @c ***************************** - - @node Examples of Project Files - @section Examples of Project Files - @noindent - This section illustrates some of the typical uses of project files and - explains their basic structure and behavior. - - @menu - * Common Sources with Different Qualifiers and Different Output Directories:: - * Using External Variables:: - * Importing Other Projects:: - * Extending a Project:: - @end menu - - @node Common Sources with Different Qualifiers and Different Output Directories - @subsection Common Sources with Different Qualifiers and Different Output Directories - - @menu - * Source Files:: - * Specifying the Object Directory:: - * Specifying the Exec Directory:: - * Project File Packages:: - * Specifying Qualifier Settings:: - * Main Subprograms:: - * Source File Naming Conventions:: - * Source Language(s):: - @end menu - - @noindent - Assume that the Ada source files @file{PACK.ADS}, @file{PACK.ADB}, and - @file{PROC.ADB} are in the @file{/common} directory. The file - @file{PROC.ADB} contains an Ada main subprogram @code{Proc} that "with"s - package @code{Pack}. We want to compile these source files under two sets - of qualifiers: - @itemize @bullet - @item - When debugging, we want to pass the @option{-g} qualifier to @command{GNAT MAKE}, - and the @option{/CHECKS=ASSERTIONS}, @option{/CHECKS=OVERFLOW}, and @option{/CHECKS=ELABORATION} qualifiers to the - compiler; the compiler's output is to appear in @file{/common/debug} - @item - When preparing a release version, we want to pass the @option{/OPTIMIZE=ALL} qualifier to - the compiler; the compiler's output is to appear in @file{/common/release} - @end itemize - - @noindent - The GNAT project files shown below, respectively @file{debug.gpr} and - @file{release.gpr} in the @file{/common} directory, achieve these effects. - - Diagrammatically: - @smallexample - @group - /common - debug.gpr - release.gpr - PACK.ADS - PACK.ADB - PROC.ADB - @end group - @group - /common/debug @{-g, /CHECKS=ASSERTIONS, /CHECKS=OVERFLOW, /CHECKS=ELABORATION@} - PROC.ALI, PROC.OBJ - PACK.ALI, PACK.OBJ - @end group - @group - /common/release @{/OPTIMIZE=ALL@} - PROC.ALI, PROC.OBJ - PACK.ALI, PACK.OBJ - @end group - @end smallexample - Here are the project files: - @smallexample - @group - project Debug is - for Object_Dir use "debug"; - for Main use ("proc"); - - package Builder is - for Default_Qualifiers ("Ada") use ("-g"); - end Builder; - @end group - - @group - package Compiler is - for Default_Qualifiers ("Ada") - use ("-fstack-check", "/CHECKS=ASSERTIONS", "/CHECKS=OVERFLOW", "/CHECKS=ELABORATION"); - end Compiler; - end Debug; - @end group - @end smallexample - - @smallexample - @group - project Release is - for Object_Dir use "release"; - for Exec_Dir use "."; - for Main use ("proc"); - - package Compiler is - for Default_Qualifiers ("Ada") use ("/OPTIMIZE=ALL"); - end Compiler; - end Release; - @end group - @end smallexample - - @noindent - The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case - insensitive), and analogously the project defined by @file{release.gpr} is - @code{"Release"}. For consistency the file should have the same name as the - project, and the project file's extension should be @code{"gpr"}. These - conventions are not required, but a warning is issued if they are not followed. - - If the current directory is @file{/temp}, then the command - @smallexample - GNAT MAKE -P/common/debug.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/debug}, and the @code{proc} - executable also in @file{/common/debug}, using the qualifier settings defined in - the project file. - - Likewise, the command - @smallexample - GNAT MAKE -P/common/release.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/release}, and the @code{proc} - executable in @file{/common}, using the qualifier settings from the project file. - - @node Source Files - @unnumberedsubsubsec Source Files - - @noindent - If a project file does not explicitly specify a set of source directories or - a set of source files, then by default the project's source files are the - Ada source files in the project file directory. Thus @file{PACK.ADS}, - @file{PACK.ADB}, and @file{PROC.ADB} are the source files for both projects. - - @node Specifying the Object Directory - @unnumberedsubsubsec Specifying the Object Directory - - @noindent - Several project properties are modeled by Ada-style @emph{attributes}; - you define the property by supplying the equivalent of an Ada attribute - definition clause in the project file. - A project's object directory is such a property; the corresponding - attribute is @code{Object_Dir}, and its value is a string expression. A - directory may be specified either as absolute or as relative; in the latter - case, it is relative to the project file directory. Thus the compiler's - output is directed to @file{/common/debug} (for the @code{Debug} project) - and to @file{/common/release} (for the @code{Release} project). If - @code{Object_Dir} is not specified, then the default is the project file - directory. - - @node Specifying the Exec Directory - @unnumberedsubsubsec Specifying the Exec Directory - - @noindent - A project's exec directory is another property; the corresponding - attribute is @code{Exec_Dir}, and its value is also a string expression, - either specified as relative or absolute. If @code{Exec_Dir} is not specified, - then the default is the object directory (which may also be the project file - directory if attribute @code{Object_Dir} is not specified). Thus the executable - is placed in @file{/common/debug} for the @code{Debug} project (attribute - @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release} - project. - - @node Project File Packages - @unnumberedsubsubsec Project File Packages - - @noindent - A GNAT tool integrated with the Project Manager is modeled by a - corresponding package in the project file. - The @code{Debug} project defines the packages @code{Builder} - (for @command{GNAT MAKE}) and @code{Compiler}; - the @code{Release} project defines only the @code{Compiler} package. - - The Ada package syntax is not to be taken literally. Although packages in - project files bear a surface resemblance to packages in Ada source code, the - notation is simply a way to convey a grouping of properties for a named - entity. Indeed, the package names permitted in project files are restricted - to a predefined set, corresponding to the project-aware tools, and the contents - of packages are limited to a small set of constructs. - The packages in the example above contain attribute definitions. - - - @node Specifying Qualifier Settings - @unnumberedsubsubsec Specifying Qualifier Settings - - @noindent - Qualifier settings for a project-aware tool can be specified through attributes - in the package corresponding to the tool. - The example above illustrates one of the relevant attributes, - @code{Default_Qualifiers}, defined in the packages in both project files. - Unlike simple attributes like @code{Source_Dirs}, @code{Default_Qualifiers} is - known as an @emph{associative array}. When you define this attribute, you must - supply an "index" (a literal string), and the effect of the attribute - definition is to set the value of the "array" at the specified "index". - For the @code{Default_Qualifiers} attribute, the index is a programming - language (in our case, Ada) , and the value specified (after @code{use}) - must be a list of string expressions. - - The attributes permitted in project files are restricted to a predefined set. - Some may appear at project level, others in packages. - For any attribute that is an associate array, the index must always be a - literal string, but the restrictions on this string (e.g., a file name or a - language name) depend on the individual attribute. - Also depending on the attribute, its specified value will need to be either a - string or a string list. - - In the @code{Debug} project, we set the qualifiers for two tools, - @command{GNAT MAKE} and the compiler, and thus we include corresponding - packages, with each package defining the @code{Default_Qualifiers} attribute - with index @code{"Ada"}. - Note that the package corresponding to - @command{GNAT MAKE} is named @code{Builder}. The @code{Release} project is - similar, but with just the @code{Compiler} package. - - In project @code{Debug} above the qualifiers starting with @option{-gnat} that - are specified in package @code{Compiler} could have been placed in package - @code{Builder}, since @command{GNAT MAKE} transmits all such qualifiers to the - compiler. - - @node Main Subprograms - @unnumberedsubsubsec Main Subprograms - - @noindent - One of the properties of a project is its list of main subprograms (actually - a list of names of source files containing main subprograms, with the file - extension optional. This property is captured in the @code{Main} attribute, - whose value is a list of strings. If a project defines the @code{Main} - attribute, then you do not need to identify the main subprogram(s) when - invoking @command{GNAT MAKE} (see @ref{GNAT MAKE and Project Files}). - - @node Source File Naming Conventions - @unnumberedsubsubsec Source File Naming Conventions - - @noindent - Since the project files do not specify any source file naming conventions, - the GNAT defaults are used. The mechanism for defining source file naming - conventions -- a package named @code{Naming} -- will be described below - (@pxref{Naming Schemes}). - - @node Source Language(s) - @unnumberedsubsubsec Source Language(s) - - @noindent - Since the project files do not specify a @code{Languages} attribute, by - default the GNAT tools assume that the language of the project file is Ada. - More generally, a project can comprise source files - in Ada, C, and/or other languages. - - @node Using External Variables - @subsection Using External Variables - - @noindent - Instead of supplying different project files for debug and release, we can - define a single project file that queries an external variable (set either - on the command line or via an environment variable) in order to - conditionally define the appropriate settings. Again, assume that the - source files @file{PACK.ADS}, @file{PACK.ADB}, and @file{PROC.ADB} are - located in directory @file{/common}. The following project file, - @file{build.gpr}, queries the external variable named @code{STYLE} and - defines an object directory and qualifier settings based on whether the value - is @code{"deb"} (debug) or @code{"rel"} (release), where the default is - @code{"deb"}. - - @smallexample - @group - project Build is - for Main use ("proc"); - - type Style_Type is ("deb", "rel"); - Style : Style_Type := external ("STYLE", "deb"); - - case Style is - when "deb" => - for Object_Dir use "debug"; - - when "rel" => - for Object_Dir use "release"; - for Exec_Dir use "."; - end case; - @end group - - @group - package Builder is - - case Style is - when "deb" => - for Default_Qualifiers ("Ada") use ("-g"); - end case; - - end Builder; - @end group - - @group - package Compiler is - - case Style is - when "deb" => - for Default_Qualifiers ("Ada") use ("/CHECKS=ASSERTIONS", "/CHECKS=OVERFLOW", "/CHECKS=ELABORATION"); - - when "rel" => - for Default_Qualifiers ("Ada") use ("/OPTIMIZE=ALL"); - end case; - - end Compiler; - - end Build; - @end group - @end smallexample - - @noindent - @code{Style_Type} is an example of a @emph{string type}, which is the project - file analog of an Ada enumeration type but containing string literals rather - than identifiers. @code{Style} is declared as a variable of this type. - - The form @code{external("STYLE", "deb")} is known as an - @emph{external reference}; its first argument is the name of an - @emph{external variable}, and the second argument is a default value to be - used if the external variable doesn't exist. You can define an external - variable on the command line via the @option{-X} qualifier, or you can use an - environment variable as an external variable. - - Each @code{case} construct is expanded by the Project Manager based on the - value of @code{Style}. Thus the command - @smallexample - GNAT MAKE -P/common/build.gpr -XSTYLE=deb - @end smallexample - - @noindent - is equivalent to the @command{GNAT MAKE} invocation using the project file - @file{debug.gpr} in the earlier example. So is the command - @smallexample - GNAT MAKE -P/common/build.gpr - @end smallexample - - @noindent - since @code{"deb"} is the default for @code{STYLE}. - - Analogously, - @smallexample - GNAT MAKE -P/common/build.gpr -XSTYLE=rel - @end smallexample - - @noindent - is equivalent to the @command{GNAT MAKE} invocation using the project file - @file{release.gpr} in the earlier example. - - - @node Importing Other Projects - @subsection Importing Other Projects - - @noindent - A compilation unit in a source file in one project may depend on compilation - units in source files in other projects. To obtain this behavior, the - dependent project must @emph{import} the projects containing the needed source - files. This effect is embodied in syntax similar to an Ada @code{with} clause, - but the "with"ed entities are strings denoting project files. - - As an example, suppose that the two projects @code{GUI_Proj} and - @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and - @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm}, - respectively. Assume that the source files for @code{GUI_Proj} are - @file{GUI.ADS} and @file{GUI.ADB}, and that the source files for - @code{Comm_Proj} are @file{COMM.ADS} and @file{COMM.ADB}, with each set of - files located in its respective project file directory. Diagrammatically: - - @smallexample - @group - /gui - gui_proj.gpr - GUI.ADS - GUI.ADB - @end group - - @group - /comm - comm_proj.gpr - COMM.ADS - COMM.ADB - @end group - @end smallexample - - @noindent - We want to develop an application in directory @file{/app} that "with"s the - packages @code{GUI} and @code{Comm}, using the properties of the - corresponding project files (e.g. the qualifier settings and object directory). - Skeletal code for a main procedure might be something like the following: - - @smallexample - @group - with GUI, Comm; - procedure App_Main is - ... - begin - ... - end App_Main; - @end group - @end smallexample - - @noindent - Here is a project file, @file{app_proj.gpr}, that achieves the desired - effect: - - @smallexample - @group - with "/gui/gui_proj", "/comm/comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Building an executable is achieved through the command: - @smallexample - GNAT MAKE -P/app/app_proj - @end smallexample - @noindent - which will generate the @code{app_main} executable in the directory where - @file{app_proj.gpr} resides. - - If an imported project file uses the standard extension (@code{gpr}) then - (as illustrated above) the @code{with} clause can omit the extension. - - Our example specified an absolute path for each imported project file. - Alternatively, you can omit the directory if either - @itemize @bullet - @item - The imported project file is in the same directory as the importing project - file, or - @item - You have defined an environment variable @code{ADA_PROJECT_PATH} that - includes the directory containing the needed project file. - @end itemize - - @noindent - Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and - @file{/comm}, then our project file @file{app_proj.gpr} could be written as - follows: - - @smallexample - @group - with "gui_proj", "comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Importing other projects raises the possibility of ambiguities. For - example, the same unit might be present in different imported projects, or - it might be present in both the importing project and an imported project. - Both of these conditions are errors. Note that in the current version of - the Project Manager, it is illegal to have an ambiguous unit even if the - unit is never referenced by the importing project. This restriction may be - relaxed in a future release. - - @node Extending a Project - @subsection Extending a Project - - @noindent - A common situation in large software systems is to have multiple - implementations for a common interface; in Ada terms, multiple versions of a - package body for the same specification. For example, one implementation - might be safe for use in tasking programs, while another might only be used - in sequential applications. This can be modeled in GNAT using the concept - of @emph{project extension}. If one project (the "child") @emph{extends} - another project (the "parent") then by default all source files of the - parent project are inherited by the child, but the child project can - override any of the parent's source files with new versions, and can also - add new files. This facility is the project analog of extension in - Object-Oriented Programming. Project hierarchies are permitted (a child - project may be the parent of yet another project), and a project that - inherits one project can also import other projects. - - As an example, suppose that directory @file{/seq} contains the project file - @file{seq_proj.gpr} and the source files @file{PACK.ADS}, @file{PACK.ADB}, - and @file{PROC.ADB}: - - @smallexample - @group - /seq - PACK.ADS - PACK.ADB - PROC.ADB - seq_proj.gpr - @end group - @end smallexample - - @noindent - Note that the project file can simply be empty (that is, no attribute or - package is defined): - - @smallexample - @group - project Seq_Proj is - end Seq_Proj; - @end group - @end smallexample - - @noindent - implying that its source files are all the Ada source files in the project - directory. - - Suppose we want to supply an alternate version of @file{PACK.ADB}, in - directory @file{/tasking}, but use the existing versions of @file{PACK.ADS} - and @file{PROC.ADB}. We can define a project @code{Tasking_Proj} that - inherits @code{Seq_Proj}: - - @smallexample - @group - /tasking - PACK.ADB - tasking_proj.gpr - @end group - - @group - project Tasking_Proj extends "/seq/seq_proj" is - end Tasking_Proj; - @end group - @end smallexample - - @noindent - The version of @file{PACK.ADB} used in a build depends on which project file - is specified. - - Note that we could have designed this using project import rather than - project inheritance; a @code{base} project would contain the sources for - @file{PACK.ADS} and @file{PROC.ADB}, a sequential project would import - @code{base} and add @file{PACK.ADB}, and likewise a tasking project would - import @code{base} and add a different version of @file{PACK.ADB}. The - choice depends on whether other sources in the original project need to be - overridden. If they do, then project extension is necessary, otherwise, - importing is sufficient. - - - @c *********************** - @c * Project File Syntax * - @c *********************** - - @node Project File Syntax - @section Project File Syntax - - @menu - * Basic Syntax:: - * Packages:: - * Expressions:: - * String Types:: - * Variables:: - * Attributes:: - * Associative Array Attributes:: - * case Constructions:: - @end menu - - @noindent - This section describes the structure of project files. - - A project may be an @emph{independent project}, entirely defined by a single - project file. Any Ada source file in an independent project depends only - on the predefined library and other Ada source files in the same project. - - @noindent - A project may also @dfn{depend on} other projects, in either or both of the following ways: - @itemize @bullet - @item It may import any number of projects - @item It may extend at most one other project - @end itemize - - @noindent - The dependence relation is a directed acyclic graph (the subgraph reflecting - the "extends" relation is a tree). - - A project's @dfn{immediate sources} are the source files directly defined by - that project, either implicitly by residing in the project file's directory, - or explicitly through any of the source-related attributes described below. - More generally, a project @var{proj}'s @dfn{sources} are the immediate sources - of @var{proj} together with the immediate sources (unless overridden) of any - project on which @var{proj} depends (either directly or indirectly). - - @node Basic Syntax - @subsection Basic Syntax - - @noindent - As seen in the earlier examples, project files have an Ada-like syntax. - The minimal project file is: - @smallexample - @group - project Empty is - - end Empty; - @end group - @end smallexample - - @noindent - The identifier @code{Empty} is the name of the project. - This project name must be present after the reserved - word @code{end} at the end of the project file, followed by a semi-colon. - - Any name in a project file, such as the project name or a variable name, - has the same syntax as an Ada identifier. - - The reserved words of project files are the Ada reserved words plus - @code{extends}, @code{external}, and @code{project}. Note that the only Ada - reserved words currently used in project file syntax are: - - @itemize @bullet - @item - @code{case} - @item - @code{end} - @item - @code{for} - @item - @code{is} - @item - @code{others} - @item - @code{package} - @item - @code{renames} - @item - @code{type} - @item - @code{use} - @item - @code{when} - @item - @code{with} - @end itemize - - @noindent - Comments in project files have the same syntax as in Ada, two consecutives - hyphens through the end of the line. - - @node Packages - @subsection Packages - - @noindent - A project file may contain @emph{packages}. The name of a package must be one - of the identifiers (case insensitive) from a predefined list, and a package - with a given name may only appear once in a project file. The predefined list - includes the following packages: - - @itemize @bullet - @item - @code{Naming} - @item - @code{Builder} - @item - @code{Compiler} - @item - @code{Binder} - @item - @code{Linker} - @item - @code{Finder} - @item - @code{Cross_Reference} - @item - @code{GNAT LIST} - @end itemize - - @noindent - (The complete list of the package names and their attributes can be found - in file @file{PRJ-ATTR.ADB}). - - @noindent - In its simplest form, a package may be empty: - - @smallexample - @group - project Simple is - package Builder is - end Builder; - end Simple; - @end group - @end smallexample - - @noindent - A package may contain @emph{attribute declarations}, - @emph{variable declarations} and @emph{case constructions}, as will be - described below. - - When there is ambiguity between a project name and a package name, - the name always designates the project. To avoid possible confusion, it is - always a good idea to avoid naming a project with one of the - names allowed for packages or any name that starts with @code{gnat}. - - - @node Expressions - @subsection Expressions - - @noindent - An @emph{expression} is either a @emph{string expression} or a - @emph{string list expression}. - - A @emph{string expression} is either a @emph{simple string expression} or a - @emph{compound string expression}. - - A @emph{simple string expression} is one of the following: - @itemize @bullet - @item A literal string; e.g.@code{"comm/my_proj.gpr"} - @item A string-valued variable reference (see @ref{Variables}) - @item A string-valued attribute reference (see @ref{Attributes}) - @item An external reference (see @ref{External References in Project Files}) - @end itemize - - @noindent - A @emph{compound string expression} is a concatenation of string expressions, - using @code{"&"} - @smallexample - Path & "/" & File_Name & ".ADS" - @end smallexample - - @noindent - A @emph{string list expression} is either a - @emph{simple string list expression} or a - @emph{compound string list expression}. - - A @emph{simple string list expression} is one of the following: - @itemize @bullet - @item A parenthesized list of zero or more string expressions, separated by commas - @smallexample - File_Names := (File_Name, "GNAT.ADC", File_Name & ".orig"); - Empty_List := (); - @end smallexample - @item A string list-valued variable reference - @item A string list-valued attribute reference - @end itemize - - @noindent - A @emph{compound string list expression} is the concatenation (using - @code{"&"}) of a simple string list expression and an expression. Note that - each term in a compound string list expression, except the first, may be - either a string expression or a string list expression. - - @smallexample - @group - File_Name_List := () & File_Name; -- One string in this list - Extended_File_Name_List := File_Name_List & (File_Name & ".orig"); - -- Two strings - Big_List := File_Name_List & Extended_File_Name_List; - -- Concatenation of two string lists: three strings - Illegal_List := "GNAT.ADC" & Extended_File_Name_List; - -- Illegal: must start with a string list - @end group - @end smallexample - - - @node String Types - @subsection String Types - - @noindent - The value of a variable may be restricted to a list of string literals. - The restricted list of string literals is given in a - @emph{string type declaration}. - - Here is an example of a string type declaration: - - @smallexample - type OS is ("NT, "nt", "Unix", "Linux", "other OS"); - @end smallexample - - @noindent - Variables of a string type are called @emph{typed variables}; all other - variables are called @emph{untyped variables}. Typed variables are - particularly useful in @code{case} constructions - (see @ref{case Constructions}). - - A string type declaration starts with the reserved word @code{type}, followed - by the name of the string type (case-insensitive), followed by the reserved - word @code{is}, followed by a parenthesized list of one or more string literals - separated by commas, followed by a semicolon. - - The string literals in the list are case sensitive and must all be different. - They may include any graphic characters allowed in Ada, including spaces. - - A string type may only be declared at the project level, not inside a package. - - A string type may be referenced by its name if it has been declared in the same - project file, or by its project name, followed by a dot, - followed by the string type name. - - - @node Variables - @subsection Variables - - @noindent - A variable may be declared at the project file level, or in a package. - Here are some examples of variable declarations: - - @smallexample - @group - This_OS : OS := external ("OS"); -- a typed variable declaration - That_OS := "Linux"; -- an untyped variable declaration - @end group - @end smallexample - - @noindent - A @emph{typed variable declaration} includes the variable name, followed by a colon, - followed by the name of a string type, followed by @code{:=}, followed by - a simple string expression. - - An @emph{untyped variable declaration} includes the variable name, - followed by @code{:=}, followed by an expression. Note that, despite the - terminology, this form of "declaration" resembles more an assignment - than a declaration in Ada. It is a declaration in several senses: - @itemize @bullet - @item - The variable name does not need to be defined previously - @item - The declaration establishes the @emph{kind} (string versus string list) of the - variable, and later declarations of the same variable need to be consistent - with this - @end itemize - - @noindent - A string variable declaration (typed or untyped) declares a variable - whose value is a string. This variable may be used as a string expression. - @smallexample - File_Name := "readme.txt"; - Saved_File_Name := File_Name & ".saved"; - @end smallexample - - @noindent - A string list variable declaration declares a variable whose value is a list - of strings. The list may contain any number (zero or more) of strings. - - @smallexample - Empty_List := (); - List_With_One_Element := ("/STYLE="); - List_With_Two_Elements := List_With_One_Element & "/STYLE=GNAT"; - Long_List := ("MAIN.ADA", "PACK1_.ADA", "PACK1.ADA", "PACK2_.ADA" - "PACK2.ADA", "UTIL_.ADA", "UTIL.ADA"); - @end smallexample - - @noindent - The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable. - - The same untyped variable may be declared several times. - In this case, the new value replaces the old one, - and any subsequent reference to the variable uses the new value. - However, as noted above, if a variable has been declared as a string, all subsequent - declarations must give it a string value. Similarly, if a variable has - been declared as a string list, all subsequent declarations - must give it a string list value. - - A @emph{variable reference} may take several forms: - - @itemize @bullet - @item The simple variable name, for a variable in the current package (if any) or in the current project - @item A context name, followed by a dot, followed by the variable name. - @end itemize - - @noindent - A @emph{context} may be one of the following: - - @itemize @bullet - @item The name of an existing package in the current project - @item The name of an imported project of the current project - @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly) - @item An imported/parent project name, followed by a dot, followed by a package name - @end itemize - - @noindent - A variable reference may be used in an expression. - - - @node Attributes - @subsection Attributes - - @noindent - A project (and its packages) may have @emph{attributes} that define the project's properties. - Some attributes have values that are strings; - others have values that are string lists. - - There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays} - (see @ref{Associative Array Attributes}). - - The names of the attributes are restricted; there is a list of project - attributes, and a list of package attributes for each package. - The names are not case sensitive. - - The project attributes are as follows (all are simple attributes): - - @multitable @columnfractions .4 .3 - @item @emph{Attribute Name} - @tab @emph{Value} - @item @code{Source_Files} - @tab string list - @item @code{Source_Dirs} - @tab string list - @item @code{Source_List_File} - @tab string - @item @code{Object_Dir} - @tab string - @item @code{Exec_Dir} - @tab string - @item @code{Main} - @tab string list - @item @code{Languages} - @tab string list - @item @code{Library_Dir} - @tab string - @item @code{Library_Name} - @tab string - @item @code{Library_Kind} - @tab string - @item @code{Library_Elaboration} - @tab string - @item @code{Library_Version} - @tab string - @end multitable - - @noindent - The attributes for package @code{Naming} are as follows - (see @ref{Naming Schemes}): - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Specification_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Implementation_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Separate_Suffix} - @tab simple attribute - @tab n/a - @tab string - @item @code{Casing} - @tab simple attribute - @tab n/a - @tab string - @item @code{Dot_Replacement} - @tab simple attribute - @tab n/a - @tab string - @item @code{Specification} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Implementation} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Specification_Exceptions} - @tab associative array - @tab language name - @tab string list - @item @code{Implementation_Exceptions} - @tab associative array - @tab language name - @tab string list - @end multitable - - @noindent - The attributes for package @code{Builder}, @code{Compiler}, @code{Binder}, - @code{Linker}, @code{Cross_Reference}, and @code{Finder} - are as follows (see @ref{Qualifiers and Project Files}). - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Default_Qualifiers} - @tab associative array - @tab language name - @tab string list - @item @code{Qualifiers} - @tab associative array - @tab file name - @tab string list - @end multitable - - @noindent - In addition, package @code{Builder} has a single string attribute - @code{Local_Configuration_Pragmas} and package @code{Builder} has a single - string attribute @code{Global_Configuration_Pragmas}. - - @noindent - The attribute for package @code{Glide} are not documented: they are for - internal use only. - - @noindent - Each simple attribute has a default value: the empty string (for string-valued - attributes) and the empty list (for string list-valued attributes). - - Similar to variable declarations, an attribute declaration defines a new value - for an attribute. - - Examples of simple attribute declarations: - - @smallexample - for Object_Dir use "objects"; - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - @noindent - A @dfn{simple attribute declaration} starts with the reserved word @code{for}, - followed by the name of the attribute, followed by the reserved word - @code{use}, followed by an expression (whose kind depends on the attribute), - followed by a semicolon. - - Attributes may be referenced in expressions. - The general form for such a reference is @code{'}: - the entity for which the attribute is defined, - followed by an apostrophe, followed by the name of the attribute. - For associative array attributes, a litteral string between parentheses - need to be supplied as index. - - Examples are: - - @smallexample - project'Object_Dir - Naming'Dot_Replacement - Imported_Project'Source_Dirs - Imported_Project.Naming'Casing - Builder'Default_Qualifiers("Ada") - @end smallexample - - @noindent - The entity may be: - @itemize @bullet - @item @code{project} for an attribute of the current project - @item The name of an existing package of the current project - @item The name of an imported project - @item The name of a parent project (extended by the current project) - @item An imported/parent project name, followed by a dot, - followed by a package name - @end itemize - - @noindent - Example: - @smallexample - @group - project Prj is - for Source_Dirs use project'Source_Dirs & "units"; - for Source_Dirs use project'Source_Dirs & "test/drivers" - end Prj; - @end group - @end smallexample - - @noindent - In the first attribute declaration, initially the attribute @code{Source_Dirs} - has the default value: an empty string list. After this declaration, - @code{Source_Dirs} is a string list of one element: "units". - After the second attribute declaration @code{Source_Dirs} is a string list of - two elements: "units" and "test/drivers". - - Note: this example is for illustration only. In practice, - the project file would contain only one attribute declaration: - - @smallexample - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - - @node Associative Array Attributes - @subsection Associative Array Attributes - - @noindent - Some attributes are defined as @emph{associative arrays}. An associative - array may be regarded as a function that takes a string as a parameter - and delivers a string or string list value as its result. - - Here are some examples of associative array attribute declarations: - - @smallexample - for Implementation ("main") use "MAIN.ADA"; - for Qualifiers ("MAIN.ADA") use ("-v", "/REPORT_ERRORS=VERBOSE"); - for Qualifiers ("MAIN.ADA") use Builder'Qualifiers ("MAIN.ADA") & "-g"; - @end smallexample - - @noindent - Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the - attribute, replacing the previous setting. - - - @node case Constructions - @subsection @code{case} Constructions - - @noindent - A @code{case} construction is used in a project file to effect conditional - behavior. - Here is a typical example: - - @smallexample - @group - project MyProj is - type OS_Type is ("Linux", "Unix", "NT", "VMS"); - - OS : OS_Type := external ("OS", "Linux"); - @end group - - @group - package Compiler is - case OS is - when "Linux" | "Unix" => - for Default_Qualifiers ("Ada") use ("-gnath"); - when "NT" => - for Default_Qualifiers ("Ada") use ("/POLLING_ENABLE"); - when others => - end case; - end Compiler; - end MyProj; - @end group - @end smallexample - - @noindent - The syntax of a @code{case} construction is based on the Ada case statement - (although there is no @code{null} construction for empty alternatives). - - Following the reserved word @code{case} there is the case variable (a typed - string variable), the reserved word @code{is}, and then a sequence of one or - more alternatives. - Each alternative comprises the reserved word @code{when}, either a list of - literal strings separated by the @code{"|"} character or the reserved word - @code{others}, and the @code{"=>"} token. - Each literal string must belong to the string type that is the type of the - case variable. - An @code{others} alternative, if present, must occur last. - The @code{end case;} sequence terminates the case construction. - - After each @code{=>}, there are zero or more constructions. The only - constructions allowed in a case construction are other case constructions and - attribute declarations. String type declarations, variable declarations and - package declarations are not allowed. - - The value of the case variable is often given by an external reference - (see @ref{External References in Project Files}). - - - @c **************************************** - @c * Objects and Sources in Project Files * - @c **************************************** - - @node Objects and Sources in Project Files - @section Objects and Sources in Project Files - - @menu - * Object Directory:: - * Exec Directory:: - * Source Directories:: - * Source File Names:: - @end menu - - @noindent - Each project has exactly one object directory and one or more source - directories. The source directories must contain at least one source file, - unless the project file explicitly specifies that no source files are present - (see @ref{Source File Names}). - - - @node Object Directory - @subsection Object Directory - - @noindent - The object directory for a project is the directory containing the compiler's - output (such as @file{ALI} files and object files) for the project's immediate - sources. Note that for inherited sources (when extending a parent project) the - parent project's object directory is used. - - The object directory is given by the value of the attribute @code{Object_Dir} - in the project file. - - @smallexample - for Object_Dir use "objects"; - @end smallexample - - @noindent - The attribute @var{Object_Dir} has a string value, the path name of the object - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be readable and writable. - - By default, when the attribute @code{Object_Dir} is not given an explicit value - or when its value is the empty string, the object directory is the same as the - directory containing the project file. - - - @node Exec Directory - @subsection Exec Directory - - @noindent - The exec directory for a project is the directory containing the executables - for the project's main subprograms. - - The exec directory is given by the value of the attribute @code{Exec_Dir} - in the project file. - - @smallexample - for Exec_Dir use "executables"; - @end smallexample - - @noindent - The attribute @var{Exec_Dir} has a string value, the path name of the exec - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be writable. - - By default, when the attribute @code{Exec_Dir} is not given an explicit value - or when its value is the empty string, the exec directory is the same as the - object directory of the project file. - - - @node Source Directories - @subsection Source Directories - - @noindent - The source directories of a project are specified by the project file - attribute @code{Source_Dirs}. - - This attribute's value is a string list. If the attribute is not given an - explicit value, then there is only one source directory, the one where the - project file resides. - - A @code{Source_Dirs} attribute that is explicitly defined to be the empty list, - as in - - @smallexample - for Source_Dirs use (); - @end smallexample - - @noindent - indicates that the project contains no source files. - - Otherwise, each string in the string list designates one or more - source directories. - - @smallexample - for Source_Dirs use ("sources", "test/drivers"); - @end smallexample - - @noindent - If a string in the list ends with @code{"/**"}, then the directory whose path - name precedes the two asterisks, as well as all its subdirectories - (recursively), are source directories. - - @smallexample - for Source_Dirs use ("/system/sources/**"); - @end smallexample - - @noindent - Here the directory @code{/system/sources} and all of its subdirectories - (recursively) are source directories. - - To specify that the source directories are the directory of the project file - and all of its subdirectories, you can declare @code{Source_Dirs} as follows: - @smallexample - for Source_Dirs use ("./**"); - @end smallexample - - @noindent - Each of the source directories must exist and be readable. - - - @node Source File Names - @subsection Source File Names - - @noindent - In a project that contains source files, their names may be specified by the - attributes @code{Source_Files} (a string list) or @code{Source_List_File} - (a string). Source file names never include any directory information. - - If the attribute @code{Source_Files} is given an explicit value, then each - element of the list is a source file name. - - @smallexample - for Source_Files use ("MAIN.ADB"); - for Source_Files use ("MAIN.ADB", "PACK1.ADS", "PACK2.ADB"); - @end smallexample - - @noindent - If the attribute @code{Source_Files} is not given an explicit value, - but the attribute @code{Source_List_File} is given a string value, - then the source file names are contained in the text file whose path name - (absolute or relative to the directory of the project file) is the - value of the attribute @code{Source_List_File}. - - Each line in the file that is not empty or is not a comment - contains a source file name. A comment line starts with two hyphens. - - @smallexample - for Source_List_File use "source_list.txt"; - @end smallexample - - @noindent - By default, if neither the attribute @code{Source_Files} nor the attribute - @code{Source_List_File} is given an explicit value, then each file in the - source directories that conforms to the project's naming scheme - (see @ref{Naming Schemes}) is an immediate source of the project. - - A warning is issued if both attributes @code{Source_Files} and - @code{Source_List_File} are given explicit values. In this case, the attribute - @code{Source_Files} prevails. - - Each source file name must be the name of one and only one existing source file - in one of the source directories. - - A @code{Source_Files} attribute defined with an empty list as its value - indicates that there are no source files in the project. - - Except for projects that are clearly specified as containing no Ada source - files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list, - or @code{Languages} specified without @code{"Ada"} in the list) - @smallexample - for Source_Dirs use (); - for Source_Files use (); - for Languages use ("C", "C++"); - @end smallexample - - @noindent - a project must contain at least one immediate source. - - Projects with no source files are useful as template packages - (see @ref{Packages in Project Files}) for other projects; in particular to - define a package @code{Naming} (see @ref{Naming Schemes}). - - - @c **************************** - @c * Importing Projects * - @c **************************** - - @node Importing Projects - @section Importing Projects - - @noindent - An immediate source of a project P may depend on source files that - are neither immediate sources of P nor in the predefined library. - To get this effect, P must @emph{import} the projects that contain the needed - source files. - - @smallexample - @group - with "project1", "utilities.gpr"; - with "/namings/apex.gpr"; - project Main is - ... - @end group - @end smallexample - - @noindent - As can be seen in this example, the syntax for importing projects is similar - to the syntax for importing compilation units in Ada. However, project files - use literal strings instead of names, and the @code{with} clause identifies - project files rather than packages. - - Each literal string is the file name or path name (absolute or relative) of a - project file. If a string is simply a file name, with no path, then its - location is determined by the @emph{project path}: - - @itemize @bullet - @item - If the environment variable @env{ADA_PROJECT_PATH} exists, then the project - path includes all the directories in this environment variable, plus the - directory of the project file. - - @item - If the environment variable @env{ADA_PROJECT_PATH} does not exist, - then the project path contains only one directory, namely the one where - the project file is located. - @end itemize - - @noindent - If a relative pathname is used as in - - @smallexample - with "tests/proj"; - @end smallexample - - @noindent - then the path is relative to the directory where the importing project file is - located. Any symbolic link will be fully resolved in the directory - of the importing project file before the imported project file is looked up. - - When the @code{with}'ed project file name does not have an extension, - the default is @file{.gpr}. If a file with this extension is not found, then - the file name as specified in the @code{with} clause (no extension) will be - used. In the above example, if a file @code{project1.gpr} is found, then it - will be used; otherwise, if a file @code{project1} exists then it will be used; - if neither file exists, this is an error. - - A warning is issued if the name of the project file does not match the - name of the project; this check is case insensitive. - - Any source file that is an immediate source of the imported project can be - used by the immediate sources of the importing project, and recursively. Thus - if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate - sources of @code{A} may depend on the immediate sources of @code{C}, even if - @code{A} does not import @code{C} explicitly. However, this is not recommended, - because if and when @code{B} ceases to import @code{C}, some sources in - @code{A} will no longer compile. - - A side effect of this capability is that cyclic dependences are not permitted: - if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not - allowed to import @code{A}. - - - @c ********************* - @c * Project Extension * - @c ********************* - - @node Project Extension - @section Project Extension - - @noindent - During development of a large system, it is sometimes necessary to use - modified versions of some of the source files without changing the original - sources. This can be achieved through a facility known as - @emph{project extension}. - - @smallexample - project Modified_Utilities extends "/baseline/utilities.gpr" is ... - @end smallexample - - @noindent - The project file for the project being extended (the @emph{parent}) is - identified by the literal string that follows the reserved word @code{extends}, - which itself follows the name of the extending project (the @emph{child}). - - By default, a child project inherits all the sources of its parent. - However, inherited sources can be overridden: a unit with the same name as one - in the parent will hide the original unit. - Inherited sources are considered to be sources (but not immediate sources) - of the child project; see @ref{Project File Syntax}. - - An inherited source file retains any qualifiers specified in the parent project. - - For example if the project @code{Utilities} contains the specification and the - body of an Ada package @code{Util_IO}, then the project - @code{Modified_Utilities} can contain a new body for package @code{Util_IO}. - The original body of @code{Util_IO} will not be considered in program builds. - However, the package specification will still be found in the project - @code{Utilities}. - - A child project can have only one parent but it may import any number of other - projects. - - A project is not allowed to import directly or indirectly at the same time a - child project and any of its ancestors. - - - @c **************************************** - @c * External References in Project Files * - @c **************************************** - - @node External References in Project Files - @section External References in Project Files - - @noindent - A project file may contain references to external variables; such references - are called @emph{external references}. - - An external variable is either defined as part of the environment (an - environment variable in Unix, for example) or else specified on the command - line via the @option{-X@emph{vbl}=@emph{value}} qualifier. If both, then the - command line value is used. - - An external reference is denoted by the built-in function - @code{external}, which returns a string value. This function has two forms: - @itemize @bullet - @item @code{external (external_variable_name)} - @item @code{external (external_variable_name, default_value)} - @end itemize - - @noindent - Each parameter must be a string literal. For example: - - @smallexample - external ("USER") - external ("OS", "Linux") - @end smallexample - - @noindent - In the form with one parameter, the function returns the value of - the external variable given as parameter. If this name is not present in the - environment, then the returned value is an empty string. - - In the form with two string parameters, the second parameter is - the value returned when the variable given as the first parameter is not - present in the environment. In the example above, if @code{"OS"} is not - the name of an environment variable and is not passed on the command line, - then the returned value will be @code{"Linux"}. - - An external reference may be part of a string expression or of a string - list expression, to define variables or attributes. - - @smallexample - @group - type Mode_Type is ("Debug", "Release"); - Mode : Mode_Type := external ("MODE"); - case Mode is - when "Debug" => - ... - @end group - @end smallexample - - - @c ***************************** - @c * Packages in Project Files * - @c ***************************** - - @node Packages in Project Files - @section Packages in Project Files - - @noindent - The @emph{package} is the project file feature that defines the settings for - project-aware tools. - For each such tool you can declare a corresponding package; the names for these - packages are preset (see @ref{Packages}) but are not case sensitive. - A package may contain variable declarations, attribute declarations, and case - constructions. - - @smallexample - @group - project Proj is - package Builder is -- used by GNAT MAKE - for Default_Qualifiers ("Ada") use ("-v", "-g"); - end Builder; - end Proj; - @end group - @end smallexample - - @noindent - A package declaration starts with the reserved word @code{package}, - followed by the package name (case insensitive), followed by the reserved word - @code{is}. It ends with the reserved word @code{end}, followed by the package - name, finally followed by a semi-colon. - - Most of the packages have an attribute @code{Default_Qualifiers}. - This attribute is an associative array, and its value is a string list. - The index of the associative array is the name of a programming language (case - insensitive). This attribute indicates the qualifier or qualifiers to be used - with the corresponding tool. - - Some packages also have another attribute, @code{Qualifiers}, an associative - array whose value is a string list. The index is the name of a source file. - This attribute indicates the qualifier or qualifiers to be used by the corresponding - tool when dealing with this specific file. - - Further information on these qualifier-related attributes is found in - @ref{Qualifiers and Project Files}. - - A package may be declared as a @emph{renaming} of another package; e.g., from - the project file for an imported project. - - @smallexample - @group - with "/global/apex.gpr"; - project Example is - package Naming renames Apex.Naming; - ... - end Example; - @end group - @end smallexample - - @noindent - Packages that are renamed in other project files often come from project files - that have no sources: they are just used as templates. Any modification in the - template will be reflected automatically in all the project files that rename - a package from the template. - - In addition to the tool-oriented packages, you can also declare a package - named @code{Naming} to establish specialized source file naming conventions - (see @ref{Naming Schemes}). - - - @c ************************************ - @c * Variables from Imported Projects * - @c ************************************ - - @node Variables from Imported Projects - @section Variables from Imported Projects - - @noindent - An attribute or variable defined in an imported or parent project can - be used in expressions in the importing / extending project. - Such an attribute or variable is prefixed with the name of the project - and (if relevant) the name of package where it is defined. - - @smallexample - @group - with "imported"; - project Main extends "base" is - Var1 := Imported.Var; - Var2 := Base.Var & ".new"; - @end group - - @group - package Builder is - for Default_Qualifiers ("Ada") use Imported.Builder.Ada_Qualifiers & - "/STYLE=GNAT" & "-v"; - end Builder; - @end group - - @group - package Compiler is - for Default_Qualifiers ("Ada") use Base.Compiler.Ada_Qualifiers; - end Compiler; - end Main; - @end group - @end smallexample - - @noindent - In this example: - - @itemize @bullet - @item - @code{Var1} is a copy of the variable @code{Var} defined in the project file - @file{"imported.gpr"} - @item - the value of @code{Var2} is a copy of the value of variable @code{Var} - defined in the project file @file{base.gpr}, concatenated with @code{".new"} - @item - attribute @code{Default_Qualifiers ("Ada")} in package @code{Builder} - is a string list that includes in its value a copy of variable - @code{Ada_Qualifiers} defined in the @code{Builder} package in project file - @file{imported.gpr} plus two new elements: @option{"/STYLE=GNAT"} and @option{"-v"}; - @item - attribute @code{Default_Qualifiers ("Ada")} in package @code{Compiler} - is a copy of the variable @code{Ada_Qualifiers} defined in the @code{Compiler} - package in project file @file{base.gpr}, the project being extended. - @end itemize - - - @c ****************** - @c * Naming Schemes * - @c ****************** - - @node Naming Schemes - @section Naming Schemes - - @noindent - Sometimes an Ada software system is ported from a foreign compilation - environment to GNAT, with file names that do not use the default GNAT - conventions. Instead of changing all the file names (which for a variety of - reasons might not be possible), you can define the relevant file naming scheme - in the @code{Naming} package in your project file. For example, the following - package models the Apex file naming rules: - - @smallexample - @group - package Naming is - for Casing use "lowercase"; - for Dot_Replacement use "."; - for Specification_Suffix ("Ada") use ".1.ADA"; - for Implementation_Suffix ("Ada") use ".2.ADA"; - end Naming; - @end group - @end smallexample - - @noindent - You can define the following attributes in package @code{Naming}: - - @table @code - - @item @var{Casing} - This must be a string with one of the three values @code{"lowercase"}, - @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive. - - @noindent - If @var{Casing} is not specified, then the default is @code{"lowercase"}. - - @item @var{Dot_Replacement} - This must be a string whose value satisfies the following conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start or end with an alphanumeric character - @item It cannot be a single underscore - @item It cannot start with an underscore followed by an alphanumeric - @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."} - @end itemize - - @noindent - If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. - - @item @var{Specification_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @end itemize - @noindent - If @code{Specification_Suffix ("Ada")} is not specified, then the default is - @code{".ADS"}. - - @item @var{Implementation_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @item It cannot be a suffix of @code{Specification_Suffix} - @end itemize - @noindent - If @code{Implementation_Suffix ("Ada")} is not specified, then the default is - @code{".ADB"}. - - @item @var{Separate_Suffix} - This must be a string whose value satisfies the same conditions as - @code{Implementation_Suffix}. - - @noindent - If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same - value as @code{Implementation_Suffix ("Ada")}. - - @item @var{Specification} - @noindent - You can use the @code{Specification} attribute, an associative array, to define - the source file name for an individual Ada compilation unit's spec. The array - index must be a string literal that identifies the Ada unit (case insensitive). - The value of this attribute must be a string that identifies the file that - contains this unit's spec (case sensitive or insensitive depending on the - operating system). - - @smallexample - for Specification ("MyPack.MyChild") use "mypack.mychild.spec"; - @end smallexample - - @item @var{Implementation} - - You can use the @code{Implementation} attribute, an associative array, to - define the source file name for an individual Ada compilation unit's body - (possibly a subunit). The array index must be a string literal that identifies - the Ada unit (case insensitive). The value of this attribute must be a string - that identifies the file that contains this unit's body or subunit (case - sensitive or insensitive depending on the operating system). - - @smallexample - for Implementation ("MyPack.MyChild") use "mypack.mychild.body"; - @end smallexample - @end table - - - @c ******************** - @c * Library Projects * - @c ******************** - - @node Library Projects - @section Library Projects - - @noindent - @emph{Library projects} are projects whose object code is placed in a library. - (Note that this facility is not yet supported on all platforms) - - To create a library project, you need to define in its project file - two project-level attributes: @code{Library_Name} and @code{Library_Dir}. - Additionally, you may define the library-related attributes - @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}. - - The @code{Library_Name} attribute has a string value that must start with a - letter and include only letters and digits. - - The @code{Library_Dir} attribute has a string value that designates the path - (absolute or relative) of the directory where the library will reside. - It must designate an existing directory, and this directory needs to be - different from the project's object directory. It also needs to be writable. - - If both @code{Library_Name} and @code{Library_Dir} are specified and - are legal, then the project file defines a library project. The optional - library-related attributes are checked only for such project files. - - The @code{Library_Kind} attribute has a string value that must be one of the - following (case insensitive): @code{"static"}, @code{"dynamic"} or - @code{"relocatable"}. If this attribute is not specified, the library is a - static library. Otherwise, the library may be dynamic or relocatable. - Depending on the operating system, there may or may not be a distinction - between dynamic and relocatable libraries. For example, on Unix there is no - such distinction. - - The @code{Library_Version} attribute has a string value whose interpretation - is platform dependent. On Unix, it is used only for dynamic/relocatable - libraries as the internal name of the library (the @code{"soname"}). If the - library file name (built from the @code{Library_Name}) is different from the - @code{Library_Version}, then the library file will be a symbolic link to the - actual file whose name will be @code{Library_Version}. - - Example (on Unix): - - @smallexample - @group - project Plib is - - Version := "1"; - - for Library_Dir use "lib_dir"; - for Library_Name use "dummy"; - for Library_Kind use "relocatable"; - for Library_Version use "libdummy.so." & Version; - - end Plib; - @end group - @end smallexample - - @noindent - Directory @file{lib_dir} will contain the internal library file whose name - will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to - @file{libdummy.so.1}. - - When @command{GNAT MAKE} detects that a project file (not the main project file) - is a library project file, it will check all immediate sources of the project - and rebuild the library if any of the sources have been recompiled. - All @file{ALI} files will also be copied from the object directory to the - library directory. To build executables, @command{GNAT MAKE} will use the - library rather than the individual object files. - - - @c ************************************* - @c * Qualifiers Related to Project Files * - @c ************************************* - @node Qualifiers Related to Project Files - @section Qualifiers Related to Project Files - - @noindent - The following qualifiers are used by GNAT tools that support project files: - - @table @code - - @item @option{-P@var{project}} - Indicates the name of a project file. This project file will be parsed with - the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external - references indicated by @option{-X} qualifiers, if any. - - @noindent - There must be only one @option{-P} qualifier on the command line. - - @noindent - Since the Project Manager parses the project file only after all the qualifiers - on the command line are checked, the order of the qualifiers @option{-P}, - @option{-Vp@emph{x}} or @option{-X} is not significant. - - @item @option{-X@var{name=value}} - Indicates that external variable @var{name} has the value @var{value}. - The Project Manager will use this value for occurrences of - @code{external(name)} when parsing the project file. - - @noindent - If @var{name} or @var{value} includes a space, then @var{name=value} should be - put between quotes. - @smallexample - -XOS=NT - -X"user=John Doe" - @end smallexample - - @noindent - Several @option{-X} qualifiers can be used simultaneously. - If several @option{-X} qualifiers specify the same @var{name}, only the last one - is used. - - @noindent - An external variable specified with a @option{-X} qualifier takes precedence - over the value of the same name in the environment. - - @item @option{-vP@emph{x}} - Indicates the verbosity of the parsing of GNAT project files. - @option{-vP0} means Default (no output for syntactically correct project - files); - @option{-vP1} means Medium; - @option{-vP2} means High. - @noindent - The default is Default. - @noindent - If several @option{-vP@emph{x}} qualifiers are present, only the last one is - used. - - @end table - - - @c ********************************** - @c * Tools Supporting Project Files * - @c ********************************** - - @node Tools Supporting Project Files - @section Tools Supporting Project Files - - @menu - * GNAT MAKE and Project Files:: - * The GNAT Driver and Project Files:: - @end menu - - @node GNAT MAKE and Project Files - @subsection GNAT MAKE and Project Files - - @noindent - This section covers two topics related to @command{GNAT MAKE} and project files: - defining qualifiers for @command{GNAT MAKE} and for the tools that it invokes; - and the use of the @code{Main} attribute. - - @menu - * Qualifiers and Project Files:: - * Project Files and Main Subprograms:: - @end menu - - @node Qualifiers and Project Files - @subsubsection Qualifiers and Project Files - - @noindent - For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and - @code{Linker}, you can specify a @code{Default_Qualifiers} attribute, a - @code{Qualifiers} attribute, or both; as their names imply, these qualifier-related - attributes affect which qualifiers are used for which files when - @command{GNAT MAKE} is invoked. As will be explained below, these - package-contributed qualifiers precede the qualifiers passed on the - @command{GNAT MAKE} command line. - - The @code{Default_Qualifiers} attribute is an associative array indexed by - language name (case insensitive) and returning a string list. For example: - - @smallexample - @group - package Compiler is - for Default_Qualifiers ("Ada") use ("/STYLE=", "-v"); - end Compiler; - @end group - @end smallexample - - @noindent - The @code{Qualifiers} attribute is also an associative array, indexed by a file - name (which may or may not be case sensitive, depending on the operating - system) and returning a string list. For example: - - @smallexample - @group - package Builder is - for Qualifiers ("MAIN1.ADB") use ("/OPTIMIZE=ALL"); - for Qualifiers ("MAIN2.ADB") use ("-g"); - end Builder; - @end group - @end smallexample - - @noindent - For the @code{Builder} package, the file names should designate source files - for main subprograms. For the @code{Binder} and @code{Linker} packages, the - file names should designate @file{ALI} or source files for main subprograms. - In each case just the file name (without explicit extension) is acceptable. - - For each tool used in a program build (@command{GNAT MAKE}, the compiler, the - binder, and the linker), its corresponding package @dfn{contributes} a set of - qualifiers for each file on which the tool is invoked, based on the - qualifier-related attributes defined in the package. In particular, the qualifiers - that each of these packages contributes for a given file @var{f} comprise: - - @itemize @bullet - @item - the value of attribute @code{Qualifiers (@var{f})}, if it is specified in the - package for the given file, - @item - otherwise, the value of @code{Default_Qualifiers ("Ada")}, if it is specified in - the package. - @end itemize - - @noindent - If neither of these attributes is defined in the package, then the package does - not contribute any qualifiers for the given file. - - When @command{GNAT MAKE} is invoked on a file, the qualifiers comprise two sets, - in the following order: those contributed for the file by the @code{Builder} - package; and the qualifiers passed on the command line. - - When @command{GNAT MAKE} invokes a tool (compiler, binder, linker) on a file, - the qualifiers passed to the tool comprise three sets, in the following order: - - @enumerate - @item - the applicable qualifiers contributed for the file by the @code{Builder} package - in the project file supplied on the command line; - - @item - those contributed for the file by the package (in the relevant project file -- - see below) corresponding to the tool; and - - @item - the applicable qualifiers passed on the command line. - @end enumerate - - @noindent - The term @emph{applicable qualifiers} reflects the fact that @command{GNAT MAKE} - qualifiers may or may not be passed to individual tools, depending on the - individual qualifier. - - @command{GNAT MAKE} may invoke the compiler on source files from different - projects. The Project Manager will use the appropriate project file to - determine the @code{Compiler} package for each source file being compiled. - Likewise for the @code{Binder} and @code{Linker} packages. - - As an example, consider the following package in a project file: - - @smallexample - @group - project Proj1 is - package Compiler is - for Default_Qualifiers ("Ada") use ("-g"); - for Qualifiers ("A.ADB") use ("/OPTIMIZE=SOME"); - for Qualifiers ("B.ADB") use ("/OPTIMIZE=ALL", "/STYLE="); - end Compiler; - end Proj1; - @end group - @end smallexample - - @noindent - If @command{GNAT MAKE} is invoked with this project file, and it needs to - compile, say, the files @file{A.ADB}, @file{B.ADB}, and @file{C.ADB}, then - @file{A.ADB} will be compiled with the qualifier @option{/OPTIMIZE=SOME}, @file{B.ADB} - with qualifiers @option{/OPTIMIZE=ALL} and @option{/STYLE=}, and @file{C.ADB} with - @option{-g}. - - Another example illustrates the ordering of the qualifiers contributed by - different packages: - - @smallexample - @group - project Proj2 is - package Builder is - for Qualifiers ("MAIN.ADB") use ("-g", "/OPTIMIZE=SOME", "-f"); - end Builder; - @end group - - @group - package Compiler is - for Qualifiers ("MAIN.ADB") use ("/OPTIMIZE=ALL"); - end Compiler; - end Proj2; - @end group - @end smallexample - - @noindent - If you issue the command: - - @smallexample - GNAT MAKE -PProj2 /OPTIMIZE=NONE main - @end smallexample - - @noindent - then the compiler will be invoked on @file{MAIN.ADB} with the following sequence of qualifiers - - @smallexample - -g /OPTIMIZE=SOME /OPTIMIZE=ALL /OPTIMIZE=NONE - @end smallexample - - with the last @option{-O} qualifier having precedence over the earlier ones; - several other qualifiers (such as @option{-c}) are added implicitly. - - The qualifiers @option{-g} and @option{/OPTIMIZE=SOME} are contributed by package - @code{Builder}, @option{/OPTIMIZE=ALL} is contributed by the package @code{Compiler} - and @option{/OPTIMIZE=NONE} comes from the command line. - - The @option{-g} qualifier will also be passed in the invocation of - @command{GNAT LINK.} - - A final example illustrates qualifier contributions from packages in different - project files: - - @smallexample - @group - project Proj3 is - for Source_Files use ("PACK.ADS", "PACK.ADB"); - package Compiler is - for Default_Qualifiers ("Ada") use ("/CHECKS=ASSERTIONS"); - end Compiler; - end Proj3; - @end group - - @group - with "Proj3"; - project Proj4 is - for Source_Files use ("FOO_MAIN.ADB", "BAR_MAIN.ADB"); - package Builder is - for Qualifiers ("FOO_MAIN.ADB") use ("-s", "-g"); - end Builder; - end Proj4; - @end group - - @group - -- Ada source file: - with Pack; - procedure Foo_Main is - ... - end Foo_Main; - @end group - @end smallexample - - If the command is - @smallexample - GNAT MAKE -PProj4 FOO_MAIN.ADB /COMPILER_QUALIFIERS /CHECKS=OVERFLOW - @end smallexample - - @noindent - then the qualifiers passed to the compiler for @file{FOO_MAIN.ADB} are - @option{-g} (contributed by the package @code{Proj4.Builder}) and - @option{/CHECKS=OVERFLOW} (passed on the command line). - When the imported package @code{Pack} is compiled, the qualifiers used are - @option{-g} from @code{Proj4.Builder}, @option{/CHECKS=ASSERTIONS} (contributed from - package @code{Proj3.Compiler}, and @option{/CHECKS=OVERFLOW} from the command line. - - - @node Project Files and Main Subprograms - @subsubsection Project Files and Main Subprograms - - @noindent - When using a project file, you can invoke @command{GNAT MAKE} - with several main subprograms, by specifying their source files on the command - line. Each of these needs to be an immediate source file of the project. - - @smallexample - GNAT MAKE -Pprj main1 main2 main3 - @end smallexample - - @noindent - When using a project file, you can also invoke @command{GNAT MAKE} without - explicitly specifying any main, and the effect depends on whether you have - defined the @code{Main} attribute. This attribute has a string list value, - where each element in the list is the name of a source file (the file - extension is optional) containing a main subprogram. - - If the @code{Main} attribute is defined in a project file as a non-empty - string list and the qualifier @option{-u} is not used on the command line, then - invoking @command{GNAT MAKE} with this project file but without any main on the - command line is equivalent to invoking @command{GNAT MAKE} with all the file - names in the @code{Main} attribute on the command line. - - Example: - @smallexample - @group - project Prj is - for Main use ("main1", "main2", "main3"); - end Prj; - @end group - @end smallexample - - @noindent - With this project file, @code{"GNAT MAKE -Pprj"} is equivalent to - @code{"GNAT MAKE -Pprj main1 main2 main3"}. - - When the project attribute @code{Main} is not specified, or is specified - as an empty string list, or when the qualifier @option{-u} is used on the command - line, then invoking @command{GNAT MAKE} with no main on the command line will - result in all immediate sources of the project file being checked, and - potentially recompiled. Depending on the presence of the qualifier @option{-u}, - sources from other project files on which the immediate sources of the main - project file depend are also checked and potentially recompiled. In other - words, the @option{-u} qualifier is applied to all of the immediate sources of themain project file. - - - @node The GNAT Driver and Project Files - @subsection The GNAT Driver and Project Files - - @noindent - A number of GNAT tools, other than @command{GNAT MAKE} are project-aware: - @command{GNAT BIND}, @command{GNAT FIND}, @command{GNAT LINK}, @command{GNAT LIST} - and @command{GNAT XREF}. However, none of these tools can be invoked directly - with a project file qualifier (@code{-P}). They need to be invoke through the - @command{gnat} driver. - - The @command{gnat} driver is a front-end that accepts a number of commands and - call the corresponding tool. It has been designed initially for VMS to convert - VMS style qualifiers to Unix style qualifiers, but it is now available to all - the GNAT supported platforms. - - On non VMS platforms, the @command{gnat} driver accepts the following commands - (case insensitive): - - @itemize @bullet - @item - BIND to invoke @command{GNAT BIND} - @item - CHOP to invoke @command{GNAT CHOP} - @item - COMP or COMPILE to invoke the compiler - @item - ELIM to invoke @command{GNAT ELIM} - @item - FIND to invoke @command{GNAT FIND} - @item - KR or KRUNCH to invoke @command{GNAT KRUNCH} - @item - LINK to invoke @command{GNAT LINK} - @item - LS or LIST to invoke @command{GNAT LIST} - @item - MAKE to invoke @command{GNAT MAKE} - @item - NAME to invoke @command{gnatname} - @item - PREP or PREPROCESS to invoke @command{GNAT PREPROCESS} - @item - PSTA or STANDARD to invoke @command{GNAT STANDARD} - @item - STUB to invoke @command{GNAT STUB} - @item - XREF to invoke @command{GNAT XREF} - @end itemize - - @noindent - Note that the compiler is invoked using the command @command{GNAT MAKE -f -u}. - - @noindent - Following the command, you may put qualifiers and arguments for the invoked - tool. - - @smallexample - gnat bind -C MAIN.ALI - gnat ls -a main - gnat chop foo.txt - @end smallexample - - @noindent - In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project - file related qualifiers (@code{-P}, @code{-X} and @code{-vPx}) may be used in - addition to the qualifiers of the invoking tool. - - @noindent - For each of these command, there is possibly a package in the main project that - corresponds to the invoked tool. - - @itemize @bullet - @item - package @code{Binder} for command BIND (invoking @code{GNAT BIND}) - - @item - package @code{Finder} for command FIND (invoking @code{GNAT FIND}) - - @item - package @code{GNAT LIST} for command LS or LIST (invoking @code{GNAT LIST}) - - @item - package @code{Linker} for command LINK (invoking @code{GNAT LINK}) - - @item - package @code{Cross_Reference} for command XREF (invoking @code{GNAT LINK}) - - @end itemize - - @noindent - Package @code{GNAT LIST} has a unique attribute @code{Qualifiers}, a simple variable - with a string list value. It contains qualifiers for the invocation of - @code{GNAT LIST}. - - @smallexample - @group - project Proj1 is - package GNAT LIST is - for Qualifiers use ("-a", "-v"); - end GNAT LIST; - end Proj1; - @end group - @end smallexample - - @noindent - All other packages contains a qualifier @code{Default_Qualifiers}, an associative - array, indexed by the programming language (case insensitive) and having a - string list value. @code{Default_Qualifiers ("Ada")} contains the qualifiers for - the invocation of the tool corresponding to the package. - - @smallexample - @group - project Proj is - - for Source_Dirs use ("./**"); - - package GNAT LIST is - for Qualifiers use ("-a", "-v"); - end GNAT LIST; - @end group - @group - - package Binder is - for Default_Qualifiers ("Ada") use ("-C", "-e"); - end Binder; - @end group - @group - - package Linker is - for Default_Qualifiers ("Ada") use ("-C"); - end Linker; - @end group - @group - - package Finder is - for Default_Qualifiers ("Ada") use ("-a", "-f"); - end Finder; - @end group - @group - - package Cross_Reference is - for Default_Qualifiers ("Ada") use ("-a", "-f", "-d", "-u"); - end Cross_Reference; - end Proj; - @end group - @end smallexample - - @noindent - With the above project file, commands such as - - @smallexample - gnat ls -Pproj main - gnat xref -Pproj main - gnat bind -Pproj MAIN.ALI - @end smallexample - - @noindent - will set up the environment properly and invoke the tool with the qualifiers - found in the package corresponding to the tool. - - - - - @node An Extended Example - @section An Extended Example - - @noindent - Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources - in the respective directories. We would like to build them with a single - @command{GNAT MAKE} command, and we would like to place their object files into - @file{.build} subdirectories of the source directories. Furthermore, we would - like to have to have two separate subdirectories in @file{.build} -- - @file{release} and @file{debug} -- which will contain the object files compiled with - different set of compilation flags. - - In other words, we have the following structure: - - @smallexample - @group - main - |- prog1 - | |- .build - | | debug - | | release - |- prog2 - |- .build - | debug - | release - @end group - @end smallexample - - @noindent - Here are the project files that we need to create in a directory @file{main} - to maintain this structure: - - @enumerate - - @item We create a @code{Common} project with a package @code{Compiler} that - specifies the compilation qualifiers: - - @smallexample - File "common.gpr": - @group - @b{project} Common @b{is} - - @b{for} Source_Dirs @b{use} (); -- No source files - @end group - - @group - @b{type} Build_Type @b{is} ("release", "debug"); - Build : Build_Type := External ("BUILD", "debug"); - @end group - @group - @b{package} Compiler @b{is} - @b{case} Build @b{is} - @b{when} "release" => - @b{for} Default_Qualifiers ("Ada") @b{use} ("/OPTIMIZE=ALL"); - @b{when} "debug" => - @b{for} Default_Qualifiers ("Ada") @b{use} ("-g"); - @b{end case}; - @b{end} Compiler; - - @b{end} Common; - @end group - @end smallexample - - @item We create separate projects for the two programs: - - @smallexample - @group - File "prog1.gpr": - - @b{with} "common"; - @b{project} Prog1 @b{is} - - @b{for} Source_Dirs @b{use} ("prog1"); - @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Prog1; - @end group - @end smallexample - - @smallexample - @group - File "prog2.gpr": - - @b{with} "common"; - @b{project} Prog2 @b{is} - - @b{for} Source_Dirs @b{use} ("prog2"); - @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @end group - @b{end} Prog2; - @end smallexample - - @item We create a wrapping project @var{Main}: - - @smallexample - @group - File "main.gpr": - - @b{with} "common"; - @b{with} "prog1"; - @b{with} "prog2"; - @b{project} Main @b{is} - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Main; - @end group - @end smallexample - - @item Finally we need to create a dummy procedure that @code{with}s (either - explicitly or implicitly) all the sources of our two programs. - - @end enumerate - - @noindent - Now we can build the programs using the command - - @smallexample - GNAT MAKE -Pmain dummy - @end smallexample - - @noindent - for the Debug mode, or - - @smallexample - GNAT MAKE -Pmain -XBUILD=release - @end smallexample - - @noindent - for the Release mode. - - - @c ******************************** - @c * Project File Complete Syntax * - @c ******************************** - - @node Project File Complete Syntax - @section Project File Complete Syntax - - @smallexample - project ::= - context_clause project_declaration - - context_clause ::= - @{with_clause@} - - with_clause ::= - @b{with} literal_string @{ , literal_string @} ; - - project_declaration ::= - @b{project} simple_name [ @b{extends} literal_string ] @b{is} - @{declarative_item@} - @b{end} simple_name; - - declarative_item ::= - package_declaration | - typed_string_declaration | - other_declarative_item - - package_declaration ::= - @b{package} simple_name package_completion - - package_completion ::= - package_body | package_renaming - - package body ::= - @b{is} - @{other_declarative_item@} - @b{end} simple_name ; - - package_renaming ::== - @b{renames} simple_name.simple_name ; - - typed_string_declaration ::= - @b{type} _simple_name @b{is} - ( literal_string @{, literal_string@} ); - - other_declarative_item ::= - attribute_declaration | - typed_variable_declaration | - variable_declaration | - case_construction - - attribute_declaration ::= - @b{for} attribute @b{use} expression ; - - attribute ::= - simple_name | - simple_name ( literal_string ) - - typed_variable_declaration ::= - simple_name : name := string_expression ; - - variable_declaration ::= - simple_name := expression; - - expression ::= - term @{& term@} - - term ::= - literal_string | - string_list | - name | - external_value | - attribute_reference - - literal_string ::= - (same as Ada) - - string_list ::= - ( expression @{ , expression @} ) - - external_value ::= - @b{external} ( literal_string [, literal_string] ) - - attribute_reference ::= - attribute_parent ' simple_name [ ( literal_string ) ] - - attribute_parent ::= - @b{project} | - simple_name | - simple_name . simple_name - - case_construction ::= - @b{case} name @b{is} - @{case_item@} - @b{end case} ; - - case_item ::= - @b{when} discrete_choice_list => @{case_construction | attribute_declaration@} - - discrete_choice_list ::= - literal_string @{| literal_string@} - - name ::= - simple_name @{. simple_name@} - - simple_name ::= - identifier (same as Ada) - - @end smallexample - - - @node Elaboration Order Handling in GNAT - @chapter Elaboration Order Handling in GNAT - @cindex Order of elaboration - @cindex Elaboration control - - @menu - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - @end menu - - @noindent - This chapter describes the handling of elaboration code in Ada 95 and - in GNAT, and discusses how the order of elaboration of program units can - be controlled in GNAT, either automatically or with explicit programming - features. - - @node Elaboration Code in Ada 95 - @section Elaboration Code in Ada 95 - - @noindent - Ada 95 provides rather general mechanisms for executing code at elaboration - time, that is to say before the main program starts executing. Such code arises - in three contexts: - - @table @asis - @item Initializers for variables. - Variables declared at the library level, in package specs or bodies, can - require initialization that is performed at elaboration time, as in: - @smallexample - @cartouche - Sqrt_Half : Float := Sqrt (0.5); - @end cartouche - @end smallexample - - @item Package initialization code - Code in a @code{BEGIN-END} section at the outer level of a package body is - executed as part of the package body elaboration code. - - @item Library level task allocators - Tasks that are declared using task allocators at the library level - start executing immediately and hence can execute at elaboration time. - @end table - - @noindent - Subprogram calls are possible in any of these contexts, which means that - any arbitrary part of the program may be executed as part of the elaboration - code. It is even possible to write a program which does all its work at - elaboration time, with a null main program, although stylistically this - would usually be considered an inappropriate way to structure - a program. - - An important concern arises in the context of elaboration code: - we have to be sure that it is executed in an appropriate order. What we - have is a series of elaboration code sections, potentially one section - for each unit in the program. It is important that these execute - in the correct order. Correctness here means that, taking the above - example of the declaration of @code{Sqrt_Half}, - if some other piece of - elaboration code references @code{Sqrt_Half}, - then it must run after the - section of elaboration code that contains the declaration of - @code{Sqrt_Half}. - - There would never be any order of elaboration problem if we made a rule - that whenever you @code{with} a unit, you must elaborate both the spec and body - of that unit before elaborating the unit doing the @code{with}'ing: - - @smallexample - @group - @cartouche - @b{with} Unit_1; - @b{package} Unit_2 @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - would require that both the body and spec of @code{Unit_1} be elaborated - before the spec of @code{Unit_2}. However, a rule like that would be far too - restrictive. In particular, it would make it impossible to have routines - in separate packages that were mutually recursive. - - You might think that a clever enough compiler could look at the actual - elaboration code and determine an appropriate correct order of elaboration, - but in the general case, this is not possible. Consider the following - example. - - In the body of @code{Unit_1}, we have a procedure @code{Func_1} - that references - the variable @code{Sqrt_1}, which is declared in the elaboration code - of the body of @code{Unit_1}: - - @smallexample - @cartouche - Sqrt_1 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_1} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_1 = 1 @b{then} - Q := Unit_2.Func_2; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - @code{Unit_2} is exactly parallel, - it has a procedure @code{Func_2} that references - the variable @code{Sqrt_2}, which is declared in the elaboration code of - the body @code{Unit_2}: - - @smallexample - @cartouche - Sqrt_2 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_2} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_2 = 2 @b{then} - Q := Unit_1.Func_1; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the question is, which of the following orders of elaboration is - acceptable: - - @smallexample - @group - Spec of Unit_1 - Spec of Unit_2 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - or - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_2 - Body of Unit_1 - @end group - @end smallexample - - @noindent - If you carefully analyze the flow here, you will see that you cannot tell - at compile time the answer to this question. - If @code{expression_1} is not equal to 1, - and @code{expression_2} is not equal to 2, - then either order is acceptable, because neither of the function calls is - executed. If both tests evaluate to true, then neither order is acceptable - and in fact there is no correct order. - - If one of the two expressions is true, and the other is false, then one - of the above orders is correct, and the other is incorrect. For example, - if @code{expression_1} = 1 and @code{expression_2} /= 2, - then the call to @code{Func_2} - will occur, but not the call to @code{Func_1.} - This means that it is essential - to elaborate the body of @code{Unit_1} before - the body of @code{Unit_2}, so the first - order of elaboration is correct and the second is wrong. - - By making @code{expression_1} and @code{expression_2} - depend on input data, or perhaps - the time of day, we can make it impossible for the compiler or binder - to figure out which of these expressions will be true, and hence it - is impossible to guarantee a safe order of elaboration at run time. - - @node Checking the Elaboration Order in Ada 95 - @section Checking the Elaboration Order in Ada 95 - - @noindent - In some languages that involve the same kind of elaboration problems, - e.g. Java and C++, the programmer is expected to worry about these - ordering problems himself, and it is common to - write a program in which an incorrect elaboration order gives - surprising results, because it references variables before they - are initialized. - Ada 95 is designed to be a safe language, and a programmer-beware approach is - clearly not sufficient. Consequently, the language provides three lines - of defense: - - @table @asis - @item Standard rules - Some standard rules restrict the possible choice of elaboration - order. In particular, if you @code{with} a unit, then its spec is always - elaborated before the unit doing the @code{with}. Similarly, a parent - spec is always elaborated before the child spec, and finally - a spec is always elaborated before its corresponding body. - - @item Dynamic elaboration checks - @cindex Elaboration checks - @cindex Checks, elaboration - Dynamic checks are made at run time, so that if some entity is accessed - before it is elaborated (typically by means of a subprogram call) - then the exception (@code{Program_Error}) is raised. - - @item Elaboration control - Facilities are provided for the programmer to specify the desired order - of elaboration. - @end table - - Let's look at these facilities in more detail. First, the rules for - dynamic checking. One possible rule would be simply to say that the - exception is raised if you access a variable which has not yet been - elaborated. The trouble with this approach is that it could require - expensive checks on every variable reference. Instead Ada 95 has two - rules which are a little more restrictive, but easier to check, and - easier to state: - - @table @asis - @item Restrictions on calls - A subprogram can only be called at elaboration time if its body - has been elaborated. The rules for elaboration given above guarantee - that the spec of the subprogram has been elaborated before the - call, but not the body. If this rule is violated, then the - exception @code{Program_Error} is raised. - - @item Restrictions on instantiations - A generic unit can only be instantiated if the body of the generic - unit has been elaborated. Again, the rules for elaboration given above - guarantee that the spec of the generic unit has been elaborated - before the instantiation, but not the body. If this rule is - violated, then the exception @code{Program_Error} is raised. - @end table - - @noindent - The idea is that if the body has been elaborated, then any variables - it references must have been elaborated; by checking for the body being - elaborated we guarantee that none of its references causes any - trouble. As we noted above, this is a little too restrictive, because a - subprogram that has no non-local references in its body may in fact be safe - to call. However, it really would be unsafe to rely on this, because - it would mean that the caller was aware of details of the implementation - in the body. This goes against the basic tenets of Ada. - - A plausible implementation can be described as follows. - A Boolean variable is associated with each subprogram - and each generic unit. This variable is initialized to False, and is set to - True at the point body is elaborated. Every call or instantiation checks the - variable, and raises @code{Program_Error} if the variable is False. - - Note that one might think that it would be good enough to have one Boolean - variable for each package, but that would not deal with cases of trying - to call a body in the same package as the call - that has not been elaborated yet. - Of course a compiler may be able to do enough analysis to optimize away - some of the Boolean variables as unnecessary, and @code{GNAT} indeed - does such optimizations, but still the easiest conceptual model is to - think of there being one variable per subprogram. - - @node Controlling the Elaboration Order in Ada 95 - @section Controlling the Elaboration Order in Ada 95 - - @noindent - In the previous section we discussed the rules in Ada 95 which ensure - that @code{Program_Error} is raised if an incorrect elaboration order is - chosen. This prevents erroneous executions, but we need mechanisms to - specify a correct execution and avoid the exception altogether. - To achieve this, Ada 95 provides a number of features for controlling - the order of elaboration. We discuss these features in this section. - - First, there are several ways of indicating to the compiler that a given - unit has no elaboration problems: - - @table @asis - @item packages that do not require a body - In Ada 95, a library package that does not require a body does not permit - a body. This means that if we have a such a package, as in: - - @smallexample - @group - @cartouche - @b{package} Definitions @b{is} - @b{generic} - @b{type} m @b{is new} integer; - @b{package} Subp @b{is} - @b{type} a @b{is array} (1 .. 10) @b{of} m; - @b{type} b @b{is array} (1 .. 20) @b{of} m; - @b{end} Subp; - @b{end} Definitions; - @end cartouche - @end group - @end smallexample - - @noindent - A package that @code{with}'s @code{Definitions} may safely instantiate - @code{Definitions.Subp} because the compiler can determine that there - definitely is no package body to worry about in this case - - @item pragma Pure - @cindex pragma Pure - @findex Pure - Places sufficient restrictions on a unit to guarantee that - no call to any subprogram in the unit can result in an - elaboration problem. This means that the compiler does not need - to worry about the point of elaboration of such units, and in - particular, does not need to check any calls to any subprograms - in this unit. - - @item pragma Preelaborate - @findex Preelaborate - @cindex pragma Preelaborate - This pragma places slightly less stringent restrictions on a unit than - does pragma Pure, - but these restrictions are still sufficient to ensure that there - are no elaboration problems with any calls to the unit. - - @item pragma Elaborate_Body - @findex Elaborate_Body - @cindex pragma Elaborate_Body - This pragma requires that the body of a unit be elaborated immediately - after its spec. Suppose a unit @code{A} has such a pragma, - and unit @code{B} does - a @code{with} of unit @code{A}. Recall that the standard rules require - the spec of unit @code{A} - to be elaborated before the @code{with}'ing unit; given the pragma in - @code{A}, we also know that the body of @code{A} - will be elaborated before @code{B}, so - that calls to @code{A} are safe and do not need a check. - @end table - - @noindent - Note that, - unlike pragma @code{Pure} and pragma @code{Preelaborate}, - the use of - @code{Elaborate_Body} does not guarantee that the program is - free of elaboration problems, because it may not be possible - to satisfy the requested elaboration order. - Let's go back to the example with @code{Unit_1} and @code{Unit_2}. - If a programmer - marks @code{Unit_1} as @code{Elaborate_Body}, - and not @code{Unit_2,} then the order of - elaboration will be: - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - Now that means that the call to @code{Func_1} in @code{Unit_2} - need not be checked, - it must be safe. But the call to @code{Func_2} in - @code{Unit_1} may still fail if - @code{Expression_1} is equal to 1, - and the programmer must still take - responsibility for this not being the case. - - If all units carry a pragma @code{Elaborate_Body}, then all problems are - eliminated, except for calls entirely within a body, which are - in any case fully under programmer control. However, using the pragma - everywhere is not always possible. - In particular, for our @code{Unit_1}/@code{Unit_2} example, if - we marked both of them as having pragma @code{Elaborate_Body}, then - clearly there would be no possible elaboration order. - - The above pragmas allow a server to guarantee safe use by clients, and - clearly this is the preferable approach. Consequently a good rule in - Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible, - and if this is not possible, - mark them as @code{Elaborate_Body} if possible. - As we have seen, there are situations where neither of these - three pragmas can be used. - So we also provide methods for clients to control the - order of elaboration of the servers on which they depend: - - @table @asis - @item pragma Elaborate (unit) - @findex Elaborate - @cindex pragma Elaborate - This pragma is placed in the context clause, after a @code{with} clause, - and it requires that the body of the named unit be elaborated before - the unit in which the pragma occurs. The idea is to use this pragma - if the current unit calls at elaboration time, directly or indirectly, - some subprogram in the named unit. - - @item pragma Elaborate_All (unit) - @findex Elaborate_All - @cindex pragma Elaborate_All - This is a stronger version of the Elaborate pragma. Consider the - following example: - - @smallexample - Unit A @code{with}'s unit B and calls B.Func in elab code - Unit B @code{with}'s unit C, and B.Func calls C.Func - @end smallexample - - @noindent - Now if we put a pragma @code{Elaborate (B)} - in unit @code{A}, this ensures that the - body of @code{B} is elaborated before the call, but not the - body of @code{C}, so - the call to @code{C.Func} could still cause @code{Program_Error} to - be raised. - - The effect of a pragma @code{Elaborate_All} is stronger, it requires - not only that the body of the named unit be elaborated before the - unit doing the @code{with}, but also the bodies of all units that the - named unit uses, following @code{with} links transitively. For example, - if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, - then it requires - not only that the body of @code{B} be elaborated before @code{A}, - but also the - body of @code{C}, because @code{B} @code{with}'s @code{C}. - @end table - - @noindent - We are now in a position to give a usage rule in Ada 95 for avoiding - elaboration problems, at least if dynamic dispatching and access to - subprogram values are not used. We will handle these cases separately - later. - - The rule is simple. If a unit has elaboration code that can directly or - indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate - a generic unit in a @code{with}'ed unit, - then if the @code{with}'ed unit does not have - pragma @code{Pure} or @code{Preelaborate}, then the client should have - a pragma @code{Elaborate_All} - for the @code{with}'ed unit. By following this rule a client is - assured that calls can be made without risk of an exception. - If this rule is not followed, then a program may be in one of four - states: - - @table @asis - @item No order exists - No order of elaboration exists which follows the rules, taking into - account any @code{Elaborate}, @code{Elaborate_All}, - or @code{Elaborate_Body} pragmas. In - this case, an Ada 95 compiler must diagnose the situation at bind - time, and refuse to build an executable program. - - @item One or more orders exist, all incorrect - One or more acceptable elaboration orders exists, and all of them - generate an elaboration order problem. In this case, the binder - can build an executable program, but @code{Program_Error} will be raised - when the program is run. - - @item Several orders exist, some right, some incorrect - One or more acceptable elaboration orders exists, and some of them - work, and some do not. The programmer has not controlled - the order of elaboration, so the binder may or may not pick one of - the correct orders, and the program may or may not raise an - exception when it is run. This is the worst case, because it means - that the program may fail when moved to another compiler, or even - another version of the same compiler. - - @item One or more orders exists, all correct - One ore more acceptable elaboration orders exist, and all of them - work. In this case the program runs successfully. This state of - affairs can be guaranteed by following the rule we gave above, but - may be true even if the rule is not followed. - @end table - - @noindent - Note that one additional advantage of following our Elaborate_All rule - is that the program continues to stay in the ideal (all orders OK) state - even if maintenance - changes some bodies of some subprograms. Conversely, if a program that does - not follow this rule happens to be safe at some point, this state of affairs - may deteriorate silently as a result of maintenance changes. - - You may have noticed that the above discussion did not mention - the use of @code{Elaborate_Body}. This was a deliberate omission. If you - @code{with} an @code{Elaborate_Body} unit, it still may be the case that - code in the body makes calls to some other unit, so it is still necessary - to use @code{Elaborate_All} on such units. - - @node Controlling Elaboration in GNAT - Internal Calls - @section Controlling Elaboration in GNAT - Internal Calls - - @noindent - In the case of internal calls, i.e. calls within a single package, the - programmer has full control over the order of elaboration, and it is up - to the programmer to elaborate declarations in an appropriate order. For - example writing: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - Q : Float := One; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - @end cartouche - @end group - @end smallexample - - @noindent - will obviously raise @code{Program_Error} at run time, because function - One will be called before its body is elaborated. In this case GNAT will - generate a warning that the call will raise @code{Program_Error}: - - @smallexample - @group - @cartouche - 1. procedure y is - 2. function One return Float; - 3. - 4. Q : Float := One; - | - >>> warning: cannot call "One" before body is elaborated - >>> warning: Program_Error will be raised at run time - - 5. - 6. function One return Float is - 7. begin - 8. return 1.0; - 9. end One; - 10. - 11. begin - 12. null; - 13. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that in this particular case, it is likely that the call is safe, because - the function @code{One} does not access any global variables. - Nevertheless in Ada 95, we do not want the validity of the check to depend on - the contents of the body (think about the separate compilation case), so this - is still wrong, as we discussed in the previous sections. - - The error is easily corrected by rearranging the declarations so that the - body of One appears before the declaration containing the call - (note that in Ada 95, - declarations can appear in any order, so there is no restriction that - would prevent this reordering, and if we write: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - - Q : Float := One; - @end cartouche - @end group - @end smallexample - - @noindent - then all is well, no warning is generated, and no - @code{Program_Error} exception - will be raised. - Things are more complicated when a chain of subprograms is executed: - - @smallexample - @group - @cartouche - @b{function} A @b{return} Integer; - @b{function} B @b{return} Integer; - @b{function} C @b{return} Integer; - - @b{function} B @b{return} Integer @b{is begin return} A; @b{end}; - @b{function} C @b{return} Integer @b{is begin return} B; @b{end}; - - X : Integer := C; - - @b{function} A @b{return} Integer @b{is begin return} 1; @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the call to @code{C} - at elaboration time in the declaration of @code{X} is correct, because - the body of @code{C} is already elaborated, - and the call to @code{B} within the body of - @code{C} is correct, but the call - to @code{A} within the body of @code{B} is incorrect, because the body - of @code{A} has not been elaborated, so @code{Program_Error} - will be raised on the call to @code{A}. - In this case GNAT will generate a - warning that @code{Program_Error} may be - raised at the point of the call. Let's look at the warning: - - @smallexample - @group - @cartouche - 1. procedure x is - 2. function A return Integer; - 3. function B return Integer; - 4. function C return Integer; - 5. - 6. function B return Integer is begin return A; end; - | - >>> warning: call to "A" before body is elaborated may - raise Program_Error - >>> warning: "B" called at line 7 - >>> warning: "C" called at line 9 - - 7. function C return Integer is begin return B; end; - 8. - 9. X : Integer := C; - 10. - 11. function A return Integer is begin return 1; end; - 12. - 13. begin - 14. null; - 15. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that the message here says "may raise", instead of the direct case, - where the message says "will be raised". That's because whether - @code{A} is - actually called depends in general on run-time flow of control. - For example, if the body of @code{B} said - - @smallexample - @group - @cartouche - @b{function} B @b{return} Integer @b{is} - @b{begin} - @b{if} some-condition-depending-on-input-data @b{then} - @b{return} A; - @b{else} - @b{return} 1; - @b{end if}; - @b{end} B; - @end cartouche - @end group - @end smallexample - - @noindent - then we could not know until run time whether the incorrect call to A would - actually occur, so @code{Program_Error} might - or might not be raised. It is possible for a compiler to - do a better job of analyzing bodies, to - determine whether or not @code{Program_Error} - might be raised, but it certainly - couldn't do a perfect job (that would require solving the halting problem - and is provably impossible), and because this is a warning anyway, it does - not seem worth the effort to do the analysis. Cases in which it - would be relevant are rare. - - In practice, warnings of either of the forms given - above will usually correspond to - real errors, and should be examined carefully and eliminated. - In the rare case where a warning is bogus, it can be suppressed by any of - the following methods: - - @itemize @bullet - @item - Compile with the @option{/WARNINGS=SUPPRESS} qualifier set - - @item - Suppress @code{Elaboration_Checks} for the called subprogram - - @item - Use pragma @code{Warnings_Off} to turn warnings off for the call - @end itemize - - @noindent - For the internal elaboration check case, - GNAT by default generates the - necessary run-time checks to ensure - that @code{Program_Error} is raised if any - call fails an elaboration check. Of course this can only happen if a - warning has been issued as described above. The use of pragma - @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress - some of these checks, meaning that it may be possible (but is not - guaranteed) for a program to be able to call a subprogram whose body - is not yet elaborated, without raising a @code{Program_Error} exception. - - @node Controlling Elaboration in GNAT - External Calls - @section Controlling Elaboration in GNAT - External Calls - - @noindent - The previous section discussed the case in which the execution of a - particular thread of elaboration code occurred entirely within a - single unit. This is the easy case to handle, because a programmer - has direct and total control over the order of elaboration, and - furthermore, checks need only be generated in cases which are rare - and which the compiler can easily detect. - The situation is more complex when separate compilation is taken into account. - Consider the following: - - @smallexample - @cartouche - @group - @b{package} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float; - @b{end} Math; - - @b{package body} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float @b{is} - @b{begin} - ... - @b{end} Sqrt; - @b{end} Math; - @end group - @group - @b{with} Math; - @b{package} Stuff @b{is} - X : Float := Math.Sqrt (0.5); - @b{end} Stuff; - - @b{with} Stuff; - @b{procedure} Main @b{is} - @b{begin} - ... - @b{end} Main; - @end group - @end cartouche - @end smallexample - - @noindent - where @code{Main} is the main program. When this program is executed, the - elaboration code must first be executed, and one of the jobs of the - binder is to determine the order in which the units of a program are - to be elaborated. In this case we have four units: the spec and body - of @code{Math}, - the spec of @code{Stuff} and the body of @code{Main}). - In what order should the four separate sections of elaboration code - be executed? - - There are some restrictions in the order of elaboration that the binder - can choose. In particular, if unit U has a @code{with} - for a package @code{X}, then you - are assured that the spec of @code{X} - is elaborated before U , but you are - not assured that the body of @code{X} - is elaborated before U. - This means that in the above case, the binder is allowed to choose the - order: - - @smallexample - spec of Math - spec of Stuff - body of Math - body of Main - @end smallexample - - @noindent - but that's not good, because now the call to @code{Math.Sqrt} - that happens during - the elaboration of the @code{Stuff} - spec happens before the body of @code{Math.Sqrt} is - elaborated, and hence causes @code{Program_Error} exception to be raised. - At first glance, one might say that the binder is misbehaving, because - obviously you want to elaborate the body of something you @code{with} - first, but - that is not a general rule that can be followed in all cases. Consider - - @smallexample - @group - @cartouche - @b{package} X @b{is} ... - - @b{package} Y @b{is} ... - - @b{with} X; - @b{package body} Y @b{is} ... - - @b{with} Y; - @b{package body} X @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - This is a common arrangement, and, apart from the order of elaboration - problems that might arise in connection with elaboration code, this works fine. - A rule that says that you must first elaborate the body of anything you - @code{with} cannot work in this case: - the body of @code{X} @code{with}'s @code{Y}, - which means you would have to - elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, - which means - you have to elaborate the body of @code{X} first, but ... and we have a - loop that cannot be broken. - - It is true that the binder can in many cases guess an order of elaboration - that is unlikely to cause a @code{Program_Error} - exception to be raised, and it tries to do so (in the - above example of @code{Math/Stuff/Spec}, the GNAT binder will - by default - elaborate the body of @code{Math} right after its spec, so all will be well). - - However, a program that blindly relies on the binder to be helpful can - get into trouble, as we discussed in the previous sections, so - GNAT - provides a number of facilities for assisting the programmer in - developing programs that are robust with respect to elaboration order. - - @node Default Behavior in GNAT - Ensuring Safety - @section Default Behavior in GNAT - Ensuring Safety - - @noindent - The default behavior in GNAT ensures elaboration safety. In its - default mode GNAT implements the - rule we previously described as the right approach. Let's restate it: - - @itemize - @item - @emph{If a unit has elaboration code that can directly or indirectly make a - call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit - in a @code{with}'ed unit, then if the @code{with}'ed unit - does not have pragma @code{Pure} or - @code{Preelaborate}, then the client should have an - @code{Elaborate_All} for the @code{with}'ed unit.} - @end itemize - - @noindent - By following this rule a client - is assured that calls and instantiations can be made without risk of an exception. - - In this mode GNAT traces all calls that are potentially made from - elaboration code, and puts in any missing implicit @code{Elaborate_All} - pragmas. - The advantage of this approach is that no elaboration problems - are possible if the binder can find an elaboration order that is - consistent with these implicit @code{Elaborate_All} pragmas. The - disadvantage of this approach is that no such order may exist. - - If the binder does not generate any diagnostics, then it means that it - has found an elaboration order that is guaranteed to be safe. However, - the binder may still be relying on implicitly generated - @code{Elaborate_All} pragmas so portability to other compilers than - GNAT is not guaranteed. - - If it is important to guarantee portability, then the compilations should - use the - @option{/WARNINGS=ELABORATION} - (warn on elaboration problems) qualifier. This will cause warning messages - to be generated indicating the missing @code{Elaborate_All} pragmas. - Consider the following source program: - - @smallexample - @group - @cartouche - @b{with} k; - @b{package} j @b{is} - m : integer := k.r; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - where it is clear that there - should be a pragma @code{Elaborate_All} - for unit @code{k}. An implicit pragma will be generated, and it is - likely that the binder will be able to honor it. However, - it is safer to include the pragma explicitly in the source. If this - unit is compiled with the - @option{/WARNINGS=ELABORATION} - qualifier, then the compiler outputs a warning: - - @smallexample - @group - @cartouche - 1. with k; - 2. package j is - 3. m : integer := k.r; - | - >>> warning: call to "r" may raise Program_Error - >>> warning: missing pragma Elaborate_All for "k" - - 4. end; - @end cartouche - @end group - @end smallexample - - @noindent - and these warnings can be used as a guide for supplying manually - the missing pragmas. - - This default mode is more restrictive than the Ada Reference - Manual, and it is possible to construct programs which will compile - using the dynamic model described there, but will run into a - circularity using the safer static model we have described. - - Of course any Ada compiler must be able to operate in a mode - consistent with the requirements of the Ada Reference Manual, - and in particular must have the capability of implementing the - standard dynamic model of elaboration with run-time checks. - - In GNAT, this standard mode can be achieved either by the use of - the @option{/CHECKS=ELABORATION} qualifier on the compiler (@code{GNAT COMPILE} or @code{GNAT MAKE}) - command, or by the use of the configuration pragma: - - @smallexample - pragma Elaboration_Checks (RM); - @end smallexample - - @noindent - Either approach will cause the unit affected to be compiled using the - standard dynamic run-time elaboration checks described in the Ada - Reference Manual. The static model is generally preferable, since it - is clearly safer to rely on compile and link time checks rather than - run-time checks. However, in the case of legacy code, it may be - difficult to meet the requirements of the static model. This - issue is further discussed in - @ref{What to Do If the Default Elaboration Behavior Fails}. - - Note that the static model provides a strict subset of the allowed - behavior and programs of the Ada Reference Manual, so if you do - adhere to the static model and no circularities exist, - then you are assured that your program will - work using the dynamic model. - - @node Elaboration Issues for Library Tasks - @section Elaboration Issues for Library Tasks - @cindex Library tasks, elaboration issues - @cindex Elaboration of library tasks - - @noindent - In this section we examine special elaboration issues that arise for - programs that declare library level tasks. - - Generally the model of execution of an Ada program is that all units are - elaborated, and then execution of the program starts. However, the - declaration of library tasks definitely does not fit this model. The - reason for this is that library tasks start as soon as they are declared - (more precisely, as soon as the statement part of the enclosing package - body is reached), that is to say before elaboration - of the program is complete. This means that if such a task calls a - subprogram, or an entry in another task, the callee may or may not be - elaborated yet, and in the standard - Reference Manual model of dynamic elaboration checks, you can even - get timing dependent Program_Error exceptions, since there can be - a race between the elaboration code and the task code. - - The static model of elaboration in GNAT seeks to avoid all such - dynamic behavior, by being conservative, and the conservative - approach in this particular case is to assume that all the code - in a task body is potentially executed at elaboration time if - a task is declared at the library level. - - This can definitely result in unexpected circularities. Consider - the following example - - @smallexample - package Decls is - task Lib_Task is - entry Start; - end Lib_Task; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - procedure Main is - begin - Decls.Lib_Task.Start; - end; - @end smallexample - - @noindent - If the above example is compiled in the default static elaboration - mode, then a circularity occurs. The circularity comes from the call - @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since - this call occurs in elaboration code, we need an implicit pragma - @code{Elaborate_All} for @code{Utils}. This means that not only must - the spec and body of @code{Utils} be elaborated before the body - of @code{Decls}, but also the spec and body of any unit that is - @code{with'ed} by the body of @code{Utils} must also be elaborated before - the body of @code{Decls}. This is the transitive implication of - pragma @code{Elaborate_All} and it makes sense, because in general - the body of @code{Put_Val} might have a call to something in a - @code{with'ed} unit. - - In this case, the body of Utils (actually its spec) @code{with's} - @code{Decls}. Unfortunately this means that the body of @code{Decls} - must be elaborated before itself, in case there is a call from the - body of @code{Utils}. - - Here is the exact chain of events we are worrying about: - - @enumerate - @item - In the body of @code{Decls} a call is made from within the body of a library - task to a subprogram in the package @code{Utils}. Since this call may - occur at elaboration time (given that the task is activated at elaboration - time), we have to assume the worst, i.e. that the - call does happen at elaboration time. - - @item - This means that the body and spec of @code{Util} must be elaborated before - the body of @code{Decls} so that this call does not cause an access before - elaboration. - - @item - Within the body of @code{Util}, specifically within the body of - @code{Util.Put_Val} there may be calls to any unit @code{with}'ed - by this package. - - @item - One such @code{with}'ed package is package @code{Decls}, so there - might be a call to a subprogram in @code{Decls} in @code{Put_Val}. - In fact there is such a call in this example, but we would have to - assume that there was such a call even if it were not there, since - we are not supposed to write the body of @code{Decls} knowing what - is in the body of @code{Utils}; certainly in the case of the - static elaboration model, the compiler does not know what is in - other bodies and must assume the worst. - - @item - This means that the spec and body of @code{Decls} must also be - elaborated before we elaborate the unit containing the call, but - that unit is @code{Decls}! This means that the body of @code{Decls} - must be elaborated before itself, and that's a circularity. - @end enumerate - - @noindent - Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in - the body of @code{Decls} you will get a true Ada Reference Manual - circularity that makes the program illegal. - - In practice, we have found that problems with the static model of - elaboration in existing code often arise from library tasks, so - we must address this particular situation. - - Note that if we compile and run the program above, using the dynamic model of - elaboration (that is to say use the @option{/CHECKS=ELABORATION} qualifier), - then it compiles, binds, - links, and runs, printing the expected result of 2. Therefore in some sense - the circularity here is only apparent, and we need to capture - the properties of this program that distinguish it from other library-level - tasks that have real elaboration problems. - - We have four possible answers to this question: - - @itemize @bullet - - @item - Use the dynamic model of elaboration. - - If we use the @option{/CHECKS=ELABORATION} qualifier, then as noted above, the program works. - Why is this? If we examine the task body, it is apparent that the task cannot - proceed past the - @code{accept} statement until after elaboration has been completed, because - the corresponding entry call comes from the main program, not earlier. - This is why the dynamic model works here. But that's really giving - up on a precise analysis, and we prefer to take this approach only if we cannot - solve the - problem in any other manner. So let us examine two ways to reorganize - the program to avoid the potential elaboration problem. - - @item - Split library tasks into separate packages. - - Write separate packages, so that library tasks are isolated from - other declarations as much as possible. Let us look at a variation on - the above program. - - @smallexample - package Decls1 is - task Lib_Task is - entry Start; - end Lib_Task; - end Decls1; - - with Utils; - package body Decls1 is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - end Decls1; - - package Decls2 is - type My_Int is new Integer; - function Ident (M : My_Int) return My_Int; - end Decls2; - - with Utils; - package body Decls2 is - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls2; - - with Decls2; - package Utils is - procedure Put_Val (Arg : Decls2.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls2.My_Int) is - begin - Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls1; - procedure Main is - begin - Decls1.Lib_Task.Start; - end; - @end smallexample - - @noindent - All we have done is to split @code{Decls} into two packages, one - containing the library task, and one containing everything else. Now - there is no cycle, and the program compiles, binds, links and executes - using the default static model of elaboration. - - @item - Declare separate task types. - - A significant part of the problem arises because of the use of the - single task declaration form. This means that the elaboration of - the task type, and the elaboration of the task itself (i.e. the - creation of the task) happen at the same time. A good rule - of style in Ada 95 is to always create explicit task types. By - following the additional step of placing task objects in separate - packages from the task type declaration, many elaboration problems - are avoided. Here is another modified example of the example program: - - @smallexample - package Decls is - task type Lib_Task_Type is - entry Start; - end Lib_Task_Type; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task_Type is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task_Type; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - package Declst is - Lib_Task : Decls.Lib_Task_Type; - end Declst; - - with Declst; - procedure Main is - begin - Declst.Lib_Task.Start; - end; - @end smallexample - - @noindent - What we have done here is to replace the @code{task} declaration in - package @code{Decls} with a @code{task type} declaration. Then we - introduce a separate package @code{Declst} to contain the actual - task object. This separates the elaboration issues for - the @code{task type} - declaration, which causes no trouble, from the elaboration issues - of the task object, which is also unproblematic, since it is now independent - of the elaboration of @code{Utils}. - This separation of concerns also corresponds to - a generally sound engineering principle of separating declarations - from instances. This version of the program also compiles, binds, links, - and executes, generating the expected output. - - @item - Use No_Entry_Calls_In_Elaboration_Code restriction. - @cindex No_Entry_Calls_In_Elaboration_Code - - The previous two approaches described how a program can be restructured - to avoid the special problems caused by library task bodies. in practice, - however, such restructuring may be difficult to apply to existing legacy code, - so we must consider solutions that do not require massive rewriting. - - Let us consider more carefully why our original sample program works - under the dynamic model of elaboration. The reason is that the code - in the task body blocks immediately on the @code{accept} - statement. Now of course there is nothing to prohibit elaboration - code from making entry calls (for example from another library level task), - so we cannot tell in isolation that - the task will not execute the accept statement during elaboration. - - However, in practice it is very unusual to see elaboration code - make any entry calls, and the pattern of tasks starting - at elaboration time and then immediately blocking on @code{accept} or - @code{select} statements is very common. What this means is that - the compiler is being too pessimistic when it analyzes the - whole package body as though it might be executed at elaboration - time. - - If we know that the elaboration code contains no entry calls, (a very safe - assumption most of the time, that could almost be made the default - behavior), then we can compile all units of the program under control - of the following configuration pragma: - - @smallexample - pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); - @end smallexample - - @noindent - This pragma can be placed in the @file{GNAT.ADC} file in the usual - manner. If we take our original unmodified program and compile it - in the presence of a @file{GNAT.ADC} containing the above pragma, - then once again, we can compile, bind, link, and execute, obtaining - the expected result. In the presence of this pragma, the compiler does - not trace calls in a task body, that appear after the first @code{accept} - or @code{select} statement, and therefore does not report a potential - circularity in the original program. - - The compiler will check to the extent it can that the above - restriction is not violated, but it is not always possible to do a - complete check at compile time, so it is important to use this - pragma only if the stated restriction is in fact met, that is to say - no task receives an entry call before elaboration of all units is completed. - - @end itemize - - @node Mixing Elaboration Models - @section Mixing Elaboration Models - @noindent - So far, we have assumed that the entire program is either compiled - using the dynamic model or static model, ensuring consistency. It - is possible to mix the two models, but rules have to be followed - if this mixing is done to ensure that elaboration checks are not - omitted. - - The basic rule is that @emph{a unit compiled with the static model cannot - be @code{with'ed} by a unit compiled with the dynamic model}. The - reason for this is that in the static model, a unit assumes that - its clients guarantee to use (the equivalent of) pragma - @code{Elaborate_All} so that no elaboration checks are required - in inner subprograms, and this assumption is violated if the - client is compiled with dynamic checks. - - The precise rule is as follows. A unit that is compiled with dynamic - checks can only @code{with} a unit that meets at least one of the - following criteria: - - @itemize @bullet - - @item - The @code{with'ed} unit is itself compiled with dynamic elaboration - checks (that is with the @option{/CHECKS=ELABORATION} qualifier. - - @item - The @code{with'ed} unit is an internal GNAT implementation unit from - the System, Interfaces, Ada, or GNAT hierarchies. - - @item - The @code{with'ed} unit has pragma Preelaborate or pragma Pure. - - @item - The @code{with'ing} unit (that is the client) has an explicit pragma - @code{Elaborate_All} for the @code{with'ed} unit. - - @end itemize - - @noindent - If this rule is violated, that is if a unit with dynamic elaboration - checks @code{with's} a unit that does not meet one of the above four - criteria, then the binder (@code{GNAT BIND}) will issue a warning - similar to that in the following example: - - @smallexample - warning: "X.ADS" has dynamic elaboration checks and with's - warning: "Y.ADS" which has static elaboration checks - @end smallexample - - @noindent - These warnings indicate that the rule has been violated, and that as a result - elaboration checks may be missed in the resulting executable file. - This warning may be suppressed using the @code{-ws} binder qualifier - in the usual manner. - - One useful application of this mixing rule is in the case of a subsystem - which does not itself @code{with} units from the remainder of the - application. In this case, the entire subsystem can be compiled with - dynamic checks to resolve a circularity in the subsystem, while - allowing the main application that uses this subsystem to be compiled - using the more reliable default static model. - - @node What to Do If the Default Elaboration Behavior Fails - @section What to Do If the Default Elaboration Behavior Fails - - @noindent - If the binder cannot find an acceptable order, it outputs detailed - diagnostics. For example: - @smallexample - @group - @iftex - @leftskip=0cm - @end iftex - error: elaboration circularity detected - info: "proc (body)" must be elaborated before "pack (body)" - info: reason: Elaborate_All probably needed in unit "pack (body)" - info: recompile "pack (body)" with /WARNINGS=ELABORATION - info: for full details - info: "proc (body)" - info: is needed by its spec: - info: "proc (spec)" - info: which is withed by: - info: "pack (body)" - info: "pack (body)" must be elaborated before "proc (body)" - info: reason: pragma Elaborate in unit "proc (body)" - @end group - - @end smallexample - - @noindent - In this case we have a cycle that the binder cannot break. On the one - hand, there is an explicit pragma Elaborate in @code{proc} for - @code{pack}. This means that the body of @code{pack} must be elaborated - before the body of @code{proc}. On the other hand, there is elaboration - code in @code{pack} that calls a subprogram in @code{proc}. This means - that for maximum safety, there should really be a pragma - Elaborate_All in @code{pack} for @code{proc} which would require that - the body of @code{proc} be elaborated before the body of - @code{pack}. Clearly both requirements cannot be satisfied. - Faced with a circularity of this kind, you have three different options. - - @table @asis - @item Fix the program - The most desirable option from the point of view of long-term maintenance - is to rearrange the program so that the elaboration problems are avoided. - One useful technique is to place the elaboration code into separate - child packages. Another is to move some of the initialization code to - explicitly called subprograms, where the program controls the order - of initialization explicitly. Although this is the most desirable option, - it may be impractical and involve too much modification, especially in - the case of complex legacy code. - - @item Perform dynamic checks - If the compilations are done using the - @option{/CHECKS=ELABORATION} - (dynamic elaboration check) qualifier, then GNAT behaves in - a quite different manner. Dynamic checks are generated for all calls - that could possibly result in raising an exception. With this qualifier, - the compiler does not generate implicit @code{Elaborate_All} pragmas. - The behavior then is exactly as specified in the Ada 95 Reference Manual. - The binder will generate an executable program that may or may not - raise @code{Program_Error}, and then it is the programmer's job to ensure - that it does not raise an exception. Note that it is important to - compile all units with the qualifier, it cannot be used selectively. - - @item Suppress checks - The drawback of dynamic checks is that they generate a - significant overhead at run time, both in space and time. If you - are absolutely sure that your program cannot raise any elaboration - exceptions, and you still want to use the dynamic elaboration model, - then you can use the configuration pragma - @code{Suppress (Elaboration_Checks)} to suppress all such checks. For - example this pragma could be placed in the @file{GNAT.ADC} file. - - @item Suppress checks selectively - When you know that certain calls in elaboration code cannot possibly - lead to an elaboration error, and the binder nevertheless generates warnings - on those calls and inserts Elaborate_All pragmas that lead to elaboration - circularities, it is possible to remove those warnings locally and obtain - a program that will bind. Clearly this can be unsafe, and it is the - responsibility of the programmer to make sure that the resulting program has - no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can - be used with different granularity to suppress warnings and break - elaboration circularities: - - @itemize @bullet - @item - Place the pragma that names the called subprogram in the declarative part - that contains the call. - - @item - Place the pragma in the declarative part, without naming an entity. This - disables warnings on all calls in the corresponding declarative region. - - @item - Place the pragma in the package spec that declares the called subprogram, - and name the subprogram. This disables warnings on all elaboration calls to - that subprogram. - - @item - Place the pragma in the package spec that declares the called subprogram, - without naming any entity. This disables warnings on all elaboration calls to - all subprograms declared in this spec. - @end itemize - - @noindent - These four cases are listed in order of decreasing safety, and therefore - require increasing programmer care in their application. Consider the - following program: - @smallexample - - package Pack1 is - function F1 return Integer; - X1 : Integer; - end Pack1; - - package Pack2 is - function F2 return Integer; - function Pure (x : integer) return integer; - -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) - -- pragma Suppress (Elaboration_Check); -- (4) - end Pack2; - - with Pack2; - package body Pack1 is - function F1 return Integer is - begin - return 100; - end F1; - Val : integer := Pack2.Pure (11); -- Elab. call (1) - begin - declare - -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) - -- pragma Suppress(Elaboration_Check); -- (2) - begin - X1 := Pack2.F2 + 1; -- Elab. call (2) - end; - end Pack1; - - with Pack1; - package body Pack2 is - function F2 return Integer is - begin - return Pack1.F1; - end F2; - function Pure (x : integer) return integer is - begin - return x ** 3 - 3 * x; - end; - end Pack2; - - with Pack1, Ada.Text_IO; - procedure Proc3 is - begin - Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 - end Proc3; - @end smallexample - In the absence of any pragmas, an attempt to bind this program produces - the following diagnostics: - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - error: elaboration circularity detected - info: "pack1 (body)" must be elaborated before "pack1 (body)" - info: reason: Elaborate_All probably needed in unit "pack1 (body)" - info: recompile "pack1 (body)" with /WARNINGS=ELABORATION for full details - info: "pack1 (body)" - info: must be elaborated along with its spec: - info: "pack1 (spec)" - info: which is withed by: - info: "pack2 (body)" - info: which must be elaborated along with its spec: - info: "pack2 (spec)" - info: which is withed by: - info: "pack1 (body)" - @end group - @end smallexample - The sources of the circularity are the two calls to @code{Pack2.Pure} and - @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to - F2 is safe, even though F2 calls F1, because the call appears after the - elaboration of the body of F1. Therefore the pragma (1) is safe, and will - remove the warning on the call. It is also possible to use pragma (2) - because there are no other potentially unsafe calls in the block. - - @noindent - The call to @code{Pure} is safe because this function does not depend on the - state of @code{Pack2}. Therefore any call to this function is safe, and it - is correct to place pragma (3) in the corresponding package spec. - - @noindent - Finally, we could place pragma (4) in the spec of @code{Pack2} to disable - warnings on all calls to functions declared therein. Note that this is not - necessarily safe, and requires more detailed examination of the subprogram - bodies involved. In particular, a call to @code{F2} requires that @code{F1} - be already elaborated. - @end table - - @noindent - It is hard to generalize on which of these four approaches should be - taken. Obviously if it is possible to fix the program so that the default - treatment works, this is preferable, but this may not always be practical. - It is certainly simple enough to use - @option{/CHECKS=ELABORATION} - but the danger in this case is that, even if the GNAT binder - finds a correct elaboration order, it may not always do so, - and certainly a binder from another Ada compiler might not. A - combination of testing and analysis (for which the warnings generated - with the - @option{/WARNINGS=ELABORATION} - qualifier can be useful) must be used to ensure that the program is free - of errors. One qualifier that is useful in this testing is the - @code{/PESSIMISTIC_ELABORATION_ORDER} - qualifier for - @code{GNAT BIND}. - Normally the binder tries to find an order that has the best chance of - of avoiding elaboration problems. With this qualifier, the binder - plays a devil's advocate role, and tries to choose the order that - has the best chance of failing. If your program works even with this - qualifier, then it has a better chance of being error free, but this is still - not a guarantee. - - For an example of this approach in action, consider the C-tests (executable - tests) from the ACVC suite. If these are compiled and run with the default - treatment, then all but one of them succeed without generating any error - diagnostics from the binder. However, there is one test that fails, and - this is not surprising, because the whole point of this test is to ensure - that the compiler can handle cases where it is impossible to determine - a correct order statically, and it checks that an exception is indeed - raised at run time. - - This one test must be compiled and run using the - @option{/CHECKS=ELABORATION} - qualifier, and then it passes. Alternatively, the entire suite can - be run using this qualifier. It is never wrong to run with the dynamic - elaboration qualifier if your code is correct, and we assume that the - C-tests are indeed correct (it is less efficient, but efficiency is - not a factor in running the ACVC tests.) - - @node Elaboration for Access-to-Subprogram Values - @section Elaboration for Access-to-Subprogram Values - @cindex Access-to-subprogram - - @noindent - The introduction of access-to-subprogram types in Ada 95 complicates - the handling of elaboration. The trouble is that it becomes - impossible to tell at compile time which procedure - is being called. This means that it is not possible for the binder - to analyze the elaboration requirements in this case. - - If at the point at which the access value is created - (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}), - the body of the subprogram is - known to have been elaborated, then the access value is safe, and its use - does not require a check. This may be achieved by appropriate arrangement - of the order of declarations if the subprogram is in the current unit, - or, if the subprogram is in another unit, by using pragma - @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body} - on the referenced unit. - - If the referenced body is not known to have been elaborated at the point - the access value is created, then any use of the access value must do a - dynamic check, and this dynamic check will fail and raise a - @code{Program_Error} exception if the body has not been elaborated yet. - GNAT will generate the necessary checks, and in addition, if the - @option{/WARNINGS=ELABORATION} - qualifier is set, will generate warnings that such checks are required. - - The use of dynamic dispatching for tagged types similarly generates - a requirement for dynamic checks, and premature calls to any primitive - operation of a tagged type before the body of the operation has been elaborated, - will result in the raising of @code{Program_Error}. - - @node Summary of Procedures for Elaboration Control - @section Summary of Procedures for Elaboration Control - @cindex Elaboration control - - @noindent - First, compile your program with the default options, using none of - the special elaboration control qualifiers. If the binder successfully - binds your program, then you can be confident that, apart from issues - raised by the use of access-to-subprogram types and dynamic dispatching, - the program is free of elaboration errors. If it is important that the - program be portable, then use the - @option{/WARNINGS=ELABORATION} - qualifier to generate warnings about missing @code{Elaborate_All} - pragmas, and supply the missing pragmas. - - If the program fails to bind using the default static elaboration - handling, then you can fix the program to eliminate the binder - message, or recompile the entire program with the - @option{/CHECKS=ELABORATION} qualifier to generate dynamic elaboration checks, - and, if you are sure there really are no elaboration problems, - use a global pragma @code{Suppress (Elaboration_Checks)}. - - @node Other Elaboration Order Considerations - @section Other Elaboration Order Considerations - @noindent - This section has been entirely concerned with the issue of finding a valid - elaboration order, as defined by the Ada Reference Manual. In a case - where several elaboration orders are valid, the task is to find one - of the possible valid elaboration orders (and the static model in GNAT - will ensure that this is achieved). - - The purpose of the elaboration rules in the Ada Reference Manual is to - make sure that no entity is accessed before it has been elaborated. For - a subprogram, this means that the spec and body must have been elaborated - before the subprogram is called. For an object, this means that the object - must have been elaborated before its value is read or written. A violation - of either of these two requirements is an access before elaboration order, - and this section has been all about avoiding such errors. - - In the case where more than one order of elaboration is possible, in the - sense that access before elaboration errors are avoided, then any one of - the orders is "correct" in the sense that it meets the requirements of - the Ada Reference Manual, and no such error occurs. - - However, it may be the case for a given program, that there are - constraints on the order of elaboration that come not from consideration - of avoiding elaboration errors, but rather from extra-lingual logic - requirements. Consider this example: - - @smallexample - with Init_Constants; - package Constants is - X : Integer := 0; - Y : Integer := 0; - end Constants; - - package Init_Constants is - procedure Calc; - end Init_Constants; - - with Constants; - package body Init_Constants is - procedure Calc is begin null; end; - begin - Constants.X := 3; - Constants.Y := 4; - end Init_Constants; - - with Constants; - package Calc is - Z : Integer := Constants.X + Constants.Y; - end Calc; - - with Calc; - with Text_IO; use Text_IO; - procedure Main is - begin - Put_Line (Calc.Z'Img); - end Main; - @end smallexample - - @noindent - In this example, there is more than one valid order of elaboration. For - example both the following are correct orders: - - @smallexample - Init_Constants spec - Constants spec - Calc spec - Main body - Init_Constants body - - and - - Init_Constants spec - Init_Constants body - Constants spec - Calc spec - Main body - @end smallexample - - @noindent - There is no language rule to prefer one or the other, both are correct - from an order of elaboration point of view. But the programmatic effects - of the two orders are very different. In the first, the elaboration routine - of @code{Calc} initializes @code{Z} to zero, and then the main program - runs with this value of zero. But in the second order, the elaboration - routine of @code{Calc} runs after the body of Init_Constants has set - @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} - runs. - - One could perhaps by applying pretty clever non-artificial intelligence - to the situation guess that it is more likely that the second order of - elaboration is the one desired, but there is no formal linguistic reason - to prefer one over the other. In fact in this particular case, GNAT will - prefer the second order, because of the rule that bodies are elaborated - as soon as possible, but it's just luck that this is what was wanted - (if indeed the second order was preferred). - - If the program cares about the order of elaboration routines in a case like - this, it is important to specify the order required. In this particular - case, that could have been achieved by adding to the spec of Calc: - - @smallexample - pragma Elaborate_All (Constants); - @end smallexample - - @noindent - which requires that the body (if any) and spec of @code{Constants}, - as well as the body and spec of any unit @code{with}'ed by - @code{Constants} be elaborated before @code{Calc} is elaborated. - - Clearly no automatic method can always guess which alternative you require, - and if you are working with legacy code that had constraints of this kind - which were not properly specified by adding @code{Elaborate} or - @code{Elaborate_All} pragmas, then indeed it is possible that two different - compilers can choose different orders. - - The @code{GNAT BIND} - @code{/PESSIMISTIC_ELABORATION} qualifier may be useful in smoking - out problems. This qualifier causes bodies to be elaborated as late as possible - instead of as early as possible. In the example above, it would have forced - the choice of the first elaboration order. If you get different results - when using this qualifier, and particularly if one set of results is right, - and one is wrong as far as you are concerned, it shows that you have some - missing @code{Elaborate} pragmas. For the example above, we have the - following output: - - @smallexample - GNAT MAKE -f -q main - main - 7 - GNAT MAKE -f -q main /BINDER_QUALIFIERS -p - main - 0 - @end smallexample - - @noindent - It is of course quite unlikely that both these results are correct, so - it is up to you in a case like this to investigate the source of the - difference, by looking at the two elaboration orders that are chosen, - and figuring out which is correct, and then adding the necessary - @code{Elaborate_All} pragmas to ensure the desired order. - - @node The Cross-Referencing Tools GNAT XREF and GNAT FIND - @chapter The Cross-Referencing Tools @code{GNAT XREF} and @code{GNAT FIND} - @findex GNAT XREF - @findex GNAT FIND - - @noindent - The compiler generates cross-referencing information (unless - you set the @samp{/XREF=SUPPRESS} qualifier), which are saved in the @file{.ALI} files. - This information indicates where in the source each entity is declared and - referenced. Note that entities in package Standard are not included, but - entities in all other predefined units are included in the output. - - Before using any of these two tools, you need to compile successfully your - application, so that GNAT gets a chance to generate the cross-referencing - information. - - The two tools @code{GNAT XREF} and @code{GNAT FIND} take advantage of this - information to provide the user with the capability to easily locate the - declaration and references to an entity. These tools are quite similar, - the difference being that @code{GNAT FIND} is intended for locating - definitions and/or references to a specified entity or entities, whereas - @code{GNAT XREF} is oriented to generating a full report of all - cross-references. - - To use these tools, you must not compile your application using the - @option{/XREF=SUPPRESS} qualifier on the @file{GNAT MAKE} command line (@inforef{The - GNAT Make Program GNAT MAKE,,gnat_ug}). Otherwise, cross-referencing - information will not be generated. - - @menu - * GNAT XREF Qualifiers:: - * GNAT FIND Qualifiers:: - * Project Files for GNAT XREF and GNAT FIND:: - * Regular Expressions in GNAT FIND and GNAT XREF:: - * Examples of GNAT XREF Usage:: - * Examples of GNAT FIND Usage:: - @end menu - - @node GNAT XREF Qualifiers - @section @code{GNAT XREF} Qualifiers - - @noindent - The command lines for @code{GNAT XREF} is: - @smallexample - $ GNAT XREF [qualifiers] sourcefile1 [sourcefile2 ...] - @end smallexample - - @noindent - where - - @table @code - @item sourcefile1, sourcefile2 - identifies the source files for which a report is to be generated. The - 'with'ed units will be processed too. You must provide at least one file. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.ADB' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - @end table - - @noindent - The qualifiers can be : - @table @code - @item /ALL_FILES - If this qualifier is present, @code{GNAT FIND} and @code{GNAT XREF} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{GNAT FIND} and @code{GNAT XREF} - much faster, and their output much smaller. - - @item /SOURCE_SEARCH=direc - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{GNAT MAKE}. - - @item /OBJECT_SEARCH=direc - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{GNAT MAKE}. - - @item /NOSTD_INCLUDES - Do not look for sources in the system default directory. - - @item /NOSTD_LIBRARIES - Do not look for library files in the system default directory. - - @item /RUNTIME_SYSTEM=@var{rts-path} - @cindex @code{/RUNTIME_SYSTEM} (@code{GNAT XREF}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{GNAT MAKE} flag (see @ref{Qualifiers for GNAT MAKE}). - - @item -d - If this qualifier is set @code{GNAT XREF} will output the parent type - reference for each matching derived types. - - @item /FULL_PATHNAME - If this qualifier is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this qualifier is - not set, the directory will not be printed. - - @item /IGNORE_LOCALS - If this qualifier is set, information is output only for library-level - entities, ignoring local entities. The use of this qualifier may accelerate - @code{GNAT FIND} and @code{GNAT XREF}. - - @item /SEARCH=direc - Equivalent to @samp{/OBJECT_SEARCH=direc /SOURCE_SEARCH=direc}. - - @item /PROJECT=file - Specify a project file to use @xref{Project Files}. - By default, @code{GNAT XREF} and @code{GNAT FIND} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{/SOURCE_SEARCH} - and @samp{OBJECT_SEARCH}. - @item /UNUSED - Output only unused symbols. This may be really useful if you give your - main compilation unit on the command line, as @code{GNAT XREF} will then - display every unused entity and 'with'ed package. - - - @end table - - All these qualifiers may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{GNAT XREF /ALL_FILES/IGNORE_LOCALS} instead of - @samp{GNAT XREF /ALL_FILES /IGNORE_LOCALS}. - - @node GNAT FIND Qualifiers - @section @code{GNAT FIND} Qualifiers - - @noindent - The command line for @code{GNAT FIND} is: - - @smallexample - $ GNAT FIND [qualifiers] pattern[:sourcefile[:line[:column]]] - [file1 file2 ...] - @end smallexample - - @noindent - where - - @table @code - @item pattern - An entity will be output only if it matches the regular expression found - in @samp{pattern}, see @xref{Regular Expressions in GNAT FIND and GNAT XREF}. - - Omitting the pattern is equivalent to specifying @samp{*}, which - will match any entity. Note that if you do not provide a pattern, you - have to provide both a sourcefile and a line. - - Entity names are given in Latin-1, with uppercase/lowercase equivalence - for matching purposes. At the current time there is no support for - 8-bit codes other than Latin-1, or for wide characters in identifiers. - - @item sourcefile - @code{GNAT FIND} will look for references, bodies or declarations - of symbols referenced in @file{sourcefile}, at line @samp{line} - and column @samp{column}. See @pxref{Examples of GNAT FIND Usage} - for syntax examples. - - @item line - is a decimal integer identifying the line number containing - the reference to the entity (or entities) to be located. - - @item column - is a decimal integer identifying the exact location on the - line of the first character of the identifier for the - entity reference. Columns are numbered from 1. - - @item file1 file2 ... - The search will be restricted to these files. If none are given, then - the search will be done for every library file in the search path. - These file must appear only after the pattern or sourcefile. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.ADB' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - Not that if you specify at least one file in this part, @code{GNAT FIND} may - sometimes not be able to find the body of the subprograms... - - @end table - - At least one of 'sourcefile' or 'pattern' has to be present on - the command line. - - The following qualifiers are available: - @table @code - - @item /ALL_FILES - If this qualifier is present, @code{GNAT FIND} and @code{GNAT XREF} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{GNAT FIND} and @code{GNAT XREF} - much faster, and their output much smaller. - - @item /SOURCE_SEARCH=direc - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{GNAT MAKE}. - - @item /OBJECT_SEARCH=direc - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{GNAT MAKE}. - - @item /NOSTD_INCLUDES - Do not look for sources in the system default directory. - - @item /NOSTD_LIBRARIES - Do not look for library files in the system default directory. - - @item /RUNTIME_SYSTEM=@var{rts-path} - @cindex @code{/RUNTIME_SYSTEM} (@code{GNAT FIND}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{GNAT MAKE} flag (see @ref{Qualifiers for GNAT MAKE}). - - @item -d - If this qualifier is set, then @code{GNAT FIND} will output the parent type - reference for each matching derived types. - - @item /EXPRESSIONS - By default, @code{GNAT FIND} accept the simple regular expression set for - @samp{pattern}. If this qualifier is set, then the pattern will be - considered as full Unix-style regular expression. - - @item /FULL_PATHNAME - If this qualifier is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this qualifier is - not set, the directory will not be printed. - - @item /IGNORE_LOCALS - If this qualifier is set, information is output only for library-level - entities, ignoring local entities. The use of this qualifier may accelerate - @code{GNAT FIND} and @code{GNAT XREF}. - - @item /SEARCH=direc - Equivalent to @samp{/OBJECT_SEARCH=direc /SOURCE_SEARCH=direc}. - - @item /PROJECT=file - Specify a project file (@pxref{Project Files}) to use. - By default, @code{GNAT XREF} and @code{GNAT FIND} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{/SOURCE_SEARCH} and - @samp{/OBJECT_SEARCH}. - - @item /REFERENCES - By default, @code{GNAT FIND} will output only the information about the - declaration, body or type completion of the entities. If this qualifier is - set, the @code{GNAT FIND} will locate every reference to the entities in - the files specified on the command line (or in every file in the search - path if no file is given on the command line). - - @item /PRINT_LINES - If this qualifier is set, then @code{GNAT FIND} will output the content - of the Ada source file lines were the entity was found. - - @item -t - If this qualifier is set, then @code{GNAT FIND} will output the type hierarchy for - the specified type. It act like -d option but recursively from parent - type to parent type. When this qualifier is set it is not possible to - specify more than one file. - - @end table - - All these qualifiers may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{GNAT XREF /ALL_FILES/IGNORE_LOCALS} instead of - @samp{GNAT XREF /ALL_FILES /IGNORE_LOCALS}. - - As stated previously, GNAT FIND will search in every directory in the - search path. You can force it to look only in the current directory if - you specify @code{*} at the end of the command line. - - - @node Project Files for GNAT XREF and GNAT FIND - @section Project Files for @command{GNAT XREF} and @command{GNAT FIND} - - @noindent - Project files allow a programmer to specify how to compile its - application, where to find sources,... These files are used primarily by - the Glide Ada mode, but they can also be used by the two tools - @code{GNAT XREF} and @code{GNAT FIND}. - - A project file name must end with @file{.adp}. If a single one is - present in the current directory, then @code{GNAT XREF} and @code{GNAT FIND} will - extract the information from it. If multiple project files are found, none of - them is read, and you have to use the @samp{-p} qualifier to specify the one - you want to use. - - The following lines can be included, even though most of them have default - values which can be used in most cases. - The lines can be entered in any order in the file. - Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of - each line. If you have multiple instances, only the last one is taken into - account. - - @table @code - @item src_dir=DIR [default: "[]"] - specifies a directory where to look for source files. Multiple src_dir lines - can be specified and they will be searched in the order they - are specified. - - @item obj_dir=DIR [default: "[]"] - specifies a directory where to look for object and library files. Multiple - obj_dir lines can be specified and they will be searched in the order they - are specified - - @item comp_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{comp_opt@}} notation. This is intended to store the default - qualifiers given to @file{GNAT MAKE} and @file{GNAT COMPILE}. - - @item bind_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{bind_opt@}} notation. This is intended to store the default - qualifiers given to @file{GNAT BIND}. - - @item link_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{link_opt@}} notation. This is intended to store the default - qualifiers given to @file{GNAT LINK}. - - @item main=EXECUTABLE [default: ""] - specifies the name of the executable for the application. This variable can - be referred to in the following lines by using the @samp{$@{main@}} notation. - - @item comp_cmd=COMMAND [default: "GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"] - specifies the command used to compile a single file in the application. - - @item make_cmd=COMMAND [default: "GNAT MAKE $@{main@} /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@} /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@} /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"] - specifies the command used to recompile the whole application. - - @item run_cmd=COMMAND [default: "$@{main@}"] - specifies the command used to run the application. - - @item debug_cmd=COMMAND [default: "GDB $@{main@}"] - specifies the command used to debug the application - - @end table - - @code{GNAT XREF} and @code{GNAT FIND} only take into account the @samp{src_dir} - and @samp{obj_dir} lines, and ignore the others. - - @node Regular Expressions in GNAT FIND and GNAT XREF - @section Regular Expressions in @code{GNAT FIND} and @code{GNAT XREF} - - @noindent - As specified in the section about @code{GNAT FIND}, the pattern can be a - regular expression. Actually, there are to set of regular expressions - which are recognized by the program : - - @table @code - @item globbing patterns - These are the most usual regular expression. They are the same that you - generally used in a Unix shell command line, or in a DOS session. - - Here is a more formal grammar : - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - regexp ::= term - term ::= elmt -- matches elmt - term ::= elmt elmt -- concatenation (elmt then elmt) - term ::= * -- any string of 0 or more characters - term ::= ? -- matches any character - term ::= [char @{char@}] -- matches any character listed - term ::= [char - char] -- matches any character in range - @end group - @end smallexample - - @item full regular expression - The second set of regular expressions is much more powerful. This is the - type of regular expressions recognized by utilities such a @file{grep}. - - The following is the form of a regular expression, expressed in Ada - reference manual style BNF is as follows - - @smallexample - @iftex - @leftskip=.5cm - @end iftex - @group - regexp ::= term @{| term@} -- alternation (term or term ...) - - term ::= item @{item@} -- concatenation (item then item) - - item ::= elmt -- match elmt - item ::= elmt * -- zero or more elmt's - item ::= elmt + -- one or more elmt's - item ::= elmt ? -- matches elmt or nothing - @end group - @group - elmt ::= nschar -- matches given character - elmt ::= [nschar @{nschar@}] -- matches any character listed - elmt ::= [^ nschar @{nschar@}] -- matches any character not listed - elmt ::= [char - char] -- matches chars in given range - elmt ::= \ char -- matches given character - elmt ::= . -- matches any single character - elmt ::= ( regexp ) -- parens used for grouping - - char ::= any character, including special characters - nschar ::= any character except ()[].*+?^ - @end group - @end smallexample - - Following are a few examples : - - @table @samp - @item abcde|fghi - will match any of the two strings 'abcde' and 'fghi'. - - @item abc*d - will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on - - @item [a-z]+ - will match any string which has only lowercase characters in it (and at - least one character - - @end table - @end table - - @node Examples of GNAT XREF Usage - @section Examples of @code{GNAT XREF} Usage - - @subsection General Usage - - @noindent - For the following examples, we will consider the following units : - - @smallexample - @group - @cartouche - MAIN.ADS: - 1: @b{with} Bar; - 2: @b{package} Main @b{is} - 3: @b{procedure} Foo (B : @b{in} Integer); - 4: C : Integer; - 5: @b{private} - 6: D : Integer; - 7: @b{end} Main; - - MAIN.ADB: - 1: @b{package body} Main @b{is} - 2: @b{procedure} Foo (B : @b{in} Integer) @b{is} - 3: @b{begin} - 4: C := B; - 5: D := B; - 6: Bar.Print (B); - 7: Bar.Print (C); - 8: @b{end} Foo; - 9: @b{end} Main; - - BAR.ADS: - 1: @b{package} Bar @b{is} - 2: @b{procedure} Print (B : Integer); - 3: @b{end} bar; - @end cartouche - @end group - @end smallexample - - @table @code - - @noindent - The first thing to do is to recompile your application (for instance, in - that case just by doing a @samp{GNAT MAKE main}, so that GNAT generates - the cross-referencing information. - You can then issue any of the following commands: - - @item GNAT XREF MAIN.ADB - @code{GNAT XREF} generates cross-reference information for MAIN.ADB - and every unit 'with'ed by MAIN.ADB. - - The output would be: - @smallexample - @iftex - @leftskip=0cm - @end iftex - B Type: Integer - Decl: BAR.ADS 2:22 - B Type: Integer - Decl: MAIN.ADS 3:20 - Body: MAIN.ADB 2:20 - Ref: MAIN.ADB 4:13 5:13 6:19 - Bar Type: Unit - Decl: BAR.ADS 1:9 - Ref: MAIN.ADB 6:8 7:8 - MAIN.ADS 1:6 - C Type: Integer - Decl: MAIN.ADS 4:5 - Modi: MAIN.ADB 4:8 - Ref: MAIN.ADB 7:19 - D Type: Integer - Decl: MAIN.ADS 6:5 - Modi: MAIN.ADB 5:8 - Foo Type: Unit - Decl: MAIN.ADS 3:15 - Body: MAIN.ADB 2:15 - Main Type: Unit - Decl: MAIN.ADS 2:9 - Body: MAIN.ADB 1:14 - Print Type: Unit - Decl: BAR.ADS 2:15 - Ref: MAIN.ADB 6:12 7:12 - @end smallexample - - @noindent - that is the entity @code{Main} is declared in MAIN.ADS, line 2, column 9, - its body is in MAIN.ADB, line 1, column 14 and is not referenced any where. - - The entity @code{Print} is declared in BAR.ADS, line 2, column 15 and it - it referenced in MAIN.ADB, line 6 column 12 and line 7 column 12. - - @item GNAT XREF PACKAGE1.ADB PACKAGE2.ADS - @code{GNAT XREF} will generates cross-reference information for - PACKAGE1.ADB, PACKAGE2.ADS and any other package 'with'ed by any - of these. - - @end table - - - @node Examples of GNAT FIND Usage - @section Examples of @code{GNAT FIND} Usage - - @table @code - - @item GNAT FIND /FULL_PATHNAME xyz:MAIN.ADB - Find declarations for all entities xyz referenced at least once in - MAIN.ADB. The references are search in every library file in the search - path. - - The directories will be printed as well (as the @samp{/FULL_PATHNAME} - qualifier is set) - - The output will look like: - @smallexample - [directory]MAIN.ADS:106:14: xyz <= declaration - [directory]MAIN.ADB:24:10: xyz <= body - [directory]FOO.ADS:45:23: xyz <= declaration - @end smallexample - - @noindent - that is to say, one of the entities xyz found in MAIN.ADB is declared at - line 12 of MAIN.ADS (and its body is in MAIN.ADB), and another one is - declared at line 45 of FOO.ADS - - @item GNAT FIND /FULL_PATHNAME/SOURCE_LINE xyz:MAIN.ADB - This is the same command as the previous one, instead @code{GNAT FIND} will - display the content of the Ada source file lines. - - The output will look like: - - @smallexample - [directory]MAIN.ADS:106:14: xyz <= declaration - procedure xyz; - [directory]MAIN.ADB:24:10: xyz <= body - procedure xyz is - [directory]FOO.ADS:45:23: xyz <= declaration - xyz : Integer; - @end smallexample - - @noindent - This can make it easier to find exactly the location your are looking - for. - - @item GNAT FIND /REFERENCES "*x*":MAIN.ADS:123 FOO.ADB - Find references to all entities containing an x that are - referenced on line 123 of MAIN.ADS. - The references will be searched only in MAIN.ADB and FOO.ADB. - - @item GNAT FIND MAIN.ADS:123 - Find declarations and bodies for all entities that are referenced on - line 123 of MAIN.ADS. - - This is the same as @code{GNAT FIND "*":MAIN.ADB:123}. - - @item GNAT FIND [mydir]MAIN.ADB:123:45 - Find the declaration for the entity referenced at column 45 in - line 123 of file MAIN.ADB in directory mydir. Note that it - is usual to omit the identifier name when the column is given, - since the column position identifies a unique reference. - - The column has to be the beginning of the identifier, and should not - point to any character in the middle of the identifier. - - @end table - - @node File Name Krunching Using GNAT KRUNCH - @chapter File Name Krunching Using @code{GNAT KRUNCH} - @findex GNAT KRUNCH - - @noindent - This chapter discusses the method used by the compiler to shorten - the default file names chosen for Ada units so that they do not - exceed the maximum length permitted. It also describes the - @code{GNAT KRUNCH} utility that can be used to determine the result of - applying this shortening. - @menu - * About GNAT KRUNCH:: - * Using GNAT KRUNCH:: - * Krunching Method:: - * Examples of GNAT KRUNCH Usage:: - @end menu - - @node About GNAT KRUNCH - @section About @code{GNAT KRUNCH} - - @noindent - The default file naming rule in GNAT - is that the file name must be derived from - the unit name. The exact default rule is as follows: - @itemize @bullet - @item - Take the unit name and replace all dots by hyphens. - @item - If such a replacement occurs in the - second character position of a name, and the first character is - A, G, S, or I then replace the dot by the character - $ (dollar sign) - instead of a minus. - @end itemize - The reason for this exception is to avoid clashes - with the standard names for children of System, Ada, Interfaces, - and GNAT, which use the prefixes S- A- I- and G- - respectively. - - The @code{/FILE_NAME_MAX_LENGTH=@var{nn}} - qualifier of the compiler activates a "krunching" - circuit that limits file names to nn characters (where nn is a decimal - integer). For example, using OpenVMS, - where the maximum file name length is - 39, the value of nn is usually set to 39, but if you want to generate - a set of files that would be usable if ported to a system with some - different maximum file length, then a different value can be specified. - The default value of 39 for OpenVMS need not be specified. - - The @code{GNAT KRUNCH} utility can be used to determine the krunched name for - a given file, when krunched to a specified maximum length. - - @node Using GNAT KRUNCH - @section Using @code{GNAT KRUNCH} - - @noindent - The @code{GNAT KRUNCH} command has the form - - - @smallexample - $ GNAT KRUNCH @var{name} /COUNT=nn - @end smallexample - - @noindent - @var{name} can be an Ada name with dots or the GNAT name of the unit, - where the dots representing child units or subunit are replaced by - hyphens. The only confusion arises if a name ends in @code{.ADS} or - @code{.ADB}. @code{GNAT KRUNCH} takes this to be an extension if there are - no other dots in the name. - - @var{length} represents the length of the krunched name. The default - when no argument is given is 39 characters. A length of zero stands for - unlimited, in other words do not chop except for system files which are - always 39. - - @noindent - The output is the krunched name. The output has an extension only if the - original argument was a file name with an extension. - - @node Krunching Method - @section Krunching Method - - @noindent - The initial file name is determined by the name of the unit that the file - contains. The name is formed by taking the full expanded name of the - unit and replacing the separating dots with hyphens and - using uppercase - for all letters, except that a hyphen in the second character position is - replaced by a dollar sign if the first character is - A, I, G, or S. - The extension is @code{.ADS} for a - specification and @code{.ADB} for a body. - Krunching does not affect the extension, but the file name is shortened to - the specified length by following these rules: - - @itemize @bullet - @item - The name is divided into segments separated by hyphens, tildes or - underscores and all hyphens, tildes, and underscores are - eliminated. If this leaves the name short enough, we are done. - - @item - If the name is too long, the longest segment is located (left-most if there are two - of equal length), and shortened by dropping its last character. This is - repeated until the name is short enough. - - As an example, consider the krunching of @*@file{OUR-STRINGS-WIDE_FIXED.ADB} - to fit the name into 8 characters as required by some operating systems. - - @smallexample - our-strings-wide_fixed 22 - our strings wide fixed 19 - our string wide fixed 18 - our strin wide fixed 17 - our stri wide fixed 16 - our stri wide fixe 15 - our str wide fixe 14 - our str wid fixe 13 - our str wid fix 12 - ou str wid fix 11 - ou st wid fix 10 - ou st wi fix 9 - ou st wi fi 8 - Final file name: OUSTWIFI.ADB - @end smallexample - - @item - The file names for all predefined units are always krunched to eight - characters. The krunching of these predefined units uses the following - special prefix replacements: - - @table @file - @item ada- - replaced by @file{A-} - - @item gnat- - replaced by @file{G-} - - @item interfaces- - replaced by @file{I-} - - @item system- - replaced by @file{S-} - @end table - - These system files have a hyphen in the second character position. That - is why normal user files replace such a character with a - dollar sign, to - avoid confusion with system file names. - - As an example of this special rule, consider - @*@file{ADA-STRINGS-WIDE_FIXED.ADB}, which gets krunched as follows: - - @smallexample - ada-strings-wide_fixed 22 - a- strings wide fixed 18 - a- string wide fixed 17 - a- strin wide fixed 16 - a- stri wide fixed 15 - a- stri wide fixe 14 - a- str wide fixe 13 - a- str wid fixe 12 - a- str wid fix 11 - a- st wid fix 10 - a- st wi fix 9 - a- st wi fi 8 - Final file name: A-STWIFI.ADB - @end smallexample - @end itemize - - Of course no file shortening algorithm can guarantee uniqueness over all - possible unit names, and if file name krunching is used then it is your - responsibility to ensure that no name clashes occur. The utility - program @code{GNAT KRUNCH} is supplied for conveniently determining the - krunched name of a file. - - @node Examples of GNAT KRUNCH Usage - @section Examples of @code{GNAT KRUNCH} Usage - - @smallexample - @iftex - @leftskip=0cm - @end iftex - $ GNAT KRUNCH VERY_LONG_UNIT_NAME.ADS/count=6 --> VLUNNA.ADS - $ GNAT KRUNCH VERY_LONG_UNIT_NAME.ADS/count=0 --> VERY_LONG_UNIT_NAME.ADS - @end smallexample - - @node Preprocessing Using GNAT PREPROCESS - @chapter Preprocessing Using @code{GNAT PREPROCESS} - @findex GNAT PREPROCESS - - @noindent - The @code{GNAT PREPROCESS} utility provides - a simple preprocessing capability for Ada programs. - It is designed for use with GNAT, but is not dependent on any special - features of GNAT. - - @menu - * Using GNAT PREPROCESS:: - * Qualifiers for GNAT PREPROCESS:: - * Form of Definitions File:: - * Form of Input Text for GNAT PREPROCESS:: - @end menu - - @node Using GNAT PREPROCESS - @section Using @code{GNAT PREPROCESS} - - @noindent - To call @code{GNAT PREPROCESS} use - - @smallexample - $ GNAT PREPROCESS [-bcrsu] [-Dsymbol=value] infile outfile [deffile] - @end smallexample - - @noindent - where - @table @code - @item infile - is the full name of the input file, which is an Ada source - file containing preprocessor directives. - - @item outfile - is the full name of the output file, which is an Ada source - in standard Ada form. When used with GNAT, this file name will - normally have an ads or adb suffix. - - @item deffile - is the full name of a text file containing definitions of - symbols to be referenced by the preprocessor. This argument is - optional, and can be replaced by the use of the @code{-D} qualifier. - - @item qualifiers - is an optional sequence of qualifiers as described in the next section. - @end table - - @node Qualifiers for GNAT PREPROCESS - @section Qualifiers for @code{GNAT PREPROCESS} - - @table @code - - @item /BLANK_LINES - Causes both preprocessor lines and the lines deleted by - preprocessing to be replaced by blank lines in the output source file, - preserving line numbers in the output file. - - @item /COMMENTS - Causes both preprocessor lines and the lines deleted - by preprocessing to be retained in the output source as comments marked - with the special string "--! ". This option will result in line numbers - being preserved in the output file. - - @item -Dsymbol=value - Defines a new symbol, associated with value. If no value is given on the - command line, then symbol is considered to be @code{True}. This qualifier - can be used in place of a definition file. - - @item /REMOVE (default) - This is the default setting which causes lines deleted by preprocessing - to be entirely removed from the output file. - - @item /REFERENCE - Causes a @code{Source_Reference} pragma to be generated that - references the original input file, so that error messages will use - the file name of this original file. The use of this qualifier implies - that preprocessor lines are not to be removed from the file, so its - use will force @code{/BLANK_LINES} mode if - @code{/COMMENTS} - has not been specified explicitly. - - Note that if the file to be preprocessed contains multiple units, then - it will be necessary to @code{GNAT CHOP} the output file from - @code{GNAT PREPROCESS}. If a @code{Source_Reference} pragma is present - in the preprocessed file, it will be respected by - @code{GNAT CHOP /REFERENCE} - so that the final chopped files will correctly refer to the original - input source file for @code{GNAT PREPROCESS}. - - @item /SYMBOLS - Causes a sorted list of symbol names and values to be - listed on the standard output file. - - @item /UNDEFINED - Causes undefined symbols to be treated as having the value FALSE in the context - of a preprocessor test. In the absence of this option, an undefined symbol in - a @code{#if} or @code{#elsif} test will be treated as an error. - - @end table - - - @node Form of Definitions File - @section Form of Definitions File - - @noindent - The definitions file contains lines of the form - - @smallexample - symbol := value - @end smallexample - - @noindent - where symbol is an identifier, following normal Ada (case-insensitive) - rules for its syntax, and value is one of the following: - - @itemize @bullet - @item - Empty, corresponding to a null substitution - @item - A string literal using normal Ada syntax - @item - Any sequence of characters from the set - (letters, digits, period, underline). - @end itemize - - @noindent - Comment lines may also appear in the definitions file, starting with - the usual @code{--}, - and comments may be added to the definitions lines. - - @node Form of Input Text for GNAT PREPROCESS - @section Form of Input Text for @code{GNAT PREPROCESS} - - @noindent - The input text may contain preprocessor conditional inclusion lines, - as well as general symbol substitution sequences. - - The preprocessor conditional inclusion commands have the form - - @smallexample - @group - @cartouche - #if @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - ... - #else - lines - #end if; - @end cartouche - @end group - @end smallexample - - @noindent - In this example, @i{expression} is defined by the following grammar: - @smallexample - @i{expression} ::= - @i{expression} ::= = "" - @i{expression} ::= = - @i{expression} ::= 'Defined - @i{expression} ::= not @i{expression} - @i{expression} ::= @i{expression} and @i{expression} - @i{expression} ::= @i{expression} or @i{expression} - @i{expression} ::= @i{expression} and then @i{expression} - @i{expression} ::= @i{expression} or else @i{expression} - @i{expression} ::= ( @i{expression} ) - @end smallexample - - @noindent - For the first test (@i{expression} ::= ) the symbol must have - either the value true or false, that is to say the right-hand of the - symbol definition must be one of the (case-insensitive) literals - @code{True} or @code{False}. If the value is true, then the - corresponding lines are included, and if the value is false, they are - excluded. - - The test (@i{expression} ::= @code{'Defined}) is true only if - the symbol has been defined in the definition file or by a @code{-D} - qualifier on the command line. Otherwise, the test is false. - - The equality tests are case insensitive, as are all the preprocessor lines. - - If the symbol referenced is not defined in the symbol definitions file, - then the effect depends on whether or not qualifier @code{-u} - is specified. If so, then the symbol is treated as if it had the value - false and the test fails. If this qualifier is not specified, then - it is an error to reference an undefined symbol. It is also an error to - reference a symbol that is defined with a value other than @code{True} - or @code{False}. - - The use of the @code{not} operator inverts the sense of this logical test, so - that the lines are included only if the symbol is not defined. - The @code{then} keyword is optional as shown - - The @code{#} must be the first non-blank character on a line, but - otherwise the format is free form. Spaces or tabs may appear between - the @code{#} and the keyword. The keywords and the symbols are case - insensitive as in normal Ada code. Comments may be used on a - preprocessor line, but other than that, no other tokens may appear on a - preprocessor line. Any number of @code{elsif} clauses can be present, - including none at all. The @code{else} is optional, as in Ada. - - The @code{#} marking the start of a preprocessor line must be the first - non-blank character on the line, i.e. it must be preceded only by - spaces or horizontal tabs. - - Symbol substitution outside of preprocessor lines is obtained by using - the sequence - - @smallexample - $symbol - @end smallexample - - @noindent - anywhere within a source line, except in a comment or within a - string literal. The identifier - following the @code{$} must match one of the symbols defined in the symbol - definition file, and the result is to substitute the value of the - symbol in place of @code{$symbol} in the output file. - - Note that although the substitution of strings within a string literal - is not possible, it is possible to have a symbol whose defined value is - a string literal. So instead of setting XYZ to @code{hello} and writing: - - @smallexample - Header : String := "$XYZ"; - @end smallexample - - @noindent - you should set XYZ to @code{"hello"} and write: - - @smallexample - Header : String := $XYZ; - @end smallexample - - @noindent - and then the substitution will occur as desired. - - @node The GNAT Run-Time Library Builder GNAT LIBRARY - @chapter The GNAT Run-Time Library Builder @code{GNAT LIBRARY} - @findex GNAT LIBRARY - @cindex Library builder - - @noindent - @code{GNAT LIBRARY} is a tool for rebuilding the GNAT run time with user - supplied configuration pragmas. - - @menu - * Running GNAT LIBRARY:: - * Qualifiers for GNAT LIBRARY:: - * Examples of GNAT LIBRARY Usage:: - @end menu - - @node Running GNAT LIBRARY - @section Running @code{GNAT LIBRARY} - - @noindent - The @code{GNAT LIBRARY} command has the form - - @smallexample - $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file] - @end smallexample - - @node Qualifiers for GNAT LIBRARY - @section Qualifiers for @code{GNAT LIBRARY} - - @noindent - @code{GNAT LIBRARY} recognizes the following qualifiers: - - @table @code - @item /CREATE=directory - @cindex @code{/CREATE=directory} (@code{GNAT LIBRARY}) - Create the new run-time library in the specified directory. - - @item /SET=directory - @cindex @code{/SET=directory} (@code{GNAT LIBRARY}) - Make the library in the specified directory the current run-time - library. - - @item /DELETE=directory - @cindex @code{/DELETE=directory} (@code{GNAT LIBRARY}) - Delete the run-time library in the specified directory. - - @item /CONFIG=file - @cindex @code{/CONFIG=file} (@code{GNAT LIBRARY}) - With /CREATE: - Use the configuration pragmas in the specified file when building - the library. - - With /SET: - Use the configuration pragmas in the specified file when compiling. - - @end table - - @node Examples of GNAT LIBRARY Usage - @section Example of @code{GNAT LIBRARY} Usage - - @smallexample - Contents of VAXFLOAT.ADC: - pragma Float_Representation (VAX_Float); - - $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC - - GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT] - - @end smallexample - - @node The GNAT Library Browser GNAT LIST - @chapter The GNAT Library Browser @code{GNAT LIST} - @findex GNAT LIST - @cindex Library browser - - @noindent - @code{GNAT LIST} is a tool that outputs information about compiled - units. It gives the relationship between objects, unit names and source - files. It can also be used to check the source dependencies of a unit - as well as various characteristics. - - @menu - * Running GNAT LIST:: - * Qualifiers for GNAT LIST:: - * Examples of GNAT LIST Usage:: - @end menu - - @node Running GNAT LIST - @section Running @code{GNAT LIST} - - @noindent - The @code{GNAT LIST} command has the form - - @smallexample - $ GNAT LIST qualifiers @var{object_or_ali_file} - @end smallexample - - @noindent - The main argument is the list of object or @file{ali} files - (@pxref{The Ada Library Information Files}) - for which information is requested. - - In normal mode, without additional option, @code{GNAT LIST} produces a - four-column listing. Each line represents information for a specific - object. The first column gives the full path of the object, the second - column gives the name of the principal unit in this object, the third - column gives the status of the source and the fourth column gives the - full path of the source representing this unit. - Here is a simple example of use: - - @smallexample - $ GNAT LIST *.OBJ - []DEMO1.OBJ demo1 DIF DEMO1.ADB - []DEMO2.OBJ demo2 OK DEMO2.ADB - []HELLO.OBJ h1 OK HELLO.ADB - []INSTR-CHILD.OBJ instr.child MOK INSTR-CHILD.ADB - []INSTR.OBJ instr OK INSTR.ADB - []TEF.OBJ tef DIF TEF.ADB - []TEXT_IO_EXAMPLE.OBJ text_io_example OK TEXT_IO_EXAMPLE.ADB - []TGEF.OBJ tgef DIF TGEF.ADB - @end smallexample - - @noindent - The first line can be interpreted as follows: the main unit which is - contained in - object file @file{DEMO1.OBJ} is demo1, whose main source is in - @file{DEMO1.ADB}. Furthermore, the version of the source used for the - compilation of demo1 has been modified (DIF). Each source file has a status - qualifier which can be: - - @table @code - @item OK (unchanged) - The version of the source file used for the compilation of the - specified unit corresponds exactly to the actual source file. - - @item MOK (slightly modified) - The version of the source file used for the compilation of the - specified unit differs from the actual source file but not enough to - require recompilation. If you use GNAT MAKE with the qualifier - @code{/MINIMAL_RECOMPILATION}, a file marked - MOK will not be recompiled. - - @item DIF (modified) - No version of the source found on the path corresponds to the source - used to build this object. - - @item ??? (file not found) - No source file was found for this unit. - - @item HID (hidden, unchanged version not first on PATH) - The version of the source that corresponds exactly to the source used - for compilation has been found on the path but it is hidden by another - version of the same source that has been modified. - - @end table - - @node Qualifiers for GNAT LIST - @section Qualifiers for @code{GNAT LIST} - - @noindent - @code{GNAT LIST} recognizes the following qualifiers: - - @table @code - @item /ALL_UNITS - @cindex @code{/ALL_UNITS} (@code{GNAT LIST}) - Consider all units, including those of the predefined Ada library. - Especially useful with @code{/DEPENDENCIES}. - - @item /DEPENDENCIES - @cindex @code{/DEPENDENCIES} (@code{GNAT LIST}) - List sources from which specified units depend on. - - @item /OUTPUT=OPTIONS - @cindex @code{/OUTPUT=OPTIONS} (@code{GNAT LIST}) - Output the list of options. - - @item /OUTPUT=OBJECTS - @cindex @code{/OUTPUT=OBJECTS} (@code{GNAT LIST}) - Only output information about object files. - - @item /OUTPUT=SOURCES - @cindex @code{/OUTPUT=SOURCES} (@code{GNAT LIST}) - Only output information about source files. - - @item /OUTPUT=UNITS - @cindex @code{/OUTPUT=UNITS} (@code{GNAT LIST}) - Only output information about compilation units. - - @item /OBJECT_SEARCH=@var{dir} - @itemx /SOURCE_SEARCH=@var{dir} - @itemx /SEARCH=@var{dir} - @itemx /NOCURRENT_DIRECTORY - @itemx /NOSTD_INCLUDES - Source path manipulation. Same meaning as the equivalent @code{GNAT MAKE} flags - (see @ref{Qualifiers for GNAT MAKE}). - - @item /RUNTIME_SYSTEM=@var{rts-path} - @cindex @code{/RUNTIME_SYSTEM} (@code{GNAT LIST}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{GNAT MAKE} flag (see @ref{Qualifiers for GNAT MAKE}). - - @item /OUTPUT=VERBOSE - @cindex @code{/OUTPUT=VERBOSE} (@code{GNAT LIST}) - Verbose mode. Output the complete source and object paths. Do not use - the default column layout but instead use long format giving as much as - information possible on each requested units, including special - characteristics such as: - - @table @code - @item Preelaborable - The unit is preelaborable in the Ada 95 sense. - - @item No_Elab_Code - No elaboration code has been produced by the compiler for this unit. - - @item Pure - The unit is pure in the Ada 95 sense. - - @item Elaborate_Body - The unit contains a pragma Elaborate_Body. - - @item Remote_Types - The unit contains a pragma Remote_Types. - - @item Shared_Passive - The unit contains a pragma Shared_Passive. - - @item Predefined - This unit is part of the predefined environment and cannot be modified - by the user. - - @item Remote_Call_Interface - The unit contains a pragma Remote_Call_Interface. - - @end table - - @end table - - @node Examples of GNAT LIST Usage - @section Example of @code{GNAT LIST} Usage - - @smallexample - GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB - - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ADA.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]A-FINALI.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]A-FILICO.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]A-STREAM.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]A-TAGS.ADS - DEMO1.ADB - GEN_LIST.ADS - GEN_LIST.ADB - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]GNAT.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]G-IO.ADS - INSTR.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]SYSTEM.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-EXCTAB.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-FINIMP.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-FINROO.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-SECSTA.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-STALIB.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-STOELE.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-STRATT.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-TASOLI.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]S-UNSTYP.ADS - GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]UNCHCONV.ADS - @end smallexample - - - @node Finding Memory Problems with GNAT Debug Pool - @chapter Finding Memory Problems with GNAT Debug Pool - @findex Debug Pool - @cindex storage, pool, memory corruption - - @noindent - The use of unchecked deallocation and unchecked conversion can easily - lead to incorrect memory references. The problems generated by such - references are usually difficult to tackle because the symptoms can be - very remote from the origin of the problem. In such cases, it is - very helpful to detect the problem as early as possible. This is the - purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. - - @noindent - In order to use the GNAT specific debugging pool, the user must - associate a debug pool object with each of the access types that may be - related to suspected memory problems. See Ada Reference Manual - 13.11. - @smallexample - @b{type} Ptr @b{is} @b{access} Some_Type; - Pool : GNAT.Debug_Pools.Debug_Pool; - @b{for} Ptr'Storage_Pool @b{use} Pool; - @end smallexample - - @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of - pool: the Checked_Pool. Such pools, like standard Ada storage pools, - allow the user to redefine allocation and deallocation strategies. They - also provide a checkpoint for each dereference, through the use of - the primitive operation @code{Dereference} which is implicitly called at - each dereference of an access value. - - Once an access type has been associated with a debug pool, operations on - values of the type may raise four distinct exceptions, - which correspond to four potential kinds of memory corruption: - @itemize @bullet - @item - @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } - @end itemize - - @noindent - For types associated with a Debug_Pool, dynamic allocation is performed using - the standard - GNAT allocation routine. References to all allocated chunks of memory - are kept in an internal dictionary. The deallocation strategy consists - in not releasing the memory to the underlying system but rather to fill - it with a memory pattern easily recognizable during debugging sessions: - The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#. - Upon each dereference, a check is made that the access value denotes a properly - allocated memory location. Here is a complete example of use of - @code{Debug_Pools}, that includes typical instances of memory corruption: - @smallexample - @iftex - @leftskip=0cm - @end iftex - @b{with} Gnat.Io; @b{use} Gnat.Io; - @b{with} Unchecked_Deallocation; - @b{with} Unchecked_Conversion; - @b{with} GNAT.Debug_Pools; - @b{with} System.Storage_Elements; - @b{with} Ada.Exceptions; @b{use} Ada.Exceptions; - @b{procedure} Debug_Pool_Test @b{is} - - @b{type} T @b{is} @b{access} Integer; - @b{type} U @b{is} @b{access} @b{all} T; - - P : GNAT.Debug_Pools.Debug_Pool; - @b{for} T'Storage_Pool @b{use} P; - - @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T); - @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T); - A, B : @b{aliased} T; - - @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line); - - @b{begin} - Info (P); - A := @b{new} Integer; - B := @b{new} Integer; - B := A; - Info (P); - Free (A); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - B := UC(A'Access); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - Info (P); - @b{end} Debug_Pool_Test; - @end smallexample - @noindent - The debug pool mechanism provides the following precise diagnostics on the - execution of this erroneous program: - @smallexample - Debug Pool info: - Total allocated bytes : 0 - Total deallocated bytes : 0 - Current Water Mark: 0 - High Water Mark: 0 - - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 0 - Current Water Mark: 8 - High Water Mark: 8 - - raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 4 - Current Water Mark: 4 - High Water Mark: 8 - - @end smallexample - - @node Creating Sample Bodies Using GNAT STUB - @chapter Creating Sample Bodies Using @code{GNAT STUB} - @findex GNAT STUB - - @noindent - @code{GNAT STUB} creates body stubs, that is, empty but compilable bodies - for library unit declarations. - - To create a body stub, @code{GNAT STUB} has to compile the library - unit declaration. Therefore, bodies can be created only for legal - library units. Moreover, if a library unit depends semantically upon - units located outside the current directory, you have to provide - the source search path when calling @code{GNAT STUB}, see the description - of @code{GNAT STUB} qualifiers below. - - @menu - * Running GNAT STUB:: - * Qualifiers for GNAT STUB:: - @end menu - - @node Running GNAT STUB - @section Running @code{GNAT STUB} - - @noindent - @code{GNAT STUB} has the command-line interface of the form - - @smallexample - $ GNAT STUB [qualifiers] filename [directory] - @end smallexample - - @noindent - where - @table @code - @item filename - is the name of the source file that contains a library unit declaration - for which a body must be created. This name should follow the GNAT file name - conventions. No crunching is allowed for this file name. The file - name may contain the path information. - - @item directory - indicates the directory to place a body stub (default is the - current directory) - - @item qualifiers - is an optional sequence of qualifiers as described in the next section - @end table - - @node Qualifiers for GNAT STUB - @section Qualifiers for @code{GNAT STUB} - - @table @code - - @item /FULL - If the destination directory already contains a file with a name of the body file - for the argument spec file, replace it with the generated body stub. - - @item /HEADER=SPEC - Put the comment header (i.e. all the comments preceding the - compilation unit) from the source of the library unit declaration - into the body stub. - - @item /HEADER=GENERAL - Put a sample comment header into the body stub. - - @item /SEARCH=direc - @itemx /NOCURRENT_DIRECTORY - These qualifiers have the same meaning as in calls to GNAT COMPILE. - They define the source search path in the call to GNAT COMPILE issued - by @code{GNAT STUB} to compile an argument source file. - - @item /INDENTATION=@var{n} - (@var{n} is a decimal natural number). Set the indentation level in the - generated body sample to n, '/INDENTATION=0' means "no indentation", - the default indentation is 3. - - @item /TREE_FILE=SAVE - Do not remove the tree file (i.e. the snapshot of the compiler internal - structures used by @code{GNAT STUB}) after creating the body stub. - - @item /LINE_LENGTH=@var{n} - (@var{n} is a decimal positive number) Set the maximum line length in the - body stub to n, the default is 78. - - @item /QUIET - Quiet mode: do not generate a confirmation when a body is - successfully created or a message when a body is not required for an - argument unit. - - @item /TREE_FILE=REUSE - Reuse the tree file (if it exists) instead of creating it: instead of - creating the tree file for the library unit declaration, GNAT STUB - tries to find it in the current directory and use it for creating - a body. If the tree file is not found, no body is created. @code{/REUSE} - also implies @code{/SAVE}, whether or not - @code{/SAVE} is set explicitly. - - @item /TREE_FILE=OVERWRITE - Overwrite the existing tree file: if the current directory already - contains the file which, according to the GNAT file name rules should - be considered as a tree file for the argument source file, GNAT STUB - will refuse to create the tree file needed to create a body sampler, - unless @code{-t} option is set - - @item /VERBOSE - Verbose mode: generate version information. - - @end table - - @node Reducing the Size of Ada Executables with GNAT ELIM - @chapter Reducing the Size of Ada Executables with @code{GNAT ELIM} - @findex GNAT ELIM - - @menu - * About GNAT ELIM:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for GNAT ELIM:: - * Running GNAT ELIM:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the GNAT ELIM Usage Cycle:: - @end menu - - @node About GNAT ELIM - @section About @code{GNAT ELIM} - - @noindent - When a program shares a set of Ada - packages with other programs, it may happen that this program uses - only a fraction of the subprograms defined in these packages. The code - created for these unused subprograms increases the size of the executable. - - @code{GNAT ELIM} tracks unused subprograms in an Ada program and - outputs a list of GNAT-specific @code{Eliminate} pragmas (see next - section) marking all the subprograms that are declared but never called. - By placing the list of @code{Eliminate} pragmas in the GNAT configuration - file @file{GNAT.ADC} and recompiling your program, you may decrease the - size of its executable, because the compiler will not generate the code - for 'eliminated' subprograms. - - @code{GNAT ELIM} needs as its input data a set of tree files - (see @ref{Tree Files}) representing all the components of a program to - process and a bind file for a main subprogram (see - @ref{Preparing Tree and Bind Files for GNAT ELIM}). - - @node Eliminate Pragma - @section @code{Eliminate} Pragma - @findex Eliminate - - @noindent - The simplified syntax of the Eliminate pragma used by @code{GNAT ELIM} is: - - @smallexample - @cartouche - @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name); - @end cartouche - @end smallexample - - @noindent - where - @table @code - @item Library_Unit_Name - full expanded Ada name of a library unit - - @item Subprogram_Name - a simple or expanded name of a subprogram declared within this - compilation unit - - @end table - - @noindent - The effect of an @code{Eliminate} pragma placed in the GNAT configuration - file @file{GNAT.ADC} is: - - @itemize @bullet - - @item - If the subprogram @code{Subprogram_Name} is declared within - the library unit @code{Library_Unit_Name}, the compiler will not generate - code for this subprogram. This applies to all overloaded subprograms denoted - by @code{Subprogram_Name}. - - @item - If a subprogram marked by the pragma @code{Eliminate} is used (called) - in a program, the compiler will produce an error message in the place where - it is called. - @end itemize - - @node Tree Files - @section Tree Files - @cindex Tree file - - @noindent - A tree file stores a snapshot of the compiler internal data - structures at the very end of a successful compilation. It contains all the - syntactic and semantic information for the compiled unit and all the - units upon which it depends semantically. - To use tools that make use of tree files, you - need to first produce the right set of tree files. - - GNAT produces correct tree files when /TREE_OUTPUT /NOLOAD options are set - in a GNAT COMPILE call. The tree files have an .adt extension. - Therefore, to produce a tree file for the compilation unit contained in a file - named @file{FOO.ADB}, you must use the command - - @smallexample - $ GNAT COMPILE /NOLOAD /TREE_OUTPUT FOO.ADB - @end smallexample - - @noindent - and you will get the tree file @file{foo.adt}. - compilation. - - @node Preparing Tree and Bind Files for GNAT ELIM - @section Preparing Tree and Bind Files for @code{GNAT ELIM} - - @noindent - A set of tree files covering the program to be analyzed with - @code{GNAT ELIM} and - the bind file for the main subprogram does not have to - be in the current directory. - '-T' GNAT ELIM option may be used to provide - the search path for tree files, and '-b' - option may be used to point to the bind - file to process (see @ref{Running GNAT ELIM}) - - If you do not have the appropriate set of tree - files and the right bind file, you - may create them in the current directory using the following procedure. - - Let @code{Main_Prog} be the name of a main subprogram, and suppose - this subprogram is in a file named @file{MAIN_PROG.ADB}. - - To create a bind file for @code{GNAT ELIM}, run @code{GNAT BIND} for - the main subprogram. @code{GNAT ELIM} can work with both Ada and C - bind files; when both are present, it uses the Ada bind file. - The following commands will build the program and create the bind file: - - @smallexample - $ GNAT MAKE /ACTIONS=COMPILE MAIN_PROG - $ GNAT BIND main_prog - @end smallexample - - @noindent - To create a minimal set of tree files covering the whole program, call - @code{GNAT MAKE} for this program as follows: - - @smallexample - $ GNAT MAKE /FORCE_COMPILE /ACTIONS=COMPILE /NOLOAD /TREE_OUTPUT MAIN_PROG - @end smallexample - - @noindent - The @code{/ACTIONS=COMPILE} GNAT MAKE option turns off the bind and link - steps, that are useless anyway because the sources are compiled with - @option{/NOLOAD} option which turns off code generation. - - The @code{/FORCE_COMPILE} GNAT MAKE option forces - recompilation of all the needed sources. - - This sequence of actions will create all the data needed by @code{GNAT ELIM} - from scratch and therefore guarantee its consistency. If you would like to - use some existing set of files as @code{GNAT ELIM} output, you must make - sure that the set of files is complete and consistent. You can use the - @code{-m} qualifier to check if there are missed tree files - - Note, that @code{GNAT ELIM} needs neither object nor ALI files. - - @node Running GNAT ELIM - @section Running @code{GNAT ELIM} - - @noindent - @code{GNAT ELIM} has the following command-line interface: - - @smallexample - $ GNAT ELIM [options] name - @end smallexample - - @noindent - @code{name} should be a full expanded Ada name of a main subprogram - of a program (partition). - - @code{GNAT ELIM} options: - - @table @code - @item /QUIET - Quiet mode: by default @code{GNAT ELIM} generates to the standard error - stream a trace of the source file names of the compilation units being - processed. This option turns this trace off. - - @item /VERBOSE - Verbose mode: @code{GNAT ELIM} version information is printed as Ada - comments to the standard output stream. - - @item /ALL - Also look for subprograms from the GNAT run time that can be eliminated. - - @item /MISSED - Check if any tree files are missing for an accurate result. - - @item /TREE_DIRS=@var{dir} - When looking for tree files also look in directory @var{dir} - - @item /BIND_FILE=@var{bind_file} - Specifies @var{bind_file} as the bind file to process. If not set, the name - of the bind file is computed from the full expanded Ada name of a main subprogram. - - @item -d@var{x} - Activate internal debugging qualifiers. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - mode desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - qualifiers in the body of the @code{GNAT ELIM.Options} unit in the compiler - source file @file{GNATELIM-OPTIONS.ADB}. - @end table - - @noindent - @code{GNAT ELIM} sends its output to the standard output stream, and all the - tracing and debug information is sent to the standard error stream. - In order to produce a proper GNAT configuration file - @file{GNAT.ADC}, redirection must be used: - - @smallexample - $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC - @end smallexample - - - @noindent - In order to append the @code{GNAT ELIM} output to the existing contents of - @file{GNAT.ADC}. - - @node Correcting the List of Eliminate Pragmas - @section Correcting the List of Eliminate Pragmas - - @noindent - In some rare cases it may happen that @code{GNAT ELIM} will try to eliminate - subprograms which are actually called in the program. In this case, the - compiler will generate an error message of the form: - - @smallexample - FILE.ADB:106:07: cannot call eliminated subprogram "My_Prog" - @end smallexample - - @noindent - You will need to manually remove the wrong @code{Eliminate} pragmas from - the @file{GNAT.ADC} file. It is advised that you recompile your program - from scratch after that because you need a consistent @file{GNAT.ADC} file - during the entire compilation. - - @node Making Your Executables Smaller - @section Making Your Executables Smaller - - @noindent - In order to get a smaller executable for your program you now have to - recompile the program completely with the new @file{GNAT.ADC} file - created by @code{GNAT ELIM} in your current directory: - - @smallexample - $ GNAT MAKE /FORCE_COMPILE MAIN_PROG - @end smallexample - - @noindent - (you will need @code{/FORCE_COMPILE} option for GNAT MAKE to - recompile everything - with the set of pragmas @code{Eliminate} you have obtained with - @code{GNAT ELIM}). - - Be aware that the set of @code{Eliminate} pragmas is specific to each - program. It is not recommended to merge sets of @code{Eliminate} - pragmas created for different programs in one @file{GNAT.ADC} file. - - @node Summary of the GNAT ELIM Usage Cycle - @section Summary of the GNAT ELIM Usage Cycle - - @noindent - Here is a quick summary of the steps to be taken in order to reduce - the size of your executables with @code{GNAT ELIM}. You may use - other GNAT options to control the optimization level, - to produce the debugging information, to set search path, etc. - - @enumerate - @item - Produce a bind file and a set of tree files - - @smallexample - $ GNAT MAKE /ACTIONS=COMPILE MAIN_PROG - $ GNAT BIND main_prog - $ GNAT MAKE /FORCE_COMPILE /NO_LINK /NOLOAD /TREE_OUTPUT MAIN_PROG - @end smallexample - - @item - Generate a list of @code{Eliminate} pragmas - @smallexample - $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC - @end smallexample - - @item - Recompile the application - - @smallexample - $ GNAT MAKE /FORCE_COMPILE MAIN_PROG - @end smallexample - - @end enumerate - - @node Other Utility Programs - @chapter Other Utility Programs - - @noindent - This chapter discusses some other utility programs available in the Ada - environment. - - @menu - * Using Other Utility Programs with GNAT:: - * The GNAT STANDARD Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - * Installing gnathtml:: - * LSE:: - * Profiling:: - @end menu - - @node Using Other Utility Programs with GNAT - @section Using Other Utility Programs with GNAT - - @noindent - The object files generated by GNAT are in standard system format and in - particular the debugging information uses this format. This means - programs generated by GNAT can be used with existing utilities that - depend on these formats. - - - @node The GNAT STANDARD Utility Program - @section The @code{GNAT STANDARD} Utility Program - - @noindent - Many of the definitions in package Standard are implementation-dependent. - However, the source of this package does not exist as an Ada source - file, so these values cannot be determined by inspecting the source. - They can be determined by examining in detail the coding of - @file{CSTAND.ADB} which creates the image of Standard in the compiler, - but this is awkward and requires a great deal of internal knowledge - about the system. - - The @code{GNAT STANDARD} utility is designed to deal with this situation. - It is an Ada program that dynamically determines the - values of all the relevant parameters in Standard, and prints them - out in the form of an Ada source listing for Standard, displaying all - the values of interest. This output is generated to - @file{SYS$OUTPUT}. - - To determine the value of any parameter in package Standard, simply - run @code{GNAT STANDARD} with no qualifiers or arguments, and examine - the output. This is preferable to consulting documentation, because - you know that the values you are getting are the actual ones provided - by the executing system. - - @node The External Symbol Naming Scheme of GNAT - @section The External Symbol Naming Scheme of GNAT - - @noindent - In order to interpret the output from GNAT, when using tools that are - originally intended for use with other languages, it is useful to - understand the conventions used to generate link names from the Ada - entity names. - - All link names are in all lowercase letters. With the exception of library - procedure names, the mechanism used is simply to use the full expanded - Ada name with dots replaced by double underscores. For example, suppose - we have the following package spec: - - @smallexample - @group - @cartouche - @b{package} QRS @b{is} - MN : Integer; - @b{end} QRS; - @end cartouche - @end group - @end smallexample - - @noindent - The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so - the corresponding link name is @code{qrs__mn}. - @findex Export - Of course if a @code{pragma Export} is used this may be overridden: - - @smallexample - @group - @cartouche - @b{package} Exports @b{is} - Var1 : Integer; - @b{pragma} Export (Var1, C, External_Name => "var1_name"); - Var2 : Integer; - @b{pragma} Export (Var2, C, Link_Name => "var2_link_name"); - @b{end} Exports; - @end cartouche - @end group - @end smallexample - - @noindent - In this case, the link name for @var{Var1} is whatever link name the - C compiler would assign for the C function @var{var1_name}. This typically - would be either @var{var1_name} or @var{_var1_name}, depending on operating - system conventions, but other possibilities exist. The link name for - @var{Var2} is @var{var2_link_name}, and this is not operating system - dependent. - - @findex _main - One exception occurs for library level procedures. A potential ambiguity - arises between the required name @code{_main} for the C main program, - and the name we would otherwise assign to an Ada library level procedure - called @code{Main} (which might well not be the main program). - - To avoid this ambiguity, we attach the prefix @code{_ada_} to such - names. So if we have a library level procedure such as - - @smallexample - @group - @cartouche - @b{procedure} Hello (S : String); - @end cartouche - @end group - @end smallexample - - @noindent - the external name of this procedure will be @var{_ada_hello}. - - @node Ada Mode for Glide - @section Ada Mode for @code{Glide} - - @noindent - The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the - user in understanding existing code and facilitates writing new code. It - furthermore provides some utility functions for easier integration of - standard EMACS features when programming in Ada. - - @subsection General Features: - - @itemize @bullet - @item - Full Integrated Development Environment : - - @itemize @bullet - @item - support of 'project files' for the configuration (directories, - compilation options,...) - - @item - compiling and stepping through error messages. - - @item - running and debugging your applications within Glide. - @end itemize - - @item - easy to use for beginners by pull-down menus, - - @item - user configurable by many user-option variables. - @end itemize - - @subsection Ada Mode Features That Help Understanding Code: - - @itemize @bullet - @item - functions for easy and quick stepping through Ada code, - - @item - getting cross reference information for identifiers (e.g. find the - defining place by a keystroke), - - @item - displaying an index menu of types and subprograms and move point to - the chosen one, - - @item - automatic color highlighting of the various entities in Ada code. - @end itemize - - @subsection Glide Support for Writing Ada Code: - - @itemize @bullet - @item - switching between spec and body files with possible - autogeneration of body files, - - @item - automatic formating of subprograms parameter lists. - - @item - automatic smart indentation according to Ada syntax, - - @item - automatic completion of identifiers, - - @item - automatic casing of identifiers, keywords, and attributes, - - @item - insertion of statement templates, - - @item - filling comment paragraphs like filling normal text, - @end itemize - - For more information, please refer to the online Glide documentation - available in the Glide --> Help Menu. - - @node Converting Ada Files to html with gnathtml - @section Converting Ada Files to html with @code{gnathtml} - - @noindent - This @code{Perl} script allows Ada source files to be browsed using - standard Web browsers. For installation procedure, see the section - @xref{Installing gnathtml}. - - Ada reserved keywords are highlighted in a bold font and Ada comments in - a blue font. Unless your program was compiled with the GNAT COMPILE @option{/XREF=SUPPRESS} - qualifier to suppress the generation of cross-referencing information, user - defined variables and types will appear in a different color; you will - be able to click on any identifier and go to its declaration. - - The command line is as follow: - @smallexample - $ perl gnathtml.pl [qualifiers] ada-files - @end smallexample - - You can pass it as many Ada files as you want. @code{gnathtml} will generate - an html file for every ada file, and a global file called @file{index.htm}. - This file is an index of every identifier defined in the files. - - The available qualifiers are the following ones : - - @table @code - @item -83 - @cindex @code{-83} (@code{gnathtml}) - Only the subset on the Ada 83 keywords will be highlighted, not the full - Ada 95 keywords set. - - @item -cc @var{color} - This option allows you to change the color used for comments. The default - value is green. The color argument can be any name accepted by html. - - @item -d - @cindex @code{-d} (@code{gnathtml}) - If the ada files depend on some other files (using for instance the - @code{with} command, the latter will also be converted to html. - Only the files in the user project will be converted to html, not the files - in the run-time library itself. - - @item -D - This command is the same as -d above, but @code{gnathtml} will also look - for files in the run-time library, and generate html files for them. - - @item -f - @cindex @code{-f} (@code{gnathtml}) - By default, gnathtml will generate html links only for global entities - ('with'ed units, global variables and types,...). If you specify the - @code{-f} on the command line, then links will be generated for local - entities too. - - @item -l @var{number} - @cindex @code{-l} (@code{gnathtml}) - If this qualifier is provided and @var{number} is not 0, then @code{gnathtml} - will number the html files every @var{number} line. - - @item -I @var{dir} - @cindex @code{-I} (@code{gnathtml}) - Specify a directory to search for library files (@file{.ALI} files) and - source files. You can provide several -I qualifiers on the command line, - and the directories will be parsed in the order of the command line. - - @item -o @var{dir} - @cindex @code{-o} (@code{gnathtml}) - Specify the output directory for html files. By default, gnathtml will - saved the generated html files in a subdirectory named @file{html/}. - - @item -p @var{file} - @cindex @code{-p} (@code{gnathtml}) - If you are using EMACS and the most recent EMACS Ada mode, which provides - a full Integrated Development Environment for compiling, checking, - running and debugging applications, you may be using @file{.adp} files - to give the directories where EMACS can find sources and object files. - - Using this qualifier, you can tell gnathtml to use these files. This allows - you to get an html version of your application, even if it is spread - over multiple directories. - - @item -sc @var{color} - @cindex @code{-sc} (@code{gnathtml}) - This option allows you to change the color used for symbol definitions. - The default value is red. The color argument can be any name accepted by html. - - @item -t @var{file} - @cindex @code{-t} (@code{gnathtml}) - This qualifier provides the name of a file. This file contains a list of - file names to be converted, and the effect is exactly as though they had - appeared explicitly on the command line. This - is the recommended way to work around the command line length limit on some - systems. - - @end table - - @node Installing gnathtml - @section Installing @code{gnathtml} - - @noindent - @code{Perl} needs to be installed on your machine to run this script. - @code{Perl} is freely available for almost every architecture and - Operating System via the Internet. - - On Unix systems, you may want to modify the first line of the script - @code{gnathtml}, to explicitly tell the Operating system where Perl - is. The syntax of this line is : - @smallexample - #!full_path_name_to_perl - @end smallexample - - @noindent - Alternatively, you may run the script using the following command line: - - @smallexample - $ perl gnathtml.pl [qualifiers] files - @end smallexample - - @node LSE - @section LSE - @findex LSE - - @noindent - The GNAT distribution provides an Ada 95 template for the Digital Language - Sensitive Editor (LSE), a component of DECset. In order to - access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV. - - @node Profiling - @section Profiling - @findex PCA - - @noindent - GNAT supports The Digital Performance Coverage Analyzer (PCA), a component - of DECset. To use it proceed as outlined under "HELP PCA", except for running - the collection phase with the /DEBUG qualifier. - - @smallexample - $ GNAT MAKE /DEBUG - $ DEFINE LIB$DEBUG PCA$COLLECTOR - $ RUN/DEBUG - @end smallexample - @noindent - - @node Running and Debugging Ada Programs - @chapter Running and Debugging Ada Programs - @cindex Debugging - - @noindent - This chapter discusses how to debug Ada programs. An incorrect Ada program - may be handled in three ways by the GNAT compiler: - - @enumerate - @item - The illegality may be a violation of the static semantics of Ada. In - that case GNAT diagnoses the constructs in the program that are illegal. - It is then a straightforward matter for the user to modify those parts of - the program. - - @item - The illegality may be a violation of the dynamic semantics of Ada. In - that case the program compiles and executes, but may generate incorrect - results, or may terminate abnormally with some exception. - - @item - When presented with a program that contains convoluted errors, GNAT - itself may terminate abnormally without providing full diagnostics on - the incorrect user program. - @end enumerate - - @menu - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - @end menu - - @cindex Debugger - @findex GDB - - @node The GNAT Debugger GDB - @section The GNAT Debugger GDB - - @noindent - @code{GDB} is a general purpose, platform-independent debugger that - can be used to debug mixed-language programs compiled with @code{GCC}, - and in particular is capable of debugging Ada programs compiled with - GNAT. The latest versions of @code{GDB} are Ada-aware and can handle - complex Ada data structures. - - The manual @cite{Debugging with GDB} - , located in the GNU:[DOCS] directory, - contains full details on the usage of @code{GDB}, including a section on - its usage on programs. This manual should be consulted for full - details. The section that follows is a brief introduction to the - philosophy and use of @code{GDB}. - - When GNAT programs are compiled, the compiler optionally writes debugging - information into the generated object file, including information on - line numbers, and on declared types and variables. This information is - separate from the generated code. It makes the object files considerably - larger, but it does not add to the size of the actual executable that - will be loaded into memory, and has no impact on run-time performance. The - generation of debug information is triggered by the use of the - /DEBUG qualifier in the GNAT COMPILE or GNAT MAKE command used to carry out - the compilations. It is important to emphasize that the use of these - options does not change the generated code. - - The debugging information is written in standard system formats that - are used by many tools, including debuggers and profilers. The format - of the information is typically designed to describe C types and - semantics, but GNAT implements a translation scheme which allows full - details about Ada types and variables to be encoded into these - standard C formats. Details of this encoding scheme may be found in - the file EXP_DBUG.ADS in the GNAT source distribution. However, the - details of this encoding are, in general, of no interest to a user, - since @code{GDB} automatically performs the necessary decoding. - - When a program is bound and linked, the debugging information is - collected from the object files, and stored in the executable image of - the program. Again, this process significantly increases the size of - the generated executable file, but it does not increase the size of - the executable program itself. Furthermore, if this program is run in - the normal manner, it runs exactly as if the debug information were - not present, and takes no more actual memory. - - However, if the program is run under control of @code{GDB}, the - debugger is activated. The image of the program is loaded, at which - point it is ready to run. If a run command is given, then the program - will run exactly as it would have if @code{GDB} were not present. This - is a crucial part of the @code{GDB} design philosophy. @code{GDB} is - entirely non-intrusive until a breakpoint is encountered. If no - breakpoint is ever hit, the program will run exactly as it would if no - debugger were present. When a breakpoint is hit, @code{GDB} accesses - the debugging information and can respond to user commands to inspect - variables, and more generally to report on the state of execution. - - @node Running GDB - @section Running GDB - - @noindent - The debugger can be launched directly and simply from @code{glide} or - through its graphical interface: @code{gvd}. It can also be used - directly in text mode. Here is described the basic use of @code{GDB} - in text mode. All the commands described below can be used in the - @code{gvd} console window eventhough there is usually other more - graphical ways to achieve the same goals. - - - @noindent - The command to run @code{GDB} in text mode is - - @smallexample - $ $ GDB PROGRAM - @end smallexample - - @noindent - where @code{PROGRAM} is the name of the executable file. This - activates the debugger and results in a prompt for debugger commands. - The simplest command is simply @code{run}, which causes the program to run - exactly as if the debugger were not present. The following section - describes some of the additional commands that can be given to @code{GDB}. - - - @node Introduction to GDB Commands - @section Introduction to GDB Commands - - @noindent - @code{GDB} contains a large repertoire of commands. The manual - @cite{Debugging with GDB} - , located in the GNU:[DOCS] directory, - includes extensive documentation on the use - of these commands, together with examples of their use. Furthermore, - the command @var{help} invoked from within @code{GDB} activates a simple help - facility which summarizes the available commands and their options. - In this section we summarize a few of the most commonly - used commands to give an idea of what @code{GDB} is about. You should create - a simple program with debugging information and experiment with the use of - these @code{GDB} commands on the program as you read through the - following section. - - @table @code - @item set args @var{arguments} - The @var{arguments} list above is a list of arguments to be passed to - the program on a subsequent run command, just as though the arguments - had been entered on a normal invocation of the program. The @code{set args} - command is not needed if the program does not require arguments. - - @item run - The @code{run} command causes execution of the program to start from - the beginning. If the program is already running, that is to say if - you are currently positioned at a breakpoint, then a prompt will ask - for confirmation that you want to abandon the current execution and - restart. - - @item breakpoint @var{location} - The breakpoint command sets a breakpoint, that is to say a point at which - execution will halt and @code{GDB} will await further - commands. @var{location} is - either a line number within a file, given in the format @code{file:linenumber}, - or it is the name of a subprogram. If you request that a breakpoint be set on - a subprogram that is overloaded, a prompt will ask you to specify on which of - those subprograms you want to breakpoint. You can also - specify that all of them should be breakpointed. If the program is run - and execution encounters the breakpoint, then the program - stops and @code{GDB} signals that the breakpoint was encountered by - printing the line of code before which the program is halted. - - @item breakpoint exception @var{name} - A special form of the breakpoint command which breakpoints whenever - exception @var{name} is raised. - If @var{name} is omitted, - then a breakpoint will occur when any exception is raised. - - @item print @var{expression} - This will print the value of the given expression. Most simple - Ada expression formats are properly handled by @code{GDB}, so the expression - can contain function calls, variables, operators, and attribute references. - - @item continue - Continues execution following a breakpoint, until the next breakpoint or the - termination of the program. - - @item step - Executes a single line after a breakpoint. If the next statement is a subprogram - call, execution continues into (the first statement of) the - called subprogram. - - @item next - Executes a single line. If this line is a subprogram call, executes and - returns from the call. - - @item list - Lists a few lines around the current source location. In practice, it - is usually more convenient to have a separate edit window open with the - relevant source file displayed. Successive applications of this command - print subsequent lines. The command can be given an argument which is a - line number, in which case it displays a few lines around the specified one. - - @item backtrace - Displays a backtrace of the call chain. This command is typically - used after a breakpoint has occurred, to examine the sequence of calls that - leads to the current breakpoint. The display includes one line for each - activation record (frame) corresponding to an active subprogram. - - @item up - At a breakpoint, @code{GDB} can display the values of variables local - to the current frame. The command @code{up} can be used to - examine the contents of other active frames, by moving the focus up - the stack, that is to say from callee to caller, one frame at a time. - - @item down - Moves the focus of @code{GDB} down from the frame currently being - examined to the frame of its callee (the reverse of the previous command), - - @item frame @var{n} - Inspect the frame with the given number. The value 0 denotes the frame - of the current breakpoint, that is to say the top of the call stack. - - @end table - - The above list is a very short introduction to the commands that - @code{GDB} provides. Important additional capabilities, including conditional - breakpoints, the ability to execute command sequences on a breakpoint, - the ability to debug at the machine instruction level and many other - features are described in detail in @cite{Debugging with GDB}. - Note that most commands can be abbreviated - (for example, c for continue, bt for backtrace). - - @node Using Ada Expressions - @section Using Ada Expressions - @cindex Ada expressions - - @noindent - @code{GDB} supports a fairly large subset of Ada expression syntax, with some - extensions. The philosophy behind the design of this subset is - - @itemize @bullet - @item - That @code{GDB} should provide basic literals and access to operations for - arithmetic, dereferencing, field selection, indexing, and subprogram calls, - leaving more sophisticated computations to subprograms written into the - program (which therefore may be called from @code{GDB}). - - @item - That type safety and strict adherence to Ada language restrictions - are not particularly important to the @code{GDB} user. - - @item - That brevity is important to the @code{GDB} user. - @end itemize - - Thus, for brevity, the debugger acts as if there were - implicit @code{with} and @code{use} clauses in effect for all user-written - packages, thus making it unnecessary to fully qualify most names with - their packages, regardless of context. Where this causes ambiguity, - @code{GDB} asks the user's intent. - - For details on the supported Ada syntax, see @cite{Debugging with GDB}. - - @node Calling User-Defined Subprograms - @section Calling User-Defined Subprograms - - @noindent - An important capability of @code{GDB} is the ability to call user-defined - subprograms while debugging. This is achieved simply by entering - a subprogram call statement in the form: - - @smallexample - call subprogram-name (parameters) - @end smallexample - - @noindent - The keyword @code{call} can be omitted in the normal case where the - @code{subprogram-name} does not coincide with any of the predefined - @code{GDB} commands. - - The effect is to invoke the given subprogram, passing it the - list of parameters that is supplied. The parameters can be expressions and - can include variables from the program being debugged. The - subprogram must be defined - at the library level within your program, and @code{GDB} will call the - subprogram within the environment of your program execution (which - means that the subprogram is free to access or even modify variables - within your program). - - The most important use of this facility is in allowing the inclusion of - debugging routines that are tailored to particular data structures - in your program. Such debugging routines can be written to provide a suitably - high-level description of an abstract type, rather than a low-level dump - of its physical layout. After all, the standard - @code{GDB print} command only knows the physical layout of your - types, not their abstract meaning. Debugging routines can provide information - at the desired semantic level and are thus enormously useful. - - For example, when debugging GNAT itself, it is crucial to have access to - the contents of the tree nodes used to represent the program internally. - But tree nodes are represented simply by an integer value (which in turn - is an index into a table of nodes). - Using the @code{print} command on a tree node would simply print this integer - value, which is not very useful. But the PN routine (defined in file - TREEPR.ADB in the GNAT sources) takes a tree node as input, and displays - a useful high level representation of the tree node, which includes the - syntactic category of the node, its position in the source, the integers - that denote descendant nodes and parent node, as well as varied - semantic information. To study this example in more detail, you might want to - look at the body of the PN procedure in the stated file. - - @node Using the Next Command in a Function - @section Using the Next Command in a Function - - @noindent - When you use the @code{next} command in a function, the current source - location will advance to the next statement as usual. A special case - arises in the case of a @code{return} statement. - - Part of the code for a return statement is the "epilog" of the function. - This is the code that returns to the caller. There is only one copy of - this epilog code, and it is typically associated with the last return - statement in the function if there is more than one return. In some - implementations, this epilog is associated with the first statement - of the function. - - The result is that if you use the @code{next} command from a return - statement that is not the last return statement of the function you - may see a strange apparent jump to the last return statement or to - the start of the function. You should simply ignore this odd jump. - The value returned is always that from the first return statement - that was stepped through. - - @node Ada Exceptions - @section Breaking on Ada Exceptions - @cindex Exceptions - - @noindent - You can set breakpoints that trip when your program raises - selected exceptions. - - @table @code - @item break exception - Set a breakpoint that trips whenever (any task in the) program raises - any exception. - - @item break exception @var{name} - Set a breakpoint that trips whenever (any task in the) program raises - the exception @var{name}. - - @item break exception unhandled - Set a breakpoint that trips whenever (any task in the) program raises an - exception for which there is no handler. - - @item info exceptions - @itemx info exceptions @var{regexp} - The @code{info exceptions} command permits the user to examine all defined - exceptions within Ada programs. With a regular expression, @var{regexp}, as - argument, prints out only those exceptions whose name matches @var{regexp}. - @end table - - @node Ada Tasks - @section Ada Tasks - @cindex Tasks - - @noindent - @code{GDB} allows the following task-related commands: - - @table @code - @item info tasks - This command shows a list of current Ada tasks, as in the following example: - - @smallexample - @iftex - @leftskip=0cm - @end iftex - (GDB) info tasks - ID TID P-ID Thread Pri State Name - 1 8088000 0 807e000 15 Child Activation Wait main_task - 2 80a4000 1 80ae000 15 Accept/Select Wait b - 3 809a800 1 80a4800 15 Child Activation Wait a - * 4 80ae800 3 80b8000 15 Running c - @end smallexample - - @noindent - In this listing, the asterisk before the first task indicates it to be the - currently running task. The first column lists the task ID that is used - to refer to tasks in the following commands. - - @item break @var{linespec} task @var{taskid} - @itemx break @var{linespec} task @var{taskid} if @dots{} - @cindex Breakpoints and tasks - These commands are like the @code{break @dots{} thread @dots{}}. - @var{linespec} specifies source lines. - - Use the qualifier @samp{task @var{taskid}} with a breakpoint command - to specify that you only want @code{GDB} to stop the program when a - particular Ada task reaches this breakpoint. @var{taskid} is one of the - numeric task identifiers assigned by @code{GDB}, shown in the first - column of the @samp{info tasks} display. - - If you do not specify @samp{task @var{taskid}} when you set a - breakpoint, the breakpoint applies to @emph{all} tasks of your - program. - - You can use the @code{task} qualifier on conditional breakpoints as - well; in this case, place @samp{task @var{taskid}} before the - breakpoint condition (before the @code{if}). - - @item task @var{taskno} - @cindex Task switching - - This command allows to qualifier to the task referred by @var{taskno}. In - particular, This allows to browse the backtrace of the specified - task. It is advised to qualifier back to the original task before - continuing execution otherwise the scheduling of the program may be - perturbated. - @end table - - @noindent - For more detailed information on the tasking support, see @cite{Debugging with GDB}. - - @node Debugging Generic Units - @section Debugging Generic Units - @cindex Debugging Generic Units - @cindex Generics - - @noindent - GNAT always uses code expansion for generic instantiation. This means that - each time an instantiation occurs, a complete copy of the original code is - made, with appropriate substitutions of formals by actuals. - - It is not possible to refer to the original generic entities in - @code{GDB}, but it is always possible to debug a particular instance of - a generic, by using the appropriate expanded names. For example, if we have - - @smallexample - @group - @cartouche - @b{procedure} g @b{is} - - @b{generic package} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer); - @b{end} k; - - @b{package body} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer) @b{is} - @b{begin} - v1 := v1 + 1; - @b{end} kp; - @b{end} k; - - @b{package} k1 @b{is new} k; - @b{package} k2 @b{is new} k; - - var : integer := 1; - - @b{begin} - k1.kp (var); - k2.kp (var); - k1.kp (var); - k2.kp (var); - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Then to break on a call to procedure kp in the k2 instance, simply - use the command: - - @smallexample - (GDB) break g.k2.kp - @end smallexample - - @noindent - When the breakpoint occurs, you can step through the code of the - instance in the normal manner and examine the values of local variables, as for - other units. - - @node GNAT Abnormal Termination or Failure to Terminate - @section GNAT Abnormal Termination or Failure to Terminate - @cindex GNAT Abnormal Termination or Failure to Terminate - - @noindent - When presented with programs that contain serious errors in syntax - or semantics, - GNAT may on rare occasions experience problems in operation, such - as aborting with a - segmentation fault or illegal memory access, raising an internal - exception, terminating abnormally, or failing to terminate at all. - In such cases, you can activate - various features of GNAT that can help you pinpoint the construct in your - program that is the likely source of the problem. - - The following strategies are presented in increasing order of - difficulty, corresponding to your experience in using GNAT and your - familiarity with compiler internals. - - @enumerate - @item - Run @code{GNAT COMPILE} with the @option{/REPORT_ERRORS=FULL}. This first - qualifier causes all errors on a given line to be reported. In its absence, - only the first error on a line is displayed. - - The @option{/REPORT_ERRORS=IMMEDIATE} qualifier causes errors to be displayed as soon as they - are encountered, rather than after compilation is terminated. If GNAT - terminates prematurely or goes into an infinite loop, the last error - message displayed may help to pinpoint the culprit. - - @item - Run @code{GNAT COMPILE} with the @code{/VERBOSE} qualifier. In this mode, - @code{GNAT COMPILE} produces ongoing information about the progress of the - compilation and provides the name of each procedure as code is - generated. This qualifier allows you to find which Ada procedure was being - compiled when it encountered a code generation problem. - - @item - @cindex @option{/TRACE_UNITS} qualifier - Run @code{GNAT COMPILE} with the @option{/TRACE_UNITS} qualifier. This is a GNAT specific - qualifier that does for the front-end what @code{VERBOSE} does for the back end. - The system prints the name of each unit, either a compilation unit or - nested unit, as it is being analyzed. - @item - Finally, you can start - @code{GDB} directly on the @code{GNAT1} executable. @code{GNAT1} is the - front-end of GNAT, and can be run independently (normally it is just - called from @code{GNAT COMPILE}). You can use @code{GDB} on @code{GNAT1} as you - would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The - @code{where} command is the first line of attack; the variable - @code{lineno} (seen by @code{print lineno}), used by the second phase of - @code{GNAT1} and by the @code{GNAT COMPILE} backend, indicates the source line at - which the execution stopped, and @code{input_file name} indicates the name of - the source file. - @end enumerate - - @node Naming Conventions for GNAT Source Files - @section Naming Conventions for GNAT Source Files - - @noindent - In order to examine the workings of the GNAT system, the following - brief description of its organization may be helpful: - - @itemize @bullet - @item - Files with prefix @file{SC} contain the lexical scanner. - - @item - All files prefixed with @file{PAR} are components of the parser. The - numbers correspond to chapters of the Ada 95 Reference Manual. For example, - parsing of select statements can be found in @file{PAR-CH9.ADB}. - - @item - All files prefixed with @file{SEM} perform semantic analysis. The - numbers correspond to chapters of the Ada standard. For example, all - issues involving context clauses can be found in @file{SEM_CH10.ADB}. In - addition, some features of the language require sufficient special processing - to justify their own semantic files: sem_aggr for aggregates, sem_disp for - dynamic dispatching, etc. - - @item - All files prefixed with @file{EXP} perform normalization and - expansion of the intermediate representation (abstract syntax tree, or AST). - these files use the same numbering scheme as the parser and semantics files. - For example, the construction of record initialization procedures is done in - @file{EXP_CH3.ADB}. - - @item - The files prefixed with @file{BIND} implement the binder, which - verifies the consistency of the compilation, determines an order of - elaboration, and generates the bind file. - - @item - The files @file{ATREE.ADS} and @file{ATREE.ADB} detail the low-level - data structures used by the front-end. - - @item - The files @file{SINFO.ADS} and @file{SINFO.ADB} detail the structure of - the abstract syntax tree as produced by the parser. - - @item - The files @file{EINFO.ADS} and @file{EINFO.ADB} detail the attributes of - all entities, computed during semantic analysis. - - @item - Library management issues are dealt with in files with prefix - @file{LIB}. - - @item - @findex Ada - @cindex Annex A - Ada files with the prefix @file{A-} are children of @code{Ada}, as - defined in Annex A. - - @item - @findex Interfaces - @cindex Annex B - Files with prefix @file{I-} are children of @code{Interfaces}, as - defined in Annex B. - - @item - @findex System - Files with prefix @file{S-} are children of @code{System}. This includes - both language-defined children and GNAT run-time routines. - - @item - @findex GNAT - Files with prefix @file{G-} are children of @code{GNAT}. These are useful - general-purpose packages, fully documented in their specifications. All - the other @file{.C} files are modifications of common @code{GNAT COMPILE} files. - @end itemize - - @node Getting Internal Debugging Information - @section Getting Internal Debugging Information - - @noindent - Most compilers have internal debugging qualifiers and modes. GNAT - does also, except GNAT internal debugging qualifiers and modes are not - secret. A summary and full description of all the compiler and binder - debug flags are in the file @file{DEBUG.ADB}. You must obtain the - sources of the compiler to see the full detailed effects of these flags. - - The qualifiers that print the source of the program (reconstructed from - the internal tree) are of general interest for user programs, as are the - options to print - the full internal tree, and the entity table (the symbol table - information). The reconstructed source provides a readable version of the - program after the front-end has completed analysis and expansion, and is useful - when studying the performance of specific constructs. For example, constraint - checks are indicated, complex aggregates are replaced with loops and - assignments, and tasking primitives are replaced with run-time calls. - - @node Stack Traceback - @section Stack Traceback - @cindex traceback - @cindex stack traceback - @cindex stack unwinding - - @noindent - Traceback is a mechanism to display the sequence of subprogram calls that - leads to a specified execution point in a program. Often (but not always) - the execution point is an instruction at which an exception has been raised. - This mechanism is also known as @i{stack unwinding} because it obtains - its information by scanning the run-time stack and recovering the activation - records of all active subprograms. Stack unwinding is one of the most - important tools for program debugging. - - @noindent - The first entry stored in traceback corresponds to the deepest calling level, - that is to say the subprogram currently executing the instruction - from which we want to obtain the traceback. - - @noindent - Note that there is no runtime performance penalty when stack traceback - is enabled and no exception are raised during program execution. - - @menu - * Non-Symbolic Traceback:: - * Symbolic Traceback:: - @end menu - - @node Non-Symbolic Traceback - @subsection Non-Symbolic Traceback - @cindex traceback, non-symbolic - - @noindent - Note: this feature is not supported on all platforms. See - @file{GNAT.Traceback spec in G-TRACEB.ADS} for a complete list of supported - platforms. - - @menu - * Tracebacks From an Unhandled Exception:: - * Tracebacks From Exception Occurrences (non-symbolic):: - * Tracebacks From Anywhere in a Program (non-symbolic):: - @end menu - - @node Tracebacks From an Unhandled Exception - @subsubsection Tracebacks From an Unhandled Exception - - @noindent - A runtime non-symbolic traceback is a list of addresses of call instructions. - To enable this feature you must use the @code{-E} - @code{GNAT BIND}'s option. With this option a stack traceback is stored as part - of exception information. It is possible to retrieve this information using the - standard @code{Ada.Exception.Exception_Information} routine. - - @noindent - Let's have a look at a simple example: - - @smallexample - @cartouche - @group - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ GNAT MAKE stb /BINDER_QUALIFIERS -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: STB.ADB:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @noindent - As we see the traceback lists a sequence of addresses for the unhandled - exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to - guess that this exception come from procedure P1. To translate these - addresses into the source lines where the calls appear, the - @code{addr2line} tool, described below, is invaluable. The use of this tool - requires the program to be compiled with debug information. - - @smallexample - $ GNAT MAKE -g stb /BINDER_QUALIFIERS -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: STB.ADB:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - - $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 - 0x4011f1 0x77e892a4 - - 00401373 at d:/stb/STB.ADB:5 - 0040138B at d:/stb/STB.ADB:10 - 0040139C at d:/stb/STB.ADB:14 - 00401335 at d:/stb/B~STB.ADB:104 - 004011C4 at /build/.../CRT1.C:200 - 004011F1 at /build/.../CRT1.C:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - @code{addr2line} has a number of other useful options: - - @table @code - @item --functions - to get the function name corresponding to any location - - @item --demangle=gnat - to use the @b{gnat} decoding mode for the function names. Note that - for binutils version 2.9.x the option is simply @code{--demangle}. - @end table - - @smallexample - $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b - 0x40139c 0x401335 0x4011c4 0x4011f1 - - 00401373 in stb.p1 at d:/stb/STB.ADB:5 - 0040138B in stb.p2 at d:/stb/STB.ADB:10 - 0040139C in stb at d:/stb/STB.ADB:14 - 00401335 in main at d:/stb/B~STB.ADB:104 - 004011C4 in <__mingw_CRTStartup> at /build/.../CRT1.C:200 - 004011F1 in at /build/.../CRT1.C:222 - @end smallexample - - @noindent - From this traceback we can see that the exception was raised in - @file{STB.ADB} at line 5, which was reached from a procedure call in - @file{STB.ADB} at line 10, and so on. The @file{B~STD.ADB} is the binder file, - which contains the call to the main program. - @pxref{Running GNAT BIND}. The remaining entries are assorted runtime routines, - and the output will vary from platform to platform. - - @noindent - It is also possible to use @code{GDB} with these traceback addresses to debug - the program. For example, we can break at a given code location, as reported - in the stack traceback: - - @smallexample - $ GDB -nw stb - - (GDB) break *0x401373 - Breakpoint 1 at 0x401373: file STB.ADB, line 5. - @end smallexample - - @noindent - It is important to note that the stack traceback addresses - do not change when debug information is included. This is particularly useful - because it makes it possible to release software without debug information (to - minimize object size), get a field report that includes a stack traceback - whenever an internal bug occurs, and then be able to retrieve the sequence - of calls with the same program compiled with debug information. - - @node Tracebacks From Exception Occurrences (non-symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @noindent - Non-symbolic tracebacks are obtained by using the @code{-E} binder argument. - The stack traceback is attached to the exception information string, and can - be retrieved in an exception handler within the Ada program, by means of the - Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with Ada.Exceptions; - - procedure STB is - - use Ada; - use Ada.Exceptions; - - procedure P1 is - K : Positive := 1; - begin - K := K - 1; - exception - when E : others => - Text_IO.Put_Line (Exception_Information (E)); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @noindent - This program will output: - - @smallexample - $ stb - - Exception name: CONSTRAINT_ERROR - Message: STB.ADB:12 - Call stack traceback locations: - 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @node Tracebacks From Anywhere in a Program (non-symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is also possible to retrieve a stack traceback from anywhere in a - program. For this you need to - use the @code{GNAT.Traceback} API. This package includes a procedure called - @code{Call_Chain} that computes a complete stack traceback, as well as useful - display procedures described below. It is not necessary to use the - @code{-E GNAT BIND} option in this case, because the stack traceback mechanism - is invoked explicitly. - - @noindent - In the following example we compute a traceback at a specific location in - the program, and we display it using @code{GNAT.Debug_Utilities.Image} to - convert addresses to strings: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Debug_Utilities; - - procedure STB is - - use Ada; - use GNAT; - use GNAT.Traceback; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - - Text_IO.Put ("In STB.P1 : "); - - for K in 1 .. Len loop - Text_IO.Put (Debug_Utilities.Image (TB (K))); - Text_IO.Put (' '); - end loop; - - Text_IO.New_Line; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ GNAT MAKE stb - $ stb - - In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# - 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# - @end smallexample - - @node Symbolic Traceback - @subsection Symbolic Traceback - @cindex traceback, symbolic - - @noindent - A symbolic traceback is a stack traceback in which procedure names are - associated with each code location. - - @noindent - Note that this feature is not supported on all platforms. See - @file{GNAT.Traceback.Symbolic spec in G-TRASYM.ADS} for a complete - list of currently supported platforms. - - @noindent - Note that the symbolic traceback requires that the program be compiled - with debug information. If it is not compiled with debug information - only the non-symbolic information will be valid. - - @menu - * Tracebacks From Exception Occurrences (symbolic):: - * Tracebacks From Anywhere in a Program (symbolic):: - @end menu - - @node Tracebacks From Exception Occurrences (symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback.Symbolic; - - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - procedure P3 is - begin - P2; - end P3; - - begin - P3; - exception - when E : others => - Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ GNAT MAKE -g stb /BINDER_QUALIFIERS -E /LINKER_QUALIFIERS -lgnat -laddr2line -lintl - $ stb - - 0040149F in stb.p1 at STB.ADB:8 - 004014B7 in stb.p2 at STB.ADB:13 - 004014CF in stb.p3 at STB.ADB:18 - 004015DD in ada.stb at STB.ADB:22 - 00401461 in main at B~STB.ADB:168 - 004011C4 in __mingw_CRTStartup at CRT1.C:200 - 004011F1 in mainCRTStartup at CRT1.C:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - The exact sequence of linker options may vary from platform to platform. - The above @code{/LINKER_QUALIFIERS} section is for Windows platforms. By contrast, - under Unix there is no need for the @code{/LINKER_QUALIFIERS} section. - Differences across platforms are due to details of linker implementation. - - @node Tracebacks From Anywhere in a Program (symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is possible to get a symbolic stack traceback - from anywhere in a program, just as for non-symbolic tracebacks. - The first step is to obtain a non-symbolic - traceback, and then call @code{Symbolic_Traceback} to compute the symbolic - information. Here is an example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Traceback.Symbolic; - - procedure STB is - - use Ada; - use GNAT.Traceback; - use GNAT.Traceback.Symbolic; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @node Compatibility with DEC Ada - @chapter Compatibility with DEC Ada - @cindex Compatibility - - @noindent - This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT - OpenVMS Alpha. GNAT achieves a high level of compatibility - with DEC Ada, and it should generally be straightforward to port code - from the DEC Ada environment to GNAT. However, there are a few language - and implementation differences of which the user must be aware. These - differences are discussed in this section. In - addition, the operating environment and command structure for the - compiler are different, and these differences are also discussed. - - Note that this discussion addresses specifically the implementation - of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation - of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, GNAT - always follows the Alpha implementation. - - @menu - * Ada 95 Compatibility:: - * Differences in the Definition of Package System:: - * Language-Related Features:: - * The Package STANDARD:: - * The Package SYSTEM:: - * Tasking and Task-Related Features:: - * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems:: - * Pragmas and Pragma-Related Features:: - * Library of Predefined Units:: - * Bindings:: - * Main Program Definition:: - * Implementation-Defined Attributes:: - * Compiler and Run-Time Interfacing:: - * Program Compilation and Library Management:: - * Input-Output:: - * Implementation Limits:: - * Tools:: - @end menu - - @node Ada 95 Compatibility - @section Ada 95 Compatibility - - @noindent - GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83 - compiler. Ada 95 is almost completely upwards compatible - with Ada 83, and therefore Ada 83 programs will compile - and run under GNAT with - no changes or only minor changes. The Ada 95 Reference - Manual (ANSI/ISO/IEC-8652:1995) provides details on specific - incompatibilities. - - GNAT provides the qualifier /83 on the GNAT COMPILE command, - as well as the pragma ADA_83, to force the compiler to - operate in Ada 83 mode. This mode does not guarantee complete - conformance to Ada 83, but in practice is sufficient to - eliminate most sources of incompatibilities. - In particular, it eliminates the recognition of the - additional Ada 95 keywords, so that their use as identifiers - in Ada83 program is legal, and handles the cases of packages - with optional bodies, and generics that instantiate unconstrained - types without the use of @code{(<>)}. - - @node Differences in the Definition of Package System - @section Differences in the Definition of Package System - - @noindent - Both the Ada 95 and Ada 83 reference manuals permit a compiler to add - implementation-dependent declarations to package System. In normal mode, - GNAT does not take advantage of this permission, and the version of System - provided by GNAT exactly matches that in the Ada 95 Reference Manual. - - However, DEC Ada adds an extensive set of declarations to package System, - as fully documented in the DEC Ada manuals. To minimize changes required - for programs that make use of these extensions, GNAT provides the pragma - Extend_System for extending the definition of package System. By using: - - @smallexample - @group - @cartouche - @b{pragma} Extend_System (Aux_DEC); - @end cartouche - @end group - @end smallexample - - @noindent - The set of definitions in System is extended to include those in package - @code{System.Aux_DEC}. - These definitions are incorporated directly into package - System, as though they had been declared there in the first place. For a - list of the declarations added, see the specification of this package, - which can be found in the file @code{S-AUXDEC.ADS} in the GNAT library. - The pragma Extend_System is a configuration pragma, which means that - it can be placed in the file @file{GNAT.ADC}, so that it will automatically - apply to all subsequent compilations. See the section on Configuration - Pragmas for further details. - - An alternative approach that avoids the use of the non-standard - Extend_System pragma is to add a context clause to the unit that - references these facilities: - - @smallexample - @group - @cartouche - @b{with} System.Aux_DEC; - @b{use} System.Aux_DEC; - @end cartouche - @end group - @end smallexample - - @noindent - The effect is not quite semantically identical to incorporating the declarations - directly into package @code{System}, - but most programs will not notice a difference - unless they use prefix notation (e.g. @code{System.Integer_8}) - to reference the - entities directly in package @code{System}. - For units containing such references, - the prefixes must either be removed, or the pragma @code{Extend_System} - must be used. - - @node Language-Related Features - @section Language-Related Features - - @noindent - The following sections highlight differences in types, - representations of types, operations, alignment, and - related topics. - - @menu - * Integer Types and Representations:: - * Floating-Point Types and Representations:: - * Pragmas Float_Representation and Long_Float:: - * Fixed-Point Types and Representations:: - * Record and Array Component Alignment:: - * Address Clauses:: - * Other Representation Clauses:: - @end menu - - @node Integer Types and Representations - @subsection Integer Types and Representations - - @noindent - The set of predefined integer types is identical in DEC Ada and GNAT. - Furthermore the representation of these integer types is also identical, - including the capability of size clauses forcing biased representation. - - In addition, - DEC Ada for OpenVMS Alpha systems has defined the - following additional integer types in package System: - - @itemize @bullet - - @item - INTEGER_8 - - @item - INTEGER_16 - - @item - INTEGER_32 - - @item - INTEGER_64 - - @item - LARGEST_INTEGER - @end itemize - - @noindent - When using GNAT, the first four of these types may be obtained from the - standard Ada 95 package @code{Interfaces}. - Alternatively, by use of the pragma - @code{Extend_System}, identical - declarations can be referenced directly in package @code{System}. - On both GNAT and DEC Ada, the maximum integer size is 64 bits. - - @node Floating-Point Types and Representations - @subsection Floating-Point Types and Representations - @cindex Floating-Point types - - @noindent - The set of predefined floating-point types is identical in DEC Ada and GNAT. - Furthermore the representation of these floating-point - types is also identical. One important difference is that the default - representation for DEC Ada is VAX_Float, but the default representation - for GNAT is IEEE. - - Specific types may be declared to be VAX_Float or IEEE, using the pragma - @code{Float_Representation} as described in the DEC Ada documentation. - For example, the declarations: - - @smallexample - @group - @cartouche - @b{type} F_Float @b{is digits} 6; - @b{pragma} Float_Representation (VAX_Float, F_Float); - @end cartouche - @end group - @end smallexample - - @noindent - declare a type F_Float that will be represented in VAX_Float format. - This set of declarations actually appears in System.Aux_DEC, which provides - the full set of additional floating-point declarations provided in - the DEC Ada version of package - System. This and similar declarations may be accessed in a user program by using - pragma @code{Extend_System}. The use of this - pragma, and the related pragma @code{Long_Float} is described in further - detail in the following section. - - @node Pragmas Float_Representation and Long_Float - @subsection Pragmas Float_Representation and Long_Float - - @noindent - DEC Ada provides the pragma @code{Float_Representation}, which - acts as a program library qualifier to allow control over - the internal representation chosen for the predefined - floating-point types declared in the package @code{Standard}. - The format of this pragma is as follows: - - @smallexample - @group - @cartouche - @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float); - @end cartouche - @end group - @end smallexample - - @noindent - This pragma controls the representation of floating-point - types as follows: - - @itemize @bullet - @item - @code{VAX_Float} specifies that floating-point - types are represented by default with the VAX hardware types - F-floating, D-floating, G-floating. Note that the H-floating - type is available only on DIGITAL Vax systems, and is not available - in either DEC Ada or GNAT for Alpha systems. - - @item - @code{IEEE_Float} specifies that floating-point - types are represented by default with the IEEE single and - double floating-point types. - @end itemize - - @noindent - GNAT provides an identical implementation of the pragma - @code{Float_Representation}, except that it functions as a - configuration pragma, as defined by Ada 95. Note that the - notion of configuration pragma corresponds closely to the - DEC Ada notion of a program library qualifier. - - When no pragma is used in GNAT, the default is IEEE_Float, which is different - from DEC Ada 83, where the default is VAX_Float. In addition, the - predefined libraries in GNAT are built using IEEE_Float, so it is not - advisable to change the format of numbers passed to standard library - routines, and if necessary explicit type conversions may be needed. - - The use of IEEE_Float is recommended in GNAT since it is more efficient, - and (given that it conforms to an international standard) potentially more - portable. The situation in which VAX_Float may be useful is in interfacing - to existing code and data that expects the use of VAX_Float. There are - two possibilities here. If the requirement for the use of VAX_Float is - localized, then the best approach is to use the predefined VAX_Float - types in package @code{System}, as extended by - @code{Extend_System}. For example, use @code{System.F_Float} - to specify the 32-bit @code{F-Float} format. - - Alternatively, if an entire program depends heavily on the use of - the @code{VAX_Float} and in particular assumes that the types in - package @code{Standard} are in @code{Vax_Float} format, then it - may be desirable to reconfigure GNAT to assume Vax_Float by default. - This is done by using the GNAT LIBRARY command to rebuild the library, and - then using the general form of the @code{Float_Representation} - pragma to ensure that this default format is used throughout. - The form of the GNAT LIBRARY command is: - - @smallexample - GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory} - @end smallexample - - @noindent - where @i{file} contains the new configuration pragmas - and @i{directory} is the directory to be created to contain - the new library. - - @noindent - On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float} - to allow control over the internal representation chosen - for the predefined type @code{Long_Float} and for floating-point - type declarations with digits specified in the range 7 .. 15. - The format of this pragma is as follows: - - @smallexample - @cartouche - @b{pragma} Long_Float (D_FLOAT | G_FLOAT); - @end cartouche - @end smallexample - - @node Fixed-Point Types and Representations - @subsection Fixed-Point Types and Representations - - @noindent - On DEC Ada for OpenVMS Alpha systems, rounding is - away from zero for both positive and negative numbers. - Therefore, +0.5 rounds to 1 and -0.5 rounds to -1. - - On GNAT for OpenVMS Alpha, the results of operations - on fixed-point types are in accordance with the Ada 95 - rules. In particular, results of operations on decimal - fixed-point types are truncated. - - @node Record and Array Component Alignment - @subsection Record and Array Component Alignment - - @noindent - On DEC Ada for OpenVMS Alpha, all non composite components - are aligned on natural boundaries. For example, 1-byte - components are aligned on byte boundaries, 2-byte - components on 2-byte boundaries, 4-byte components on 4-byte - byte boundaries, and so on. The OpenVMS Alpha hardware - runs more efficiently with naturally aligned data. - - ON GNAT for OpenVMS Alpha, alignment rules are compatible - with DEC Ada for OpenVMS Alpha. - - @node Address Clauses - @subsection Address Clauses - - @noindent - In DEC Ada and GNAT, address clauses are supported for - objects and imported subprograms. - The predefined type @code{System.Address} is a private type - in both compilers, with the same representation (it is simply - a machine pointer). Addition, subtraction, and comparison - operations are available in the standard Ada 95 package - @code{System.Storage_Elements}, or in package @code{System} - if it is extended to include @code{System.Aux_DEC} using a - pragma @code{Extend_System} as previously described. - - Note that code that with's both this extended package @code{System} - and the package @code{System.Storage_Elements} should not @code{use} - both packages, or ambiguities will result. In general it is better - not to mix these two sets of facilities. The Ada 95 package was - designed specifically to provide the kind of features that DEC Ada - adds directly to package @code{System}. - - GNAT is compatible with DEC Ada in its handling of address - clauses, except for some limitations in - the form of address clauses for composite objects with - initialization. Such address clauses are easily replaced - by the use of an explicitly-defined constant as described - in the Ada 95 Reference Manual (13.1(22)). For example, the sequence - of declarations: - - @smallexample - @group - @cartouche - X, Y : Integer := Init_Func; - Q : String (X .. Y) := "abc"; - ... - @b{for} Q'Address @b{use} Compute_Address; - @end cartouche - @end group - @end smallexample - - @noindent - will be rejected by GNAT, since the address cannot be computed at the time - that Q is declared. To achieve the intended effect, write instead: - - @smallexample - @group - @cartouche - X, Y : Integer := Init_Func; - Q_Address : @b{constant} Address := Compute_Address; - Q : String (X .. Y) := "abc"; - ... - @b{for} Q'Address @b{use} Q_Address; - @end cartouche - @end group - @end smallexample - - @noindent - which will be accepted by GNAT (and other Ada 95 compilers), and is also - backwards compatible with Ada 83. A fuller description of the restrictions - on address specifications is found in the GNAT Reference Manual. - - @node Other Representation Clauses - @subsection Other Representation Clauses - - @noindent - GNAT supports in a compatible manner all the representation - clauses supported by DEC Ada. In addition, it - supports representation clause forms that are new in Ada 95 - including COMPONENT_SIZE and SIZE clauses for objects. - - @node The Package STANDARD - @section The Package STANDARD - - @noindent - The package STANDARD, as implemented by DEC Ada, is fully - described in the Reference Manual for the Ada Programming - Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada - Language Reference Manual. As implemented by GNAT, the - package STANDARD is described in the Ada 95 Reference - Manual. - - In addition, DEC Ada supports the Latin-1 character set in - the type CHARACTER. GNAT supports the Latin-1 character set - in the type CHARACTER and also Unicode (ISO 10646 BMP) in - the type WIDE_CHARACTER. - - The floating-point types supported by GNAT are those - supported by DEC Ada, but defaults are different, and are controlled by - pragmas. See @pxref{Floating-Point Types and Representations} for details. - - @node The Package SYSTEM - @section The Package SYSTEM - - @noindent - DEC Ada provides a system-specific version of the package - SYSTEM for each platform on which the language ships. - For the complete specification of the package SYSTEM, see - Appendix F of the DEC Ada Language Reference Manual. - - On DEC Ada, the package SYSTEM includes the following conversion functions: - @itemize @bullet - @item TO_ADDRESS(INTEGER) - - @item TO_ADDRESS(UNSIGNED_LONGWORD) - - @item TO_ADDRESS(universal_integer) - - @item TO_INTEGER(ADDRESS) - - @item TO_UNSIGNED_LONGWORD(ADDRESS) - - @item Function IMPORT_VALUE return UNSIGNED_LONGWORD and the - functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE - @end itemize - - @noindent - By default, GNAT supplies a version of SYSTEM that matches - the definition given in the Ada 95 Reference Manual. - This - is a subset of the DIGITAL system definitions, which is as - close as possible to the original definitions. The only difference - is that the definition of SYSTEM_NAME is different: - - @smallexample - @group - @cartouche - @b{type} Name @b{is} (SYSTEM_NAME_GNAT); - System_Name : @b{constant} Name := SYSTEM_NAME_GNAT; - @end cartouche - @end group - @end smallexample - - @noindent - Also, GNAT adds the new Ada 95 declarations for - BIT_ORDER and DEFAULT_BIT_ORDER. - - However, the use of the following pragma causes GNAT - to extend the definition of package SYSTEM so that it - encompasses the full set of DIGITAL-specific extensions, - including the functions listed above: - - @smallexample - @cartouche - @b{pragma} Extend_System (Aux_DEC); - @end cartouche - @end smallexample - - @noindent - The pragma Extend_System is a configuration pragma that - is most conveniently placed in the @file{GNAT.ADC} file. See the - GNAT Reference Manual for further details. - - DEC Ada does not allow the recompilation of the package - SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_ - NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in - the package SYSTEM. On OpenVMS Alpha systems, the pragma - SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as - its single argument. - - GNAT does permit the recompilation of package SYSTEM using - a special qualifier (/STYLE=GNAT) and this qualifier can be used if - it is necessary to change constants in SYSTEM. GNAT does - not permit the specification of SYSTEM_NAME, STORAGE_UNIT - or MEMORY_SIZE by any other means. - - On GNAT systems, the pragma SYSTEM_NAME takes the - enumeration literal SYSTEM_NAME_GNAT. - - The definitions provided by the use of - - @smallexample - pragma Extend_System (AUX_Dec); - @end smallexample - - @noindent - are virtually identical to those provided by the DEC Ada 83 package - System. One important difference is that the name of the TO_ADDRESS - function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG. - See the GNAT Reference manual for a discussion of why this change was - necessary. - - @noindent - The version of TO_ADDRESS taking a universal integer argument is in fact - an extension to Ada 83 not strictly compatible with the reference manual. - In GNAT, we are constrained to be exactly compatible with the standard, - and this means we cannot provide this capability. In DEC Ada 83, the - point of this definition is to deal with a call like: - - @smallexample - TO_ADDRESS (16#12777#); - @end smallexample - - @noindent - Normally, according to the Ada 83 standard, one would expect this to be - ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms - of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the - definition using universal_integer takes precedence. - - In GNAT, since the version with universal_integer cannot be supplied, it is - not possible to be 100% compatible. Since there are many programs using - numeric constants for the argument to TO_ADDRESS, the decision in GNAT was - to change the name of the function in the UNSIGNED_LONGWORD case, so the - declarations provided in the GNAT version of AUX_Dec are: - - @smallexample - function To_Address (X : Integer) return Address; - pragma Pure_Function (To_Address); - - function To_Address_Long (X : Unsigned_Longword) return Address; - pragma Pure_Function (To_Address_Long); - @end smallexample - - @noindent - This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must - change the name to TO_ADDRESS_LONG. - - @node Tasking and Task-Related Features - @section Tasking and Task-Related Features - - @noindent - The concepts relevant to a comparison of tasking on GNAT - and on DEC Ada for OpenVMS Alpha systems are discussed in - the following sections. - - For detailed information on concepts related to tasking in - DEC Ada, see the DEC Ada Language Reference Manual and the - relevant run-time reference manual. - - @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems - @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems - - @noindent - On OpenVMS Alpha systems, each Ada task (except a passive - task) is implemented as a single stream of execution - that is created and managed by the kernel. On these - systems, DEC Ada tasking support is based on DECthreads, - an implementation of the POSIX standard for threads. - - Although tasks are implemented as threads, all tasks in - an Ada program are part of the same process. As a result, - resources such as open files and virtual memory can be - shared easily among tasks. Having all tasks in one process - allows better integration with the programming environment - (the shell and the debugger, for example). - - Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign - code that calls DECthreads routines can be used together. - The interaction between Ada tasks and DECthreads routines - can have some benefits. For example when on OpenVMS Alpha, - DEC Ada can call C code that is already threaded. - GNAT on OpenVMS Alpha uses the facilities of DECthreads, - and Ada tasks are mapped to threads. - - @menu - * Assigning Task IDs:: - * Task IDs and Delays:: - * Task-Related Pragmas:: - * Scheduling and Task Priority:: - * The Task Stack:: - * External Interrupts:: - @end menu - - @node Assigning Task IDs - @subsection Assigning Task IDs - - @noindent - The DEC Ada Run-Time Library always assigns %TASK 1 to - the environment task that executes the main program. On - OpenVMS Alpha systems, %TASK 0 is often used for tasks - that have been created but are not yet activated. - - On OpenVMS Alpha systems, task IDs are assigned at - activation. On GNAT systems, task IDs are also assigned at - task creation but do not have the same form or values as - task ID values in DEC Ada. There is no null task, and the - environment task does not have a specific task ID value. - - @node Task IDs and Delays - @subsection Task IDs and Delays - - @noindent - On OpenVMS Alpha systems, tasking delays are implemented - using Timer System Services. The Task ID is used for the - identification of the timer request (the REQIDT parameter). - If Timers are used in the application take care not to use - 0 for the identification, because cancelling such a timer - will cancel all timers and may lead to unpredictable results. - - @node Task-Related Pragmas - @subsection Task-Related Pragmas - - @noindent - Ada supplies the pragma TASK_STORAGE, which allows - specification of the size of the guard area for a task - stack. (The guard area forms an area of memory that has no - read or write access and thus helps in the detection of - stack overflow.) On OpenVMS Alpha systems, if the pragma - TASK_STORAGE specifies a value of zero, a minimal guard - area is created. In the absence of a pragma TASK_STORAGE, a default guard - area is created. - - GNAT supplies the following task-related pragmas: - - @itemize @bullet - @item TASK_INFO - - This pragma appears within a task definition and - applies to the task in which it appears. The argument - must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE. - - @item TASK_STORAGE - - GNAT implements pragma TASK_STORAGE in the same way as - DEC Ada. - Both DEC Ada and GNAT supply the pragmas PASSIVE, - SUPPRESS, and VOLATILE. - @end itemize - @node Scheduling and Task Priority - @subsection Scheduling and Task Priority - - @noindent - DEC Ada implements the Ada language requirement that - when two tasks are eligible for execution and they have - different priorities, the lower priority task does not - execute while the higher priority task is waiting. The DEC - Ada Run-Time Library keeps a task running until either the - task is suspended or a higher priority task becomes ready. - - On OpenVMS Alpha systems, the default strategy is round- - robin with preemption. Tasks of equal priority take turns - at the processor. A task is run for a certain period of - time and then placed at the rear of the ready queue for - its priority level. - - DEC Ada provides the implementation-defined pragma TIME_SLICE, - which can be used to enable or disable round-robin - scheduling of tasks with the same priority. - See the relevant DEC Ada run-time reference manual for - information on using the pragmas to control DEC Ada task - scheduling. - - GNAT follows the scheduling rules of Annex D (real-time - Annex) of the Ada 95 Reference Manual. In general, this - scheduling strategy is fully compatible with DEC Ada - although it provides some additional constraints (as - fully documented in Annex D). - GNAT implements time slicing control in a manner compatible with - DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical - to the DEC Ada 83 pragma of the same name. - Note that it is not possible to mix GNAT tasking and - DEC Ada 83 tasking in the same program, since the two run times are - not compatible. - - @node The Task Stack - @subsection The Task Stack - - @noindent - In DEC Ada, a task stack is allocated each time a - non passive task is activated. As soon as the task is - terminated, the storage for the task stack is deallocated. - If you specify a size of zero (bytes) with T'STORAGE_SIZE, - a default stack size is used. Also, regardless of the size - specified, some additional space is allocated for task - management purposes. On OpenVMS Alpha systems, at least - one page is allocated. - - GNAT handles task stacks in a similar manner. According to - the Ada 95 rules, it provides the pragma STORAGE_SIZE as - an alternative method for controlling the task stack size. - The specification of the attribute T'STORAGE_SIZE is also - supported in a manner compatible with DEC Ada. - - @node External Interrupts - @subsection External Interrupts - - @noindent - On DEC Ada, external interrupts can be associated with task entries. - GNAT is compatible with DEC Ada in its handling of external interrupts. - - @node Pragmas and Pragma-Related Features - @section Pragmas and Pragma-Related Features - - @noindent - Both DEC Ada and GNAT supply all language-defined pragmas - as specified by the Ada 83 standard. GNAT also supplies all - language-defined pragmas specified in the Ada 95 Reference Manual. - In addition, GNAT implements the implementation-defined pragmas - from DEC Ada 83. - - @itemize @bullet - @item AST_ENTRY - - @item COMMON_OBJECT - - @item COMPONENT_ALIGNMENT - - @item EXPORT_EXCEPTION - - @item EXPORT_FUNCTION - - @item EXPORT_OBJECT - - @item EXPORT_PROCEDURE - - @item EXPORT_VALUED_PROCEDURE - - @item FLOAT_REPRESENTATION - - @item IDENT - - @item IMPORT_EXCEPTION - - @item IMPORT_FUNCTION - - @item IMPORT_OBJECT - - @item IMPORT_PROCEDURE - - @item IMPORT_VALUED_PROCEDURE - - @item INLINE_GENERIC - - @item INTERFACE_NAME - - @item LONG_FLOAT - - @item MAIN_STORAGE - - @item PASSIVE - - @item PSET_OBJECT - - @item SHARE_GENERIC - - @item SUPPRESS_ALL - - @item TASK_STORAGE - - @item TIME_SLICE - - @item TITLE - @end itemize - - @noindent - These pragmas are all fully implemented, with the exception of @code{Title}, - @code{Passive}, and @code{Share_Generic}, which are - recognized, but which have no - effect in GNAT. The effect of @code{Passive} may be obtained by the - use of protected objects in Ada 95. In GNAT, all generics are inlined. - - Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require - a separate subprogram specification which must appear before the - subprogram body. - - GNAT also supplies a number of implementation-defined pragmas as follows: - @itemize @bullet - @item C_PASS_BY_COPY - - @item EXTEND_SYSTEM - - @item SOURCE_FILE_NAME - - @item UNSUPPRESS - - @item WARNINGS - - @item ABORT_DEFER - - @item ADA_83 - - @item ADA_95 - - @item ANNOTATE - - @item ASSERT - - @item CPP_CLASS - - @item CPP_CONSTRUCTOR - - @item CPP_DESTRUCTOR - - @item CPP_VIRTUAL - - @item CP_VTABLE - - @item DEBUG - - @item LINKER_ALIAS - - @item LINKER_SECTION - - @item MACHINE_ATTRIBUTE - - @item NO_RETURN - - @item PURE_FUNCTION - - @item SOURCE_REFERENCE - - @item TASK_INFO - - @item UNCHECKED_UNION - - @item UNIMPLEMENTED_UNIT - - @item WEAK_EXTERNAL - @end itemize - - @noindent - For full details on these GNAT implementation-defined pragmas, see - the GNAT Reference Manual. - - @menu - * Restrictions on the Pragma INLINE:: - * Restrictions on the Pragma INTERFACE:: - * Restrictions on the Pragma SYSTEM_NAME:: - @end menu - - @node Restrictions on the Pragma INLINE - @subsection Restrictions on the Pragma INLINE - - @noindent - DEC Ada applies the following restrictions to the pragma INLINE: - @itemize @bullet - @item Parameters cannot be a task type. - - @item Function results cannot be task types, unconstrained - array types, or unconstrained types with discriminants. - - @item Bodies cannot declare the following: - @itemize @bullet - @item Subprogram body or stub (imported subprogram is allowed) - - @item Tasks - - @item Generic declarations - - @item Instantiations - - @item Exceptions - - @item Access types (types derived from access types allowed) - - @item Array or record types - - @item Dependent tasks - - @item Direct recursive calls of subprogram or containing - subprogram, directly or via a renaming - - @end itemize - @end itemize - - @noindent - In GNAT, the only restriction on pragma INLINE is that the - body must occur before the call if both are in the same - unit, and the size must be appropriately small. There are - no other specific restrictions which cause subprograms to - be incapable of being inlined. - - @node Restrictions on the Pragma INTERFACE - @subsection Restrictions on the Pragma INTERFACE - - @noindent - The following lists and describes the restrictions on the - pragma INTERFACE on DEC Ada and GNAT: - @itemize @bullet - @item Languages accepted: Ada, Bliss, C, Fortran, Default. - Default is the default on OpenVMS Alpha systems. - - @item Parameter passing: Language specifies default - mechanisms but can be overridden with an EXPORT pragma. - - @itemize @bullet - @item Ada: Use internal Ada rules. - - @item Bliss, C: Parameters must be mode @code{in}; cannot be - record or task type. Result cannot be a string, an - array, or a record. - - @item Fortran: Parameters cannot be a task. Result cannot - be a string, an array, or a record. - @end itemize - @end itemize - - @noindent - GNAT is entirely upwards compatible with DEC Ada, and in addition allows - record parameters for all languages. - - @node Restrictions on the Pragma SYSTEM_NAME - @subsection Restrictions on the Pragma SYSTEM_NAME - - @noindent - For DEC Ada for OpenVMS Alpha, the enumeration literal - for the type NAME is OPENVMS_AXP. In GNAT, the enumeration - literal for the type NAME is SYSTEM_NAME_GNAT. - - @node Library of Predefined Units - @section Library of Predefined Units - - @noindent - A library of predefined units is provided as part of the - DEC Ada and GNAT implementations. DEC Ada does not provide - the package MACHINE_CODE but instead recommends importing - assembler code. - - The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:) - units are taken from the OpenVMS Alpha version, not the OpenVMS VAX - version. During GNAT installation, the DEC Ada Predefined - Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] - (aka DECLIB) directory and patched to remove Ada 95 incompatibilities - and to make them interoperable with GNAT, @pxref{Changes to DECLIB} - for details. - - The GNAT RTL is contained in - the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and - the default search path is set up to find DECLIB units in preference - to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO, - for example). - - However, it is possible to change the default so that the - reverse is true, or even to mix them using child package - notation. The DEC Ada 83 units are available as DEC.xxx where xxx - is the package name, and the Ada units are available in the - standard manner defined for Ada 95, that is to say as Ada.xxx. To - change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH - appropriately. For example, to change the default to use the Ada95 - versions do: - - @smallexample - $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],- - GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB] - $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],- - GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB] - @end smallexample - - @menu - * Changes to DECLIB:: - @end menu - - @node Changes to DECLIB - @subsection Changes to DECLIB - - @noindent - The changes made to the DEC Ada predefined library for GNAT and Ada 95 - compatibility are minor and include the following: - - @itemize @bullet - @item Adjusting the location of pragmas and record representation - clauses to obey Ada 95 rules - - @item Adding the proper notation to generic formal parameters - that take unconstrained types in instantiation - - @item Adding pragma ELABORATE_BODY to package specifications - that have package bodies not otherwise allowed - - @item Occurrences of the identifier "PROTECTED" are renamed to "PROTECTD". - Currently these are found only in the STARLET package spec. - @end itemize - - @noindent - None of the above changes is visible to users. - - @node Bindings - @section Bindings - - @noindent - On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings: - @itemize @bullet - - @item Command Language Interpreter (CLI interface) - - @item DECtalk Run-Time Library (DTK interface) - - @item Librarian utility routines (LBR interface) - - @item General Purpose Run-Time Library (LIB interface) - - @item Math Run-Time Library (MTH interface) - - @item National Character Set Run-Time Library (NCS interface) - - @item Compiled Code Support Run-Time Library (OTS interface) - - @item Parallel Processing Run-Time Library (PPL interface) - - @item Screen Management Run-Time Library (SMG interface) - - @item Sort Run-Time Library (SOR interface) - - @item String Run-Time Library (STR interface) - - @item STARLET System Library - @findex Starlet - - @item X Window System Version 11R4 and 11R5 (X, XLIB interface) - - @item X Windows Toolkit (XT interface) - - @item X/Motif Version 1.1.3 and 1.2 (XM interface) - @end itemize - - @noindent - GNAT provides implementations of these DEC bindings in the DECLIB directory. - - The X/Motif bindings used to build DECLIB are whatever versions are in the - DEC Ada ADA$PREDEFINED directory with extension .ADC. The build script will - automatically add a pragma Linker_Options to packages Xm, Xt, and X_Lib - causing the default X/Motif shareable image libraries to be linked in. This - is done via options files named xm.opt, xt.opt, and x_lib.opt (also located - in the DECLIB directory). - - It may be necessary to edit these options files to update or correct the - library names if, for example, the newer X/Motif bindings from ADA$EXAMPLES - had been (previous to installing GNAT) copied and renamed to superseded the - default ADA$PREDEFINED versions. - - @menu - * Shared Libraries and Options Files:: - * Interfaces to C:: - @end menu - - @node Shared Libraries and Options Files - @subsection Shared Libraries and Options Files - - @noindent - When using the DEC Ada - predefined X and Motif bindings, the linking with their shareable images is - done automatically by GNAT LINK. When using other X and Motif bindings, it - is necessary to add the corresponding shareable images to the command line for - GNAT LINK. When linking with shared libraries, or with .OPT files, it is - also necessary to add them to the command line for GNAT LINK. - - A shared library to be used with GNAT is built in the same way as other - libraries under VMS. The VMS Link command can be used in standard fashion. - - @node Interfaces to C - @subsection Interfaces to C - - @noindent - DEC Ada - provides the following Ada types and operations: - - @itemize @bullet - @item C types package (C_TYPES) - - @item C strings (C_TYPES.NULL_TERMINATED) - - @item Other_types (SHORT_INT) - @end itemize - - @noindent - Interfacing to C with GNAT, one can use the above approach - described for DEC Ada or the facilities of Annex B of - the Ada 95 Reference Manual (packages INTERFACES.C, - INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more - information, see the section "Interfacing to C" in the - GNAT Reference Manual. - - The @option{/UPPERCASE_EXTERNALS} qualifier forces default and explicit - @code{External_Name} parameters in pragmas Import and Export - to be uppercased for compatibility with the default behavior - of DEC C. The qualifier has no effect on @code{Link_Name} parameters. - - @node Main Program Definition - @section Main Program Definition - - @noindent - The following section discusses differences in the - definition of main programs on DEC Ada and GNAT. - On DEC Ada, main programs are defined to meet the - following conditions: - @itemize @bullet - @item Procedure with no formal parameters (returns 0 upon - normal completion) - - @item Procedure with no formal parameters (returns 42 when - unhandled exceptions are raised) - - @item Function with no formal parameters whose returned value - is of a discrete type - - @item Procedure with one OUT formal of a discrete type for - which a specification of pragma EXPORT_VALUED_PROCEDURE is given. - - @end itemize - - @noindent - When declared with the pragma EXPORT_VALUED_PROCEDURE, - a main function or main procedure returns a discrete - value whose size is less than 64 bits (32 on VAX systems), - the value is zero- or sign-extended as appropriate. - On GNAT, main programs are defined as follows: - @itemize @bullet - @item Must be a non-generic, parameter-less subprogram that - is either a procedure or function returning an Ada - STANDARD.INTEGER (the predefined type) - - @item Cannot be a generic subprogram or an instantiation of a - generic subprogram - @end itemize - - @node Implementation-Defined Attributes - @section Implementation-Defined Attributes - - @noindent - GNAT provides all DEC Ada implementation-defined - attributes. - - @node Compiler and Run-Time Interfacing - @section Compiler and Run-Time Interfacing - - @noindent - DEC Ada provides the following ways to pass options to the linker (ACS LINK): - @itemize @bullet - @item /WAIT and /SUBMIT qualifiers - - @item /COMMAND qualifier - - @item /[NO]MAP qualifier - - @item /OUTPUT=file-spec - - @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers - @end itemize - - @noindent - To pass options to the linker, GNAT provides the following - qualifiers: - - @itemize @bullet - @item /EXECUTABLE=exec-name - - @item /VERBOSE qualifier - - @item /[NO]DEBUG and /[NO]TRACEBACK qualifiers - @end itemize - - @noindent - For more information on these qualifiers, see the section - "Qualifiers for GNAT LINK" in the corresponding section of this Guide. - In DEC Ada, the command-line qualifier /OPTIMIZE is available - to control optimization. DEC Ada also supplies the - following pragmas: - @itemize @bullet - @item OPTIMIZE - - @item INLINE - - @item INLINE_GENERIC - - @item SUPPRESS_ALL - - @item PASSIVE - @end itemize - - @noindent - In GNAT, optimization is controlled strictly by command - line parameters, as described in the corresponding section of this guide. - The DIGITAL pragmas for control of optimization are - recognized but ignored. - - Note that in GNAT, the default is optimization off, whereas in DEC Ada 83, - the default is that optimization is turned on. - - @node Program Compilation and Library Management - @section Program Compilation and Library Management - - @noindent - DEC Ada and GNAT provide a comparable set of commands to - build programs. DEC Ada also provides a program library, - which is a concept that does not exist on GNAT. Instead, - GNAT provides directories of sources that are compiled as - needed. - - The following table summarizes - the DEC Ada commands and provides - equivalent GNAT commands. In this table, some GNAT - equivalents reflect the fact that GNAT does not use the - concept of a program library. Instead, it uses a model - in which collections of source and object files are used - in a manner consistent with other languages like C and - Fortran. Therefore, standard system file commands are used - to manipulate these elements. Those GNAT commands are marked with - an asterisk in the table that follows. - Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards. - - @need 1500 - @multitable @columnfractions .31 .30 .39 - - @item @strong{DEC_Ada_Command} - @tab @strong{GNAT_Equivalent} - @tab @strong{Description} - - @item ADA - @tab GNAT COMPILE - @tab Invokes the compiler to compile one or more Ada source files. - - @item ACS ATTACH - @tab No equivalent - @tab Qualifiers control of terminal from current process running the program - library manager. - - @item ACS CHECK - @tab GNAT MAKE /DEPENDENCY_LIST - @tab Forms the execution closure of one - or more compiled units and checks completeness and currency. - - @item ACS COMPILE - @tab GNAT MAKE /ACTIONS=COMPILE - @tab Forms the execution closure of one or - more specified units, checks completeness and currency, - identifies units that have revised source files, compiles same, - and recompiles units that are or will become obsolete. - Also completes incomplete generic instantiations. - - @item ACS COPY FOREIGN - @tab Copy (*) - @tab Copies a foreign object file into the program library as a - library unit body. - - @item ACS COPY UNIT - @tab Copy (*) - @tab Copies a compiled unit from one program library to another. - - @item ACS CREATE LIBRARY - @tab Create /directory (*) - @tab Creates a program library. - - @item ACS CREATE SUBLIBRARY - @tab Create /directory (*) - @tab Creates a program sublibrary. - - @item ACS DELETE LIBRARY - @tab - @tab Deletes a program library and its contents. - - @item ACS DELETE SUBLIBRARY - @tab - @tab Deletes a program sublibrary and its contents. - - @item ACS DELETE UNIT - @tab Delete @i{file} (*) - @tab On OpenVMS systems, deletes one or more compiled units from - the current program library. - - @item ACS DIRECTORY - @tab Directory (*) - @tab On OpenVMS systems, lists units contained in the current - program library. - - @item ACS ENTER FOREIGN - @tab Copy (*) - @tab Allows the import of a foreign body as an Ada library - specification and enters a reference to a pointer. - - @item ACS ENTER UNIT - @tab Copy (*) - @tab Enters a reference (pointer) from the current program library to - a unit compiled into another program library. - - @item ACS EXIT - @tab No equivalent - @tab Exits from the program library manager. - - @item ACS EXPORT - @tab Copy (*) - @tab Creates an object file that contains system-specific object code - for one or more units. With GNAT, object files can simply be copied - into the desired directory. - - @item ACS EXTRACT SOURCE - @tab Copy (*) - @tab Allows access to the copied source file for each Ada compilation unit - - @item ACS HELP - @tab HELP GNAT - @tab Provides online help. - - @item ACS LINK - @tab GNAT LINK - @tab Links an object file containing Ada units into an executable - file. - - @item ACS LOAD - @tab Copy (*) - @tab Loads (partially compiles) Ada units into the program library. - Allows loading a program from a collection of files into a library - without knowing the relationship among units. - - @item ACS MERGE - @tab Copy (*) - @tab Merges into the current program library, one or more units from - another library where they were modified. - - @item ACS RECOMPILE - @tab GNAT MAKE /ACTIONS=COMPILE - @tab Recompiles from external or copied source files any obsolete - unit in the closure. Also, completes any incomplete generic - instantiations. - - @item ACS REENTER - @tab GNAT MAKE - @tab Reenters current references to units compiled after last entered - with the ACS ENTER UNIT command. - - @item ACS SET LIBRARY - @tab Set default (*) - @tab Defines a program library to be the compilation context as well - as the target library for compiler output and commands in general. - - @item ACS SET PRAGMA - @tab Edit GNAT.ADC (*) - @tab Redefines specified values of the library characteristics - LONG_ FLOAT, MEMORY_SIZE, SYSTEM_NAME, and @code{Float_Representation}. - - @item ACS SET SOURCE - @tab define @* ADA_INCLUDE_PATH @i{path} (*) - @tab Defines the source file search list for the ACS COMPILE command. - - @item ACS SHOW LIBRARY - @tab Directory (*) - @tab Lists information about one or more program libraries. - - @item ACS SHOW PROGRAM - @tab No equivalent - @tab Lists information about the execution closure of one or - more units in the program library. - - @item ACS SHOW SOURCE - @tab Show logical @* ADA_INCLUDE_PATH - @tab Shows the source file search used when compiling units. - - @item ACS SHOW VERSION - @tab Compile with VERBOSE option - @tab Displays the version number of the compiler and program library - manager used. - - @item ACS SPAWN - @tab No equivalent - @tab Creates a subprocess of the current process (same as DCL SPAWN - command). - - @item ACS VERIFY - @tab No equivalent - @tab Performs a series of consistency checks on a program library to - determine whether the library structure and library files are in - valid_form. - - @end multitable - - @noindent - - @node Input-Output - @section Input-Output - - @noindent - On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record - Management Services (RMS) to perform operations on - external files. - - @noindent - DEC Ada and GNAT predefine an identical set of input- - output packages. To make the use of the - generic TEXT_IO operations more convenient, DEC Ada - provides predefined library packages that instantiate the - integer and floating-point operations for the predefined - integer and floating-point types as shown in the following table. - - @table @code - - @item Package_Name - Instantiation - - @item INTEGER_TEXT_IO - INTEGER_IO(INTEGER) - - @item SHORT_INTEGER_TEXT_IO - INTEGER_IO(SHORT_INTEGER) - - @item SHORT_SHORT_INTEGER_TEXT_IO - INTEGER_IO(SHORT_SHORT_ INTEGER) - - @item FLOAT_TEXT_IO - FLOAT_IO(FLOAT) - - @item LONG_FLOAT_TEXT_IO - FLOAT_IO(LONG_FLOAT) - @end table - - @noindent - The DEC Ada predefined packages and their operations - are implemented using OpenVMS Alpha files and input- - output facilities. DEC Ada supports asynchronous input- - output on OpenVMS Alpha. Familiarity with the following is - recommended: - @itemize @bullet - @item RMS file organizations and access methods - - @item OpenVMS file specifications and directories - - @item OpenVMS File Definition Language (FDL) - @end itemize - - @noindent - GNAT provides I/O facilities that are completely - compatible with DEC Ada. The distribution includes the - standard DEC Ada versions of all I/O packages, operating - in a manner compatible with DEC Ada. In particular, the - following packages are by default the DEC Ada (Ada 83) - versions of these packages rather than the renamings - suggested in annex J of the Ada 95 Reference Manual: - @itemize @bullet - @item TEXT_IO - - @item SEQUENTIAL_IO - - @item DIRECT_IO - @end itemize - - @noindent - The use of the standard Ada 95 syntax for child packages (for - example, ADA.TEXT_IO) retrieves the Ada 95 versions of these - packages, as defined in the Ada 95 Reference Manual. - GNAT provides DIGITAL-compatible predefined instantiations - of the TEXT_IO packages, and also - provides the standard predefined instantiations required - by the Ada 95 Reference Manual. - - For further information on how GNAT interfaces to the file - system or how I/O is implemented in programs written in - mixed languages, see the chapter "Implementation of the - Standard I/O" in the GNAT Reference Manual. - This chapter covers the following: - @itemize @bullet - @item Standard I/O packages - - @item FORM strings - - @item DIRECT_IO - - @item SEQUENTIAL_IO - - @item TEXT_IO - - @item Stream pointer positioning - - @item Reading and writing non-regular files - - @item GET_IMMEDIATE - - @item Treating TEXT_IO files as streams - - @item Shared files - - @item Open modes - @end itemize - - @node Implementation Limits - @section Implementation Limits - - @noindent - The following table lists implementation limits for DEC Ada and GNAT systems. - @multitable @columnfractions .60 .20 .20 - @item Compilation Parameter - @tab DEC Ada - @tab GNAT - - @item In a subprogram or entry declaration, maximum number of - formal parameters that are of an unconstrained record type - @tab 32 - @tab No set limit - - @item Maximum identifier length (number of characters) - @tab 255 - @tab 255 - - @item Maximum number of characters in a source line - @tab 255 - @tab 255 - - @item Maximum collection size (number of bytes) - @tab 2**31-1 - @tab 2**31-1 - - @item Maximum number of discriminants for a record type - @tab 245 - @tab No set limit - - @item Maximum number of formal parameters in an entry or - subprogram declaration - @tab 246 - @tab No set limit - - @item Maximum number of dimensions in an array type - @tab 255 - @tab No set limit - - @item Maximum number of library units and subunits in a compilation. - @tab 4095 - @tab No set limit - - @item Maximum number of library units and subunits in an execution. - @tab 16383 - @tab No set limit - - @item Maximum number of objects declared with the pragma COMMON_OBJECT - or PSECT_OBJECT - @tab 32757 - @tab No set limit - - @item Maximum number of enumeration literals in an enumeration type - definition - @tab 65535 - @tab No set limit - - @item Maximum number of lines in a source file - @tab 65534 - @tab No set limit - - @item Maximum number of bits in any object - @tab 2**31-1 - @tab 2**31-1 - - @item Maximum size of the static portion of a stack frame (approximate) - @tab 2**31-1 - @tab 2**31-1 - @end multitable - - @node Tools - @section Tools - - - @node Inline Assembler - @chapter Inline Assembler - - @noindent - If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program. First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT. However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the GNAT COMPILE Inline Assembler. The Inline Assembler approach offers a number of advantages, including the following: - - @itemize @bullet - @item No need to use non-Ada tools - @item Consistent interface over different targets - @item Automatic usage of the proper calling conventions - @item Access to Ada constants and variables - @item Definition of intrinsic routines - @item Possibility of inlining a subprogram comprising assembler code - @item Code optimizer can take Inline Assembler code into account - @end itemize - - This chapter presents a series of examples to show you how to use the Inline Assembler. Although it focuses on the Intel x86, the general approach applies also to other processors. It is assumed that you are familiar with Ada and with assembly language programming. - - @menu - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - @end menu - - @c --------------------------------------------------------------------------- - @node Basic Assembler Syntax - @section Basic Assembler Syntax - - @noindent - The assembler used by GNAT and GNAT COMPILE is based not on the Intel assembly language, but rather on a - language that descends from the AT&T Unix assembler @emph{as} (and which is often - referred to as ``AT&T syntax''). - The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions. - See the GNAT COMPILE @emph{as} and @emph{gas} (an @emph{as} macro - pre-processor) documentation for further information. - - @table @asis - @item Register names - GNAT COMPILE / @emph{as}: Prefix with ``%''; for example @code{%eax} - @* - Intel: No extra punctuation; for example @code{eax} - - @item Immediate operand - GNAT COMPILE / @emph{as}: Prefix with ``$''; for example @code{$4} - @* - Intel: No extra punctuation; for example @code{4} - - @item Address - GNAT COMPILE / @emph{as}: Prefix with ``$''; for example @code{$loc} - @* - Intel: No extra punctuation; for example @code{loc} - - @item Memory contents - GNAT COMPILE / @emph{as}: No extra punctuation; for example @code{loc} - @* - Intel: Square brackets; for example @code{[loc]} - - @item Register contents - GNAT COMPILE / @emph{as}: Parentheses; for example @code{(%eax)} - @* - Intel: Square brackets; for example @code{[eax]} - - @item Hexadecimal numbers - GNAT COMPILE / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} - @* - Intel: Trailing ``h''; for example @code{A0h} - - @item Operand size - GNAT COMPILE / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word - @* - Intel: Implicit, deduced by assembler; for example @code{mov} - - @item Instruction repetition - GNAT COMPILE / @emph{as}: Split into two lines; for example - @* - @code{rep} - @* - @code{stosl} - @* - Intel: Keep on one line; for example @code{rep stosl} - - @item Order of operands - GNAT COMPILE / @emph{as}: Source first; for example @code{movw $4, %eax} - @* - Intel: Destination first; for example @code{mov eax, 4} - @end table - - @c --------------------------------------------------------------------------- - @node A Simple Example of Inline Assembler - @section A Simple Example of Inline Assembler - - @noindent - The following example will generate a single assembly language statement, @code{nop}, which does nothing. Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility. - - @smallexample - @group - with System.Machine_Code; use System.Machine_Code; - procedure Nothing is - begin - Asm ("nop"); - end Nothing; - @end group - @end smallexample - - @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction. - @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions. - - The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}. - - Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{NOTHING.ADB}. You can build the executable in the usual way: - @smallexample - GNAT MAKE nothing - @end smallexample - However, the interesting aspect of this example is not its run-time behavior but rather the - generated assembly code. To see this output, invoke the compiler as follows: - @smallexample - GNAT COMPILE -S -fomit-frame-pointer /CHECKS=SUPPRESS_ALL @file{NOTHING.ADB} - @end smallexample - where the options are: - - @table @code - @item -c - compile only (no bind or link) - @item -S - generate assembler listing - @item -fomit-frame-pointer - do not set up separate stack frames - @item /CHECKS=SUPPRESS_ALL - do not add runtime checks - @end table - - This gives a human-readable assembler version of the code. The resulting - file will have the same name as the Ada source file, but with a @code{.s} extension. - In our example, the file @file{nothing.s} has the following contents: - - @smallexample - @group - .file "NOTHING.ADB" - gcc2_compiled.: - ___gnu_compiled_ada: - .text - .align 4 - .globl __ada_nothing - __ada_nothing: - #APP - nop - #NO_APP - jmp L1 - .align 2,0x90 - L1: - ret - @end group - @end smallexample - - The assembly code you included is clearly indicated by - the compiler, between the @code{#APP} and @code{#NO_APP} - delimiters. The character before the 'APP' and 'NOAPP' - can differ on different targets. For example, Linux uses '#APP' while - on NT you will see '/APP'. - - If you make a mistake in your assembler code (such as using the - wrong size modifier, or using a wrong operand for the instruction) GNAT - will report this error in a temporary file, which will be deleted when - the compilation is finished. Generating an assembler file will help - in such cases, since you can assemble this file separately using the - @emph{as} assembler that comes with GNAT COMPILE. - - Assembling the file using the command - - @smallexample - as @file{nothing.s} - @end smallexample - @noindent - will give you error messages whose lines correspond to the assembler - input file, so you can easily find and correct any mistakes you made. - If there are no errors, @emph{as} will generate an object file @file{nothing.out}. - - @c --------------------------------------------------------------------------- - @node Output Variables in Inline Assembler - @section Output Variables in Inline Assembler - - @noindent - The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements. - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags; - @end group - @end smallexample - - In order to have a nicely aligned assembly listing, we have separated - multiple assembler statements in the Asm template string with linefeed (ASCII.LF) - and horizontal tab (ASCII.HT) characters. The resulting section of the - assembly output file is: - - @smallexample - @group - #APP - pushfl - popl %eax - movl %eax, -40(%ebp) - #NO_APP - @end group - @end smallexample - - It would have been legal to write the Asm invocation as: - - @smallexample - Asm ("pushfl popl %%eax movl %%eax, %0") - @end smallexample - - but in the generated assembler file, this would come out as: - - @smallexample - #APP - pushfl popl %eax movl %eax, -40(%ebp) - #NO_APP - @end smallexample - - which is not so convenient for the human reader. - - We use Ada comments - at the end of each line to explain what the assembler instructions - actually do. This is a useful convention. - - When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign. Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}. In the generated assembly code, one of the percent signs will be stripped off. - - Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}. - An output variable is illustrated in - the third statement in the Asm template string: - @smallexample - movl %%eax, %0 - @end smallexample - The intent is to store the contents of the eax register in a variable that can be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization. The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable. - - Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}: - @smallexample - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end smallexample - - The output is defined by the @code{Asm_Output} attribute of the target type; the general format is - @smallexample - Type'Asm_Output (constraint_string, variable_name) - @end smallexample - - The constraint string directs the compiler how - to store/access the associated variable. In the example - @smallexample - Unsigned_32'Asm_Output ("=m", Flags); - @end smallexample - the @code{"m"} (memory) constraint tells the compiler that the variable - @code{Flags} should be stored in a memory variable, thus preventing - the optimizer from keeping it in a register. In contrast, - @smallexample - Unsigned_32'Asm_Output ("=r", Flags); - @end smallexample - uses the @code{"r"} (register) constraint, telling the compiler to - store the variable in a register. - - If the constraint is preceded by the equal character (@strong{=}), it tells the - compiler that the variable will be used to store data into it. - - In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer - to choose whatever it deems best. - - There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following: - - @table @code - @item = - output constraint - @item g - global (i.e. can be stored anywhere) - @item m - in memory - @item I - a constant - @item a - use eax - @item b - use ebx - @item c - use ecx - @item d - use edx - @item S - use esi - @item D - use edi - @item r - use one of eax, ebx, ecx or edx - @item q - use one of eax, ebx, ecx, edx, esi or edi - @end table - - The full set of constraints is described in the GNAT COMPILE and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string. - - You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer. Thus in - @smallexample - @group - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end group - @end smallexample - @noindent - @code{%0} will be replaced in the expanded code by the appropriate operand, - whatever - the compiler decided for the @code{Flags} variable. - - In general, you may have any number of output variables: - @itemize @bullet - @item - Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. - @item - Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes - @end itemize - - For example: - @smallexample - @group - Asm ("movl %%eax, %0" & LF & HT & - "movl %%ebx, %1" & LF & HT & - "movl %%ecx, %2", - Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A - Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B - Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C - @end group - @end smallexample - @noindent - where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program. - - As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_2 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax", -- save flags in eax - Outputs => Unsigned_32'Asm_Output ("=a", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_2; - @end group - @end smallexample - - @noindent - The @code{"a"} constraint tells the compiler that the @code{Flags} - variable will come from the eax register. Here is the resulting code: - - @smallexample - @group - #APP - pushfl - popl %eax - #NO_APP - movl %eax,-40(%ebp) - @end group - @end smallexample - - @noindent - The compiler generated the store of eax into Flags after - expanding the assembler code. - - Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_3 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "pop %0", -- save flags in Flags - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_3; - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Input Variables in Inline Assembler - @section Input Variables in Inline Assembler - - @noindent - The example in this section illustrates how to specify the source operands for assembly language statements. The program simply increments its input value by 1: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Incr (Value); - Put_Line ("Value after is" & Value'Img); - end Increment; - @end group - @end smallexample - - The @code{Outputs} parameter to @code{Asm} specifies - that the result will be in the eax register and that it is to be stored in the @code{Result} - variable. - - The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an - @code{Asm_Input} attribute. The - @code{"="} constraint, indicating an output value, is not present. - - You can have multiple input variables, in the same way that you can have more - than one output variable. - - The parameter count (%0, %1) etc, now starts at the first input - statement, and continues with the output statements. - When both parameters use the same variable, the - compiler will treat them as the same %n operand, which is the case here. - - Just as the @code{Outputs} parameter causes the register to be stored into the - target variable after execution of the assembler statements, so does the - @code{Inputs} parameter cause its variable to be loaded into the register before execution - of the - assembler statements. - - Thus the effect of the @code{Asm} invocation is: - @enumerate - @item load the 32-bit value of @code{Value} into eax - @item execute the @code{incl %eax} instruction - @item store the contents of eax into the @code{Result} variable - @end enumerate - - The resulting assembler file (with @code{/OPTIMIZE=ALL} optimization) contains: - @smallexample - @group - _increment__incr.1: - subl $4,%esp - movl 8(%esp),%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - movl %ecx,(%esp) - addl $4,%esp - ret - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Inlining Inline Assembler Code - @section Inlining Inline Assembler Code - - @noindent - For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame) - can be significant, compared to the amount of code in the subprogram body. - A solution is to apply Ada's @code{Inline} pragma to the subprogram, - which directs the compiler to expand invocations of the subprogram at the point(s) - of call, instead of setting up a stack frame for out-of-line calls. - Here is the resulting program: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment_2 is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - pragma Inline (Increment); - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Increment (Value); - Put_Line ("Value after is" & Value'Img); - end Increment_2; - @end group - @end smallexample - - Compile the program with both optimization (@code{/OPTIMIZE=ALL}) and inlining - enabled (@option{-gnatpn} instead of @option{/CHECKS=SUPPRESS_ALL}). - - The @code{Incr} function is still compiled as usual, but at the - point in @code{Increment} where our function used to be called: - - @smallexample - @group - pushl %edi - call _increment__incr.1 - @end group - @end smallexample - - @noindent - the code for the function body directly appears: - - @smallexample - @group - movl %esi,%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - @end group - @end smallexample - - @noindent - thus saving the overhead of stack frame setup and an out-of-line call. - - @c --------------------------------------------------------------------------- - @node Other Asm Functionality - @section Other @code{Asm} Functionality - - @noindent - This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations. - - @menu - * The Clobber Parameter:: - * The Volatile Parameter:: - @end menu - - @c --------------------------------------------------------------------------- - @node The Clobber Parameter - @subsection The @code{Clobber} Parameter - - @noindent - One of the dangers of intermixing assembly language and a compiled language such as Ada is - that the compiler needs to be aware of which registers are being used by the assembly code. - In some cases, such as the earlier examples, the constraint string is sufficient to - indicate register usage (e.g. "a" for the eax register). But more generally, the - compiler needs an explicit identification of the registers that are used by the Inline - Assembly statements. - - Using a register that the compiler doesn't know about - could be a side effect of an instruction (like @code{mull} - storing its result in both eax and edx). - It can also arise from explicit register usage in your - assembly code; for example: - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out)); - @end group - @end smallexample - @noindent - where the compiler (since it does not analyze the @code{Asm} template string) - does not know you are using the ebx register. - - In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, - to identify the registers that will be used by your assembly code: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx"); - @end group - @end smallexample - - The Clobber parameter is a static string expression specifying the - register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign. - Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"} - - The @code{Clobber} parameter has several additional uses: - @enumerate - @item Use the "register" name @code{cc} to indicate that flags might have changed - @item Use the "register" name @code{memory} if you changed a memory location - @end enumerate - - @c --------------------------------------------------------------------------- - @node The Volatile Parameter - @subsection The @code{Volatile} Parameter - @cindex Volatile parameter - - @noindent - Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects. - For example, when - an @code{Asm} invocation with an input variable is inside a loop, the compiler might move - the loading of the input variable outside the loop, regarding it as a - one-time initialization. - - If this effect is not desired, you can disable such optimizations by setting the - @code{Volatile} parameter to @code{True}; for example: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx", - Volatile => True); - @end group - @end smallexample - - By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs} - parameter. - - Although setting @code{Volatile} to @code{True} prevents unwanted optimizations, - it will also disable other optimizations that might be important for efficiency. - In general, you should set @code{Volatile} to @code{True} only if the compiler's - optimizations have created problems. - - @c --------------------------------------------------------------------------- - @node A Complete Example - @section A Complete Example - - @noindent - This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler - capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}. - The package declares a collection of functions that detect the properties of the 32-bit - x86 processor that is running the program. The main procedure invokes these functions - and displays the information. - - The Intel_CPU package could be enhanced by adding functions to - detect the type of x386 co-processor, the processor caching options and - special operations such as the SIMD extensions. - - Although the Intel_CPU package has been written for 32-bit Intel - compatible CPUs, it is OS neutral. It has been tested on DOS, - Windows/NT and Linux. - - @menu - * Check_CPU Procedure:: - * Intel_CPU Package Specification:: - * Intel_CPU Package Body:: - @end menu - - @c --------------------------------------------------------------------------- - @node Check_CPU Procedure - @subsection @code{Check_CPU} Procedure - @cindex Check_CPU procedure - - @smallexample - --------------------------------------------------------------------- - -- -- - -- Uses the Intel_CPU package to identify the CPU the program is -- - -- running on, and some of the features it supports. -- - -- -- - --------------------------------------------------------------------- - - with Intel_CPU; -- Intel CPU detection functions - with Ada.Text_IO; -- Standard text I/O - with Ada.Command_Line; -- To set the exit status - - procedure Check_CPU is - - Type_Found : Boolean := False; - -- Flag to indicate that processor was identified - - Features : Intel_CPU.Processor_Features; - -- The processor features - - Signature : Intel_CPU.Processor_Signature; - -- The processor type signature - - begin - - ----------------------------------- - -- Display the program banner. -- - ----------------------------------- - - Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name & - ": check Intel CPU version and features, v1.0"); - Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever"); - Ada.Text_IO.New_Line; - - ----------------------------------------------------------------------- - -- We can safely start with the assumption that we are on at least -- - -- a x386 processor. If the CPUID instruction is present, then we -- - -- have a later processor type. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Has_CPUID = False then - - -- No CPUID instruction, so we assume this is indeed a x386 - -- processor. We can still check if it has a FP co-processor. - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line - ("x386-type processor with a FP co-processor"); - else - Ada.Text_IO.Put_Line - ("x386-type processor without a FP co-processor"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check for CPUID - - ----------------------------------------------------------------------- - -- If CPUID is supported, check if this is a true Intel processor, -- - -- if it is not, display a warning. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then - Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor"); - Ada.Text_IO.Put_Line ("*** Some information may be incorrect"); - end if; -- check if Intel - - ---------------------------------------------------------------------- - -- With the CPUID instruction present, we can assume at least a -- - -- x486 processor. If the CPUID support level is < 1 then we have -- - -- to leave it at that. -- - ---------------------------------------------------------------------- - - if Intel_CPU.CPUID_Level < 1 then - - -- Ok, this is a x486 processor. we still can get the Vendor ID - Ada.Text_IO.Put_Line ("x486-type processor"); - Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID); - - -- We can also check if there is a FPU present - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line ("Floating-Point support"); - else - Ada.Text_IO.Put_Line ("No Floating-Point support"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check CPUID level - - --------------------------------------------------------------------- - -- With a CPUID level of 1 we can use the processor signature to -- - -- determine it's exact type. -- - --------------------------------------------------------------------- - - Signature := Intel_CPU.Signature; - - ---------------------------------------------------------------------- - -- Ok, now we go into a lot of messy comparisons to get the -- - -- processor type. For clarity, no attememt to try to optimize the -- - -- comparisons has been made. Note that since Intel_CPU does not -- - -- support getting cache info, we cannot distinguish between P5 -- - -- and Celeron types yet. -- - ---------------------------------------------------------------------- - - -- x486SL - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486SL processor"); - end if; - - -- x486DX2 Write-Back - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0111# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor"); - end if; - - -- x486DX4 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 processor"); - end if; - - -- x486DX4 Overdrive - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor"); - end if; - - -- Pentium (60, 66) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium processor (60, 66)"); - end if; - - -- Pentium (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive (60, 66) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)"); - end if; - - -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive processor for x486 processor-based systems - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor for x486 processor-based systems"); - end if; - - -- Pentium processor with MMX technology (166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor with MMX technology (166, 200)"); - end if; - - -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor with MMX " & - "technology for Pentium processor (75, 90, 100, 120, 133)"); - end if; - - -- Pentium Pro processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro processor"); - end if; - - -- Pentium II processor, model 3 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium II processor, model 3"); - end if; - - -- Pentium II processor, model 5 or Celeron processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0101# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium II processor, model 5 or Celeron processor"); - end if; - - -- Pentium Pro OverDrive processor - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor"); - end if; - - -- If no type recognized, we have an unknown. Display what - -- we _do_ know - if Type_Found = False then - Ada.Text_IO.Put_Line ("Unknown processor"); - end if; - - ----------------------------------------- - -- Display processor stepping level. -- - ----------------------------------------- - - Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img); - - --------------------------------- - -- Display vendor ID string. -- - --------------------------------- - - Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID); - - ------------------------------------ - -- Get the processors features. -- - ------------------------------------ - - Features := Intel_CPU.Features; - - ----------------------------- - -- Check for a FPU unit. -- - ----------------------------- - - if Features.FPU = True then - Ada.Text_IO.Put_Line ("Floating-Point unit available"); - else - Ada.Text_IO.Put_Line ("no Floating-Point unit"); - end if; -- check for FPU - - -------------------------------- - -- List processor features. -- - -------------------------------- - - Ada.Text_IO.Put_Line ("Supported features: "); - - -- Virtual Mode Extension - if Features.VME = True then - Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension"); - end if; - - -- Debugging Extension - if Features.DE = True then - Ada.Text_IO.Put_Line (" DE - Debugging Extension"); - end if; - - -- Page Size Extension - if Features.PSE = True then - Ada.Text_IO.Put_Line (" PSE - Page Size Extension"); - end if; - - -- Time Stamp Counter - if Features.TSC = True then - Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter"); - end if; - - -- Model Specific Registers - if Features.MSR = True then - Ada.Text_IO.Put_Line (" MSR - Model Specific Registers"); - end if; - - -- Physical Address Extension - if Features.PAE = True then - Ada.Text_IO.Put_Line (" PAE - Physical Address Extension"); - end if; - - -- Machine Check Extension - if Features.MCE = True then - Ada.Text_IO.Put_Line (" MCE - Machine Check Extension"); - end if; - - -- CMPXCHG8 instruction supported - if Features.CX8 = True then - Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction"); - end if; - - -- on-chip APIC hardware support - if Features.APIC = True then - Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support"); - end if; - - -- Fast System Call - if Features.SEP = True then - Ada.Text_IO.Put_Line (" SEP - Fast System Call"); - end if; - - -- Memory Type Range Registers - if Features.MTRR = True then - Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers"); - end if; - - -- Page Global Enable - if Features.PGE = True then - Ada.Text_IO.Put_Line (" PGE - Page Global Enable"); - end if; - - -- Machine Check Architecture - if Features.MCA = True then - Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture"); - end if; - - -- Conditional Move Instruction Supported - if Features.CMOV = True then - Ada.Text_IO.Put_Line - (" CMOV - Conditional Move Instruction Supported"); - end if; - - -- Page Attribute Table - if Features.PAT = True then - Ada.Text_IO.Put_Line (" PAT - Page Attribute Table"); - end if; - - -- 36-bit Page Size Extension - if Features.PSE_36 = True then - Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension"); - end if; - - -- MMX technology supported - if Features.MMX = True then - Ada.Text_IO.Put_Line (" MMX - MMX technology supported"); - end if; - - -- Fast FP Save and Restore - if Features.FXSR = True then - Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore"); - end if; - - --------------------- - -- Program done. -- - --------------------- - - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - - exception - - when others => - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); - raise; - - end Check_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Specification - @subsection @code{Intel_CPU} Package Specification - @cindex Intel_CPU package specification - - @smallexample - ------------------------------------------------------------------------- - -- -- - -- file: INTEL_CPU.ADS -- - -- -- - -- ********************************************* -- - -- * WARNING: for 32-bit Intel processors only * -- - -- ********************************************* -- - -- -- - -- This package contains a number of subprograms that are useful in -- - -- determining the Intel x86 CPU (and the features it supports) on -- - -- which the program is running. -- - -- -- - -- The package is based upon the information given in the Intel -- - -- Application Note AP-485: "Intel Processor Identification and the -- - -- CPUID Instruction" as of April 1998. This application note can be -- - -- found on www.intel.com. -- - -- -- - -- It currently deals with 32-bit processors only, will not detect -- - -- features added after april 1998, and does not guarantee proper -- - -- results on Intel-compatible processors. -- - -- -- - -- Cache info and x386 fpu type detection are not supported. -- - -- -- - -- This package does not use any privileged instructions, so should -- - -- work on any OS running on a 32-bit Intel processor. -- - -- -- - ------------------------------------------------------------------------- - - with Interfaces; use Interfaces; - -- for using unsigned types - - with System.Machine_Code; use System.Machine_Code; - -- for using inline assembler code - - with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; - -- for inserting control characters - - package Intel_CPU is - - ---------------------- - -- Processor bits -- - ---------------------- - - subtype Num_Bits is Natural range 0 .. 31; - -- the number of processor bits (32) - - -------------------------- - -- Processor register -- - -------------------------- - - -- define a processor register type for easy access to - -- the individual bits - - type Processor_Register is array (Num_Bits) of Boolean; - pragma Pack (Processor_Register); - for Processor_Register'Size use 32; - - ------------------------- - -- Unsigned register -- - ------------------------- - - -- define a processor register type for easy access to - -- the individual bytes - - type Unsigned_Register is - record - L1 : Unsigned_8; - H1 : Unsigned_8; - L2 : Unsigned_8; - H2 : Unsigned_8; - end record; - - for Unsigned_Register use - record - L1 at 0 range 0 .. 7; - H1 at 0 range 8 .. 15; - L2 at 0 range 16 .. 23; - H2 at 0 range 24 .. 31; - end record; - - for Unsigned_Register'Size use 32; - - --------------------------------- - -- Intel processor vendor ID -- - --------------------------------- - - Intel_Processor : constant String (1 .. 12) := "GenuineIntel"; - -- indicates an Intel manufactured processor - - ------------------------------------ - -- Processor signature register -- - ------------------------------------ - - -- a register type to hold the processor signature - - type Processor_Signature is - record - Stepping : Natural range 0 .. 15; - Model : Natural range 0 .. 15; - Family : Natural range 0 .. 15; - Processor_Type : Natural range 0 .. 3; - Reserved : Natural range 0 .. 262143; - end record; - - for Processor_Signature use - record - Stepping at 0 range 0 .. 3; - Model at 0 range 4 .. 7; - Family at 0 range 8 .. 11; - Processor_Type at 0 range 12 .. 13; - Reserved at 0 range 14 .. 31; - end record; - - for Processor_Signature'Size use 32; - - ----------------------------------- - -- Processor features register -- - ----------------------------------- - - -- a processor register to hold the processor feature flags - - type Processor_Features is - record - FPU : Boolean; -- floating point unit on chip - VME : Boolean; -- virtual mode extension - DE : Boolean; -- debugging extension - PSE : Boolean; -- page size extension - TSC : Boolean; -- time stamp counter - MSR : Boolean; -- model specific registers - PAE : Boolean; -- physical address extension - MCE : Boolean; -- machine check extension - CX8 : Boolean; -- cmpxchg8 instruction - APIC : Boolean; -- on-chip apic hardware - Res_1 : Boolean; -- reserved for extensions - SEP : Boolean; -- fast system call - MTRR : Boolean; -- memory type range registers - PGE : Boolean; -- page global enable - MCA : Boolean; -- machine check architecture - CMOV : Boolean; -- conditional move supported - PAT : Boolean; -- page attribute table - PSE_36 : Boolean; -- 36-bit page size extension - Res_2 : Natural range 0 .. 31; -- reserved for extensions - MMX : Boolean; -- MMX technology supported - FXSR : Boolean; -- fast FP save and restore - Res_3 : Natural range 0 .. 127; -- reserved for extensions - end record; - - for Processor_Features use - record - FPU at 0 range 0 .. 0; - VME at 0 range 1 .. 1; - DE at 0 range 2 .. 2; - PSE at 0 range 3 .. 3; - TSC at 0 range 4 .. 4; - MSR at 0 range 5 .. 5; - PAE at 0 range 6 .. 6; - MCE at 0 range 7 .. 7; - CX8 at 0 range 8 .. 8; - APIC at 0 range 9 .. 9; - Res_1 at 0 range 10 .. 10; - SEP at 0 range 11 .. 11; - MTRR at 0 range 12 .. 12; - PGE at 0 range 13 .. 13; - MCA at 0 range 14 .. 14; - CMOV at 0 range 15 .. 15; - PAT at 0 range 16 .. 16; - PSE_36 at 0 range 17 .. 17; - Res_2 at 0 range 18 .. 22; - MMX at 0 range 23 .. 23; - FXSR at 0 range 24 .. 24; - Res_3 at 0 range 25 .. 31; - end record; - - for Processor_Features'Size use 32; - - ------------------- - -- Subprograms -- - ------------------- - - function Has_FPU return Boolean; - -- return True if a FPU is found - -- use only if CPUID is not supported - - function Has_CPUID return Boolean; - -- return True if the processor supports the CPUID instruction - - function CPUID_Level return Natural; - -- return the CPUID support level (0, 1 or 2) - -- can only be called if the CPUID instruction is supported - - function Vendor_ID return String; - -- return the processor vendor identification string - -- can only be called if the CPUID instruction is supported - - function Signature return Processor_Signature; - -- return the processor signature - -- can only be called if the CPUID instruction is supported - - function Features return Processor_Features; - -- return the processors features - -- can only be called if the CPUID instruction is supported - - private - - ------------------------ - -- EFLAGS bit names -- - ------------------------ - - ID_Flag : constant Num_Bits := 21; - -- ID flag bit - - end Intel_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Body - @subsection @code{Intel_CPU} Package Body - @cindex Intel_CPU package body - - @smallexample - package body Intel_CPU is - - --------------------------- - -- Detect FPU presence -- - --------------------------- - - -- There is a FPU present if we can set values to the FPU Status - -- and Control Words. - - function Has_FPU return Boolean is - - Register : Unsigned_16; - -- processor register to store a word - - begin - - -- check if we can change the status word - Asm ( - - -- the assembler code - "finit" & LF & HT & -- reset status word - "movw $0x5A5A, %%ax" & LF & HT & -- set value status word - "fnstsw %0" & LF & HT & -- save status word - "movw %%ax, %0", -- store status word - - -- output stored in Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register), - - -- tell compiler that we used eax - Clobber => "eax"); - - -- if the status word is zero, there is no FPU - if Register = 0 then - return False; -- no status word - end if; -- check status word value - - -- check if we can get the control word - Asm ( - - -- the assembler code - "fnstcw %0", -- save the control word - - -- output into Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register)); - - -- check the relevant bits - if (Register and 16#103F#) /= 16#003F# then - return False; -- no control word - end if; -- check control word value - - -- FPU found - return True; - - end Has_FPU; - - -------------------------------- - -- Detect CPUID instruction -- - -------------------------------- - - -- The processor supports the CPUID instruction if it is possible - -- to change the value of ID flag bit in the EFLAGS register. - - function Has_CPUID return Boolean is - - Original_Flags, Modified_Flags : Processor_Register; - -- EFLAG contents before and after changing the ID flag - - begin - - -- try flipping the ID flag in the EFLAGS register - Asm ( - - -- the assembler code - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %%eax" & LF & HT & -- pop EFLAGS into eax - "movl %%eax, %0" & LF & HT & -- save EFLAGS content - "xor $0x200000, %%eax" & LF & HT & -- flip ID flag - "push %%eax" & LF & HT & -- push EFLAGS on stack - "popfl" & LF & HT & -- load EFLAGS register - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %1", -- save EFLAGS content - - -- output values, may be anything - -- Original_Flags is %0 - -- Modified_Flags is %1 - Outputs => - (Processor_Register'Asm_output ("=g", Original_Flags), - Processor_Register'Asm_output ("=g", Modified_Flags)), - - -- tell compiler eax is destroyed - Clobber => "eax"); - - -- check if CPUID is supported - if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then - return True; -- ID flag was modified - else - return False; -- ID flag unchanged - end if; -- check for CPUID - - end Has_CPUID; - - ------------------------------- - -- Get CPUID support level -- - ------------------------------- - - function CPUID_Level return Natural is - - Level : Unsigned_32; - -- returned support level - - begin - - -- execute CPUID, storing the results in the Level register - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero is stored in eax - -- returning the support level in eax - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- eax is stored in Level - Outputs => Unsigned_32'Asm_output ("=a", Level), - - -- tell compiler ebx, ecx and edx registers are destroyed - Clobber => "ebx, ecx, edx"); - - -- return the support level - return Natural (Level); - - end CPUID_Level; - - -------------------------------- - -- Get CPU Vendor ID String -- - -------------------------------- - - -- The vendor ID string is returned in the ebx, ecx and edx register - -- after executing the CPUID instruction with eax set to zero. - -- In case of a true Intel processor the string returned is - -- "GenuineIntel" - - function Vendor_ID return String is - - Ebx, Ecx, Edx : Unsigned_Register; - -- registers containing the vendor ID string - - Vendor_ID : String (1 .. 12); - -- the vendor ID string - - begin - - -- execute CPUID, storing the results in the processor registers - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero stored in eax - -- vendor ID string returned in ebx, ecx and edx - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- ebx is stored in Ebx - -- ecx is stored in Ecx - -- edx is stored in Edx - Outputs => (Unsigned_Register'Asm_output ("=b", Ebx), - Unsigned_Register'Asm_output ("=c", Ecx), - Unsigned_Register'Asm_output ("=d", Edx))); - - -- now build the vendor ID string - Vendor_ID( 1) := Character'Val (Ebx.L1); - Vendor_ID( 2) := Character'Val (Ebx.H1); - Vendor_ID( 3) := Character'Val (Ebx.L2); - Vendor_ID( 4) := Character'Val (Ebx.H2); - Vendor_ID( 5) := Character'Val (Edx.L1); - Vendor_ID( 6) := Character'Val (Edx.H1); - Vendor_ID( 7) := Character'Val (Edx.L2); - Vendor_ID( 8) := Character'Val (Edx.H2); - Vendor_ID( 9) := Character'Val (Ecx.L1); - Vendor_ID(10) := Character'Val (Ecx.H1); - Vendor_ID(11) := Character'Val (Ecx.L2); - Vendor_ID(12) := Character'Val (Ecx.H2); - - -- return string - return Vendor_ID; - - end Vendor_ID; - - ------------------------------- - -- Get processor signature -- - ------------------------------- - - function Signature return Processor_Signature is - - Result : Processor_Signature; - -- processor signature returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one is stored in eax - -- processor signature returned in eax - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- eax is stored in Result - Outputs => Processor_Signature'Asm_output ("=a", Result), - - -- tell compiler that ebx, ecx and edx are also destroyed - Clobber => "ebx, ecx, edx"); - - -- return processor signature - return Result; - - end Signature; - - ------------------------------ - -- Get processor features -- - ------------------------------ - - function Features return Processor_Features is - - Result : Processor_Features; - -- processor features returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one stored in eax - -- processor features returned in edx - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- edx is stored in Result - Outputs => Processor_Features'Asm_output ("=d", Result), - - -- tell compiler that ebx and ecx are also destroyed - Clobber => "ebx, ecx"); - - -- return processor signature - return Result; - - end Features; - - end Intel_CPU; - @end smallexample - @c END OF INLINE ASSEMBLER CHAPTER - @c =============================== - - - - - @node Performance Considerations - @chapter Performance Considerations - @cindex Performance - - @noindent - The GNAT system provides a number of options that allow a trade-off - between - - @itemize @bullet - @item - performance of the generated code - - @item - speed of compilation - - @item - minimization of dependences and recompilation - - @item - the degree of run-time checking. - @end itemize - - @noindent - The defaults (if no options are selected) aim at improving the speed - of compilation and minimizing dependences, at the expense of performance - of the generated code: - - @itemize @bullet - @item - no optimization - - @item - no inlining of subprogram calls - - @item - all run-time checks enabled except overflow and elaboration checks - @end itemize - - @noindent - These options are suitable for most program development purposes. This - chapter describes how you can modify these choices, and also provides - some guidelines on debugging optimized code. - - @menu - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - * Coverage Analysis:: - @end menu - - @node Controlling Run-Time Checks - @section Controlling Run-Time Checks - - @noindent - By default, GNAT generates all run-time checks, except arithmetic overflow - checking for integer operations and checks for access before elaboration on - subprogram calls. The latter are not required in default mode, because all - necessary checking is done at compile time. - @cindex @option{/CHECKS=SUPPRESS_ALL} (@code{GNAT COMPILE}) - @cindex @option{/CHECKS=OVERFLOW} (@code{GNAT COMPILE}) - Two gnat qualifiers, @option{/CHECKS=SUPPRESS_ALL} and @option{/CHECKS=OVERFLOW} allow this default to - be modified. @xref{Run-Time Checks}. - - Our experience is that the default is suitable for most development - purposes. - - We treat integer overflow specially because these - are quite expensive and in our experience are not as important as other - run-time checks in the development process. Note that division by zero - is not considered an overflow check, and divide by zero checks are - generated where required by default. - - Elaboration checks are off by default, and also not needed by default, since - GNAT uses a static elaboration analysis approach that avoids the need for - run-time checking. This manual contains a full chapter discussing the issue - of elaboration checks, and if the default is not satisfactory for your use, - you should read this chapter. - - For validity checks, the minimal checks required by the Ada Reference - Manual (for case statements and assignments to array elements) are on - by default. These can be suppressed by use of the @option{-gnatVn} qualifier. - Note that in Ada 83, there were no validity checks, so if the Ada 83 mode - is acceptable (or when comparing GNAT performance with an Ada 83 compiler), - it may be reasonable to routinely use @option{-gnatVn}. Validity checks - are also suppressed entirely if @option{/CHECKS=SUPPRESS_ALL} is used. - - @cindex Overflow checks - @cindex Checks, overflow - @findex Suppress - @findex Unsuppress - @cindex pragma Suppress - @cindex pragma Unsuppress - Note that the setting of the qualifiers controls the default setting of - the checks. They may be modified using either @code{pragma Suppress} (to - remove checks) or @code{pragma Unsuppress} (to add back suppressed - checks) in the program source. - - @node Optimization Levels - @section Optimization Levels - @cindex @code{/OPTIMIZE} (@code{GNAT COMPILE}) - - @noindent - The default is optimization off. This results in the fastest compile - times, but GNAT makes absolutely no attempt to optimize, and the - generated programs are considerably larger and slower than when - optimization is enabled. You can use the - @code{/OPTIMIZE} - on the @code{GNAT COMPILE} command line to control the optimization level: - - @table @code - @item /OPTIMIZE=NONE - no optimization (the default) - - @item /OPTIMIZE=SOME - medium level optimization - - @item /OPTIMIZE=ALL - full optimization - - @item /OPTIMIZE=INLINING - full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - @end table - - Higher optimization levels perform more global transformations on the - program and apply more expensive analysis algorithms in order to generate - faster and more compact code. The price in compilation time, and the - resulting improvement in execution time, - both depend on the particular application and the hardware environment. - You should experiment to find the best level for your application. - - Note: Unlike some other compilation systems, @code{GNAT COMPILE} has - been tested extensively at all optimization levels. There are some bugs - which appear only with optimization turned on, but there have also been - bugs which show up only in @emph{unoptimized} code. Selecting a lower - level of optimization does not improve the reliability of the code - generator, which in practice is highly reliable at all optimization - levels. - - Note regarding the use of @code{/OPTIMIZE=INLINING}: The use of this optimization level - is generally discouraged with GNAT, since it often results in larger - executables which run more slowly. See further discussion of this point - in @pxref{Inlining of Subprograms}. - - @node Debugging Optimized Code - @section Debugging Optimized Code - - @noindent - Since the compiler generates debugging tables for a compilation unit before - it performs optimizations, the optimizing transformations may invalidate some - of the debugging data. You therefore need to anticipate certain - anomalous situations that may arise while debugging optimized code. This - section describes the most common cases. - - @enumerate - @item - @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC - bouncing back and forth in the code. This may result from any of the following - optimizations: - - @itemize @bullet - @item - @i{Common subexpression elimination:} using a single instance of code for a - quantity that the source computes several times. As a result you - may not be able to stop on what looks like a statement. - - @item - @i{Invariant code motion:} moving an expression that does not change within a - loop, to the beginning of the loop. - - @item - @i{Instruction scheduling:} moving instructions so as to - overlap loads and stores (typically) with other code, or in - general to move computations of values closer to their uses. Often - this causes you to pass an assignment statement without the assignment - happening and then later bounce back to the statement when the - value is actually needed. Placing a breakpoint on a line of code - and then stepping over it may, therefore, not always cause all the - expected side-effects. - @end itemize - - @item - @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two - identical pieces of code are merged and the program counter suddenly - jumps to a statement that is not supposed to be executed, simply because - it (and the code following) translates to the same thing as the code - that @emph{was} supposed to be executed. This effect is typically seen in - sequences that end in a jump, such as a @code{goto}, a @code{return}, or - a @code{break} in a C @code{qualifier} statement. - - @item - @i{The "roving variable":} The symptom is an unexpected value in a variable. - There are various reasons for this effect: - - @itemize @bullet - @item - In a subprogram prologue, a parameter may not yet have been moved to its - "home". - - @item - A variable may be dead, and its register re-used. This is - probably the most common cause. - - @item - As mentioned above, the assignment of a value to a variable may - have been moved. - - @item - A variable may be eliminated entirely by value propagation or - other means. In this case, GCC may incorrectly generate debugging - information for the variable - @end itemize - - @noindent - In general, when an unexpected value appears for a local variable or parameter - you should first ascertain if that value was actually computed by - your program, as opposed to being incorrectly reported by the debugger. - Record fields or - array elements in an object designated by an access value - are generally less of a problem, once you have ascertained that the access value - is sensible. - Typically, this means checking variables in the preceding code and in the - calling subprogram to verify that the value observed is explainable from other - values (one must apply the procedure recursively to those - other values); or re-running the code and stopping a little earlier - (perhaps before the call) and stepping to better see how the variable obtained - the value in question; or continuing to step @emph{from} the point of the - strange value to see if code motion had simply moved the variable's - assignments later. - @end enumerate - - @node Inlining of Subprograms - @section Inlining of Subprograms - - @noindent - A call to a subprogram in the current unit is inlined if all the - following conditions are met: - - @itemize @bullet - @item - The optimization level is at least @code{/OPTIMIZE=SOME}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else that @code{GNAT COMPILE} - cannot support in inlined subprograms. - - @item - The call occurs after the definition of the body of the subprogram. - - @item - @cindex pragma Inline - @findex Inline - Either @code{pragma Inline} applies to the subprogram or it is - small and automatic inlining (optimization level @code{/OPTIMIZE=INLINING}) is - specified. - @end itemize - - @noindent - Calls to subprograms in @code{with}'ed units are normally not inlined. - To achieve this level of inlining, the following conditions must all be - true: - - @itemize @bullet - @item - The optimization level is at least @code{/OPTIMIZE=SOME}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else @code{GNAT COMPILE} cannot - support in inlined subprograms. - - @item - The call appears in a body (not in a package spec). - - @item - There is a @code{pragma Inline} for the subprogram. - - @item - @cindex @option{/INLINE=PRAGMA} (@code{GNAT COMPILE}) - The @code{/INLINE} qualifier - is used in the @code{GNAT COMPILE} command line - @end itemize - - Note that specifying the @option{/INLINE=PRAGMA} qualifier causes additional - compilation dependencies. Consider the following: - - @smallexample - @group - @cartouche - @b{package} R @b{is} - @b{procedure} Q; - @b{pragma} Inline (Q); - @b{end} R; - @b{package body} R @b{is} - ... - @b{end} R; - - @b{with} R; - @b{procedure} Main @b{is} - @b{begin} - ... - R.Q; - @b{end} Main; - @end cartouche - @end group - @end smallexample - - @noindent - With the default behavior (no @option{/INLINE=PRAGMA} qualifier specified), the - compilation of the @code{Main} procedure depends only on its own source, - @file{MAIN.ADB}, and the spec of the package in file @file{R.ADS}. This - means that editing the body of @code{R} does not require recompiling - @code{Main}. - - On the other hand, the call @code{R.Q} is not inlined under these - circumstances. If the @option{/INLINE=PRAGMA} qualifier is present when @code{Main} - is compiled, the call will be inlined if the body of @code{Q} is small - enough, but now @code{Main} depends on the body of @code{R} in - @file{R.ADB} as well as on the spec. This means that if this body is edited, - the main program must be recompiled. Note that this extra dependency - occurs whether or not the call is in fact inlined by @code{GNAT COMPILE}. - - The use of front end inlining with @option{-gnatN} generates similar - additional dependencies. - - @cindex @code{/INLINE=SUPPRESS} (@code{GNAT COMPILE}) - Note: The @code{/INLINE=SUPPRESS} qualifier - can be used to prevent - all inlining. This qualifier overrides all other conditions and ensures - that no inlining occurs. The extra dependences resulting from - @option{/INLINE=PRAGMA} will still be active, even if - this qualifier is used to suppress the resulting inlining actions. - - Note regarding the use of @code{/OPTIMIZE=INLINING}: There is no difference in inlining - behavior between @code{/OPTIMIZE=ALL} and @code{/OPTIMIZE=INLINING} for subprograms with an explicit - pragma @code{Inline} assuming the use of @option{/INLINE=PRAGMA} - or @option{-gnatN} (the qualifiers that activate inlining). If you have used - pragma @code{Inline} in appropriate cases, then it is usually much better - to use @code{/OPTIMIZE=ALL} and @option{/INLINE=PRAGMA} and avoid the use of @code{/OPTIMIZE=INLINING} which - in this case only has the effect of inlining subprograms you did not - think should be inlined. We often find that the use of @code{/OPTIMIZE=INLINING} slows - down code by performing excessive inlining, leading to increased instruction - cache pressure from the increased code size. So the bottom line here is - that you should not automatically assume that @code{/OPTIMIZE=INLINING} is better than - @code{/OPTIMIZE=ALL}, and indeed you should use @code{/OPTIMIZE=INLINING} only if tests show that - it actually improves performance. - - @node Coverage Analysis - @section Coverage Analysis - - @noindent - GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows - the user to determine the distribution of execution time across a program, - @pxref{Profiling} for details of usage. - - @include fdl.texi - @c GNU Free Documentation License - - @node Index,,GNU Free Documentation License, Top - @unnumbered Index - - @printindex cp - - @contents - - @bye --- 0 ---- diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_ug_vxw.texi gcc-3.4.1/gcc/ada/gnat_ug_vxw.texi *** gcc-3.4.0/gcc/ada/gnat_ug_vxw.texi 2004-03-20 15:33:53.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_ug_vxw.texi 1970-01-01 00:00:00.000000000 +0000 *************** *** 1,20089 **** - \input texinfo @c -*-texinfo-*- - @c %**start of header - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c o - @c GNAT DOCUMENTATION o - @c o - @c G N A T _ U G o - @c o - @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. o - @c o - @c GNAT is free software; you can redistribute it and/or modify it under o - @c terms of the GNU General Public License as published by the Free Soft- o - @c ware Foundation; either version 2, or (at your option) any later ver- o - @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o - @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o - @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o - @c for more details. You should have received a copy of the GNU General o - @c Public License distributed with GNAT; see file COPYING. If not, write o - @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o - @c MA 02111-1307, USA. o - @c o - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c - @c GNAT_UG Style Guide - @c - @c 1. Always put a @noindent on the line before the first paragraph - @c after any of these commands: - @c - @c @chapter - @c @section - @c @subsection - @c @subsubsection - @c @subsubsubsection - @c - @c @end smallexample - @c @end itemize - @c @end enumerate - @c - @c 2. DO NOT use @example. Use @smallexample instead. - @c - @c 3. Each @chapter, @section, @subsection, @subsubsection, etc. - @c command must be preceded by two empty lines - @c - @c 4. The @item command must be on a line of its own if it is in an - @c @itemize or @enumerate command. - @c - @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" - @c or "ali". - @c - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - - - - @setfilename gnat_ug_vxw.info - @settitle GNAT User's Guide for Cross Platforms - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_vxw). GNAT User's Guide for Cross Platforms. - @end direntry - - @include gcc-common.texi - - @setchapternewpage odd - @syncodeindex fn cp - @c %**end of header - - @copying - Copyright @copyright{} 1995-2003, Free Software Foundation - - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with the Invariant Sections being ``GNU Free Documentation License'', with the - Front-Cover Texts being - ``GNAT User's Guide for Cross Platforms'', - and with no Back-Cover Texts. - A copy of the license is included in the section entitled ``GNU - Free Documentation License''. - @end copying - - @titlepage - - - - - @title GNAT User's Guide - @center @titlefont{for Cross Platforms} - - @subtitle GNAT, The GNU Ada 95 Compiler - @subtitle GNAT Version for GCC @value{version-GCC} - - @author Ada Core Technologies, Inc. - - @page - @vskip 0pt plus 1filll - - @insertcopying - - @end titlepage - - @ifnottex - @node Top, About This Guide, (dir), (dir) - @top GNAT User's Guide - - - - - GNAT User's Guide for Cross Platforms - - GNAT, The GNU Ada 95 Compiler - - GNAT Version for GCC @value{version-GCC} - - Ada Core Technologies, Inc. - - @insertcopying - - @menu - * About This Guide:: - * Preliminary Note for Cross Platform Users:: - * Getting Started with GNAT:: - * The GNAT Compilation Model:: - * Compiling Using gcc:: - * Binding Using gnatbind:: - * Linking Using gnatlink:: - * The GNAT Make Program gnatmake:: - * Renaming Files Using gnatchop:: - * Configuration Pragmas:: - * Handling Arbitrary File Naming Conventions Using gnatname:: - * GNAT Project Manager:: - * Elaboration Order Handling in GNAT:: - * The Cross-Referencing Tools gnatxref and gnatfind:: - * File Name Krunching Using gnatkr:: - * Preprocessing Using gnatprep:: - * The GNAT Library Browser gnatls:: - * GNAT and Libraries:: - * Using the GNU make Utility:: - * Finding Memory Problems with GNAT Debug Pool:: - * Creating Sample Bodies Using gnatstub:: - * Reducing the Size of Ada Executables with gnatelim:: - * Other Utility Programs:: - * Running and Debugging Ada Programs:: - * Inline Assembler:: - * VxWorks Topics:: - * LynxOS Topics:: - * Performance Considerations:: - * GNU Free Documentation License:: - * Index:: - - --- The Detailed Node Listing --- - - About This Guide - - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - - Preliminary Note for Cross Platform Users:: - - Getting Started with GNAT - - * Running GNAT:: - * Building a Simple Ada Program:: - * Executing a Program on VxWorks:: - * Running a Program with Multiple Units:: - * Using the gnatmake Utility:: - - The GNAT Compilation Model - - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - - Foreign Language Representation - - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - - Compiling Ada Programs With gcc - - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - - Switches for gcc - - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - - Binding Ada Programs With gnatbind - - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - - Linking Using gnatlink - - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - - The GNAT Make Program gnatmake - - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - - Renaming Files Using gnatchop - - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - - Configuration Pragmas - - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - - Handling Arbitrary File Naming Conventions Using gnatname - - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - - GNAT Project Manager - - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - - Elaboration Order Handling in GNAT - - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - - The Cross-Referencing Tools gnatxref and gnatfind - - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - - File Name Krunching Using gnatkr - - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - - Preprocessing Using gnatprep - - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - - - The GNAT Library Browser gnatls - - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - - - GNAT and Libraries - - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - - Using the GNU make Utility - - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - - - Finding Memory Problems with GNAT Debug Pool - - Creating Sample Bodies Using gnatstub - - * Running gnatstub:: - * Switches for gnatstub:: - - Reducing the Size of Ada Executables with gnatelim - - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - - Other Utility Programs - - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - - - Running and Debugging Ada Programs - - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - - Inline Assembler - - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - - - VxWorks Topics - - * Kernel Configuration for VxWorks:: - * Kernel Compilation Issues for VxWorks:: - * Handling Relocation Issues for PowerPc Targets:: - * Support for Software Floating Point on PowerPC Processors:: - * Interrupt Handling for VxWorks:: - * Simulating Command Line Arguments for VxWorks:: - * Debugging Issues for VxWorks:: - * Using GNAT from the Tornado 2 Project Facility:: - * Frequently Asked Questions for VxWorks:: - - LynxOS Topics - - * Getting Started with GNAT on LynxOS:: - * Kernel Configuration for LynxOS:: - * Patch Level Issues for LynxOS:: - * Debugging Issues for LynxOS:: - * An Example Debugging Session for LynxOS:: - - Performance Considerations - - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - - * Index:: - @end menu - @end ifnottex - - @node About This Guide - @unnumbered About This Guide - - @noindent - This guide describes the use of GNAT, a compiler and software development - toolset for the full Ada 95 programming language. - It describes the features of the compiler and tools, and details - how to use them to build Ada 95 applications. - - @menu - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - @end menu - - @node What This Guide Contains - @unnumberedsec What This Guide Contains - - @noindent - This guide contains the following chapters: - @itemize @bullet - @item - @ref{Preliminary Note for Cross Platform Users}, describes the basic - differences between the cross and native versions of GNAT. - @item - @ref{Getting Started with GNAT}, describes how to get started compiling - and running Ada programs with the GNAT Ada programming environment. - @item - @ref{The GNAT Compilation Model}, describes the compilation model used - by GNAT. - @item - @ref{Compiling Using gcc}, describes how to compile - Ada programs with @code{gcc}, the Ada compiler. - @item - @ref{Binding Using gnatbind}, describes how to - perform binding of Ada programs with @code{gnatbind}, the GNAT binding - utility. - @item - @ref{Linking Using gnatlink}, - describes @code{gnatlink}, a - program that provides for linking using the GNAT run-time library to - construct a program. @code{gnatlink} can also incorporate foreign language - object units into the executable. - @item - @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a - utility that automatically determines the set of sources - needed by an Ada compilation unit, and executes the necessary compilations - binding and link. - @item - @ref{Renaming Files Using gnatchop}, describes - @code{gnatchop}, a utility that allows you to preprocess a file that - contains Ada source code, and split it into one or more new files, one - for each compilation unit. - @item - @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT. - @item - @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override - the default GNAT file naming conventions, either for an individual unit or globally. - @item - @ref{GNAT Project Manager}, describes how to use project files to organize large projects. - @item - @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with - elaboration order issues. - @item - @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses - @code{gnatxref} and @code{gnatfind}, two tools that provide an easy - way to navigate through sources. - @item - @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr} - file name krunching utility, used to handle shortened - file names on operating systems with a limit on the length of names. - @item - @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a - preprocessor utility that allows a single source file to be used to - generate multiple or parameterized source files, by means of macro - substitution. - @item - @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a - utility that displays information about compiled units, including dependences - on the corresponding sources files, and consistency of compilations. - @item - @ref{GNAT and Libraries}, describes the process of creating and using - Libraries with GNAT. It also describes how to recompile the GNAT run-time - library. - - @item - @ref{Using the GNU make Utility}, describes some techniques for using - the GNAT toolset in Makefiles. - - @item - @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to - use the GNAT-specific Debug Pool in order to detect as early as possible - the use of incorrect memory references. - - @item - @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub}, - a utility that generates empty but compilable bodies for library units. - - @item - @ref{Reducing the Size of Ada Executables with gnatelim}, describes - @code{gnatelim}, a tool which detects unused subprograms and helps - the compiler to create a smaller executable for the program. - - @item - @ref{Other Utility Programs}, discusses several other GNAT utilities, - including @code{gnatpsta}. - - @item - @ref{Running and Debugging Ada Programs}, describes how to run and debug - Ada programs. - - @item - @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program. - - @item - @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation - configurations. - - @item - @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation - configurations. - - @item - @ref{Performance Considerations}, reviews the trade offs between using - defaults or options in program development. - @end itemize - - @node What You Should Know before Reading This Guide - @unnumberedsec What You Should Know before Reading This Guide - - @cindex Ada 95 Language Reference Manual - @noindent - This user's guide assumes that you are familiar with Ada 95 language, as - described in the International Standard ANSI/ISO/IEC-8652:1995, Jan - 1995. - - @node Related Information - @unnumberedsec Related Information - - @noindent - For further information about related tools, refer to the following - documents: - - @itemize @bullet - @item - @cite{GNAT Reference Manual}, which contains all reference - material for the GNAT implementation of Ada 95. - - @item - @cite{Ada 95 Language Reference Manual}, which contains all reference - material for the Ada 95 programming language. - - @item - @cite{Debugging with GDB} - contains all details on the use of the GNU source-level debugger. - - @item - @cite{GNU Emacs Manual} - contains full information on the extensible editor and programming - environment Emacs. - - @end itemize - - @node Conventions - @unnumberedsec Conventions - @cindex Conventions - @cindex Typographical conventions - - @noindent - Following are examples of the typographical and graphic conventions used - in this guide: - - @itemize @bullet - @item - @code{Functions}, @code{utility program names}, @code{standard names}, - and @code{classes}. - - @item - @samp{Option flags} - - @item - @file{File Names}, @file{button names}, and @file{field names}. - - @item - @var{Variables}. - - @item - @emph{Emphasis}. - - @item - [optional information or parameters] - - @item - Examples are described by text - @smallexample - and then shown this way. - @end smallexample - @end itemize - - @noindent - Commands that are entered by the user are preceded in this manual by the - characters @w{"@code{$ }"} (dollar sign followed by space). If your system - uses this sequence as a prompt, then the commands will appear exactly as - you see them in the manual. If your system uses some other prompt, then - the command will appear with the @code{$} replaced by whatever prompt - character you are using. - - @node Preliminary Note for Cross Platform Users - @chapter Preliminary Note for Cross Platform Users - - @noindent - The use of GNAT in a cross environment is very similar to its use in a - native environment. Most of the tools described in this manual have - similar functions and options in both modes. The major - difference is that the name of the cross tools includes the target for - which the cross compiler is configured. For instance, the cross @command{gnatmake} - tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of - the cross target. Thus, in an environment configured for the - target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is - @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the - installation of a native and one or several cross development - environments at the same location. - - The tools that are most relevant in a cross environment are: - @code{@i{target}-gcc}, @code{@i{target}-gnatmake}, - @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross - applications and @code{@i{target}-gnatls} for cross library - browsing. @code{@i{target}-gdb} is also usually available for cross - debugging in text mode. The graphical debugger interface - @code{gvd} is always a native tool but it can be configured to drive - the above mentioned cross debugger, thus allowing graphical cross debugging - sessions. Some other tools such as @code{@i{target}-gnatchop}, - @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep}, - @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind} - and @code{@i{target}-gnatname} are also provided for completeness - even though they do not differ greatly from their native counterpart. - - In the rest of this manual, the tools are sometimes designated with - their full cross name, and sometimes with their simplified native - name. - - - @node Getting Started with GNAT - @chapter Getting Started with GNAT - - @noindent - This introduction is a starting point for using GNAT to develop - and execute Ada 95 programs in a cross environment. - It provides some specifics - about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform; - for other targets please refer to the corresponding chapter later in this manual. - - Basic familiarity with use of GNAT in a native environment is - presumed. For the VxWorks specific part, a knowledge of how to start - Tornado's @code{windsh} tool is also presumed. - - @menu - * Running GNAT:: - * Building a Simple Ada Program:: - * Executing a Program on VxWorks:: - - * Running a Program with Multiple Units:: - - * Using the gnatmake Utility:: - * Introduction to Glide and GVD:: - @end menu - - @node Running GNAT - @section Running GNAT - - @noindent - Three steps are needed to create an executable file from an Ada source - file: - - @enumerate - @item - The source file(s) must be compiled. - @item - The file(s) must be bound using the GNAT binder. - @item - All appropriate object files must be linked to produce a loadable module. - @end enumerate - - @noindent - All three steps are most commonly handled by using the @code{gnatmake} - utility program that, given the name of the main program, automatically - performs the necessary compilation, binding and linking steps. - - @node Building a Simple Ada Program - @section Building a Simple Ada Program - - @noindent - Any text editor may be used to prepare an Ada program. If @code{Glide} is - used, the optional Ada mode may be helpful in laying out the program. The - program text is a normal text file. We will suppose in our initial - example that you have used your editor to prepare the following - standard format text file: - - @smallexample - @group - @cartouche - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - @end cartouche - @end group - @end smallexample - - @noindent - This file should be named @file{hello.adb}. - With the normal default file naming conventions, GNAT requires - that each file - contain a single compilation unit whose file name is the - unit name, - with periods replaced by hyphens; the - extension is @file{ads} for a - spec and @file{adb} for a body. - You can override this default file naming convention by use of the - special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). - Alternatively, if you want to rename your files according to this default - convention, which is probably more convenient if you will be using GNAT - for all your compilations, then the @code{gnatchop} utility - can be used to generate correctly-named source files - (@pxref{Renaming Files Using gnatchop}). - - You can compile the program using the following command (@code{$} is used - as the command prompt in the examples in this document): - - - @smallexample - $ @i{target}-gcc -c hello.adb - @end smallexample - - @noindent - @code{gcc} is the command used to run the compiler. This compiler is - capable of compiling programs in several languages, including Ada 95 and - C. It assumes that you have given it an Ada program if the file extension is - either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile - the specified file. - - The @option{-c} switch is required. It tells @command{gcc} to only do a - compilation. (For C programs, @command{gcc} can also do linking, but this - capability is not used directly for Ada programs, so the @option{-c} - switch must always be present.) - - This compile command generates a file - @file{hello.o}, which is the object - file corresponding to your Ada program. It also generates an "Ada Library Information" file - @file{hello.ali}, - which contains additional information used to check - that an Ada program is consistent. - To build a downloadable module, - use @code{gnatbind} to bind the program - and @code{gnatlink} to link it. The - argument to both @code{gnatbind} and @code{gnatlink} is the name of the - @file{ali} file, but the default extension of @file{.ali} can - be omitted. This means that in the most common case, the argument - is simply the name of the main program: - - - @smallexample - $ @i{target}-gnatbind hello - $ @i{target}-gnatlink hello - @end smallexample - - @noindent - A simpler method of carrying out these steps is to use - @command{gnatmake}, - a master program that invokes all the required - compilation, binding and linking tools in the correct order. In particular, - @command{gnatmake} automatically recompiles any sources that have been modified - since they were last compiled, or sources that depend - on such modified sources, so that "version skew" is avoided. - @cindex Version skew (avoided by @command{gnatmake}) - - - @smallexample - $ @i{target}-gnatmake hello.adb - @end smallexample - - - @noindent - The result is a relocatable object called @file{hello}. - - @emph{Technical note:} the result of the linking stage is a - relocatable partially-linked object containing all the relevant GNAT - run-time units, in contrast with the executable-format object file found in - native environments. - - - @node Executing a Program on VxWorks - @section Executing a Program on VxWorks - - @noindent - Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it. - - @menu - * Loading and Running the Program:: - * Unloading the Program:: - @end menu - - @node Loading and Running the Program - @subsection Loading and Running the Program - - @noindent - An Ada program is loaded and run in the same way as a C program. - Details may be found in the @cite{Tornado User's Guide}. - - In order to load and run our simple "Hello World" example, we assume that - the target has access to the disk of the host containing this object and - that its working directory has been set to the directory containing this - object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt - is the @code{->} sequence. - - @smallexample - -> vf0=open("/vio/0",2,0) - new symbol "vf0" added to symbol table. - vf0 = 0x2cab48: value = 12 = 0xc - -> ioGlobalStdSet(1,vf0) - value = 1 = 0x1 - -> ld < hello - value = 665408 = 0xa2740 - -> hello - Hello World - value = 0 = 0x0 - -> - @end smallexample - - @noindent - The first two commands redirect output to the shell window. - They are only needed if the target server was started without the - @code{-C} option. The third command loads the module, which is the file - @file{hello} created previously by the @code{@i{target}-gnatmake} command. - Note that for Tornado AE, the @command{ml} command replaces @command{ld}." - - The "Hello World" program comprises a procedure named @code{hello}, and this - is the name entered for the procedure in the target server's symbol table - when the module is loaded. To execute the procedure, type the symbol name @code{hello} - into @code{windsh} as shown in the last command above. - - Note that by default the entry point of an Ada program is the name of the main - Ada subprogram in a VxWorks environment. It is possible to use an alternative - name; see the description of @code{gnatbind} options for details. - - @node Unloading the Program - @subsection Unloading the Program - - @noindent - It is important to remember that - you must unload a program once you have run it. You - cannot load it once and run it several times. If you don't follow - this rule, your program's behavior can be unpredictable, and will most - probably crash. - - This effect is due to the implementation of Ada 95's @emph{elaboration} semantics. - The unit elaboration phase comprises a @emph{static} elaboration and a - @emph{dynamic} elaboration. On a native platform they both take place - when the program is run. Thus rerunning the program will repeat the complete - elaboration phase, and the program will run correctly. - - On VxWorks, the process is a bit different. - The static elaboration phase is handled by - the loader (typically when you type @code{ld < program_name} in - @code{windsh}). The dynamic phase takes place when the program is run. If the - program is run twice and has not been unloaded and then reloaded, the - second time it is run, the static elaboration phase is skipped. - Variables initialized during the static elaboration phase - may have been modified during the first execution of the program. Thus the - second execution isn't performed on a completely initialized environment. - - Note that in C programs, elaboration isn't systematic. Multiple runs without reload - might work, but, even with C programs, if there is an elaboration - phase, you will have to unload your program before re-running it. - - - @node Running a Program with Multiple Units - @section Running a Program with Multiple Units - - @noindent - Consider a slightly more complicated example that has three files: a - main program, and the spec and body of a package: - - @smallexample - @cartouche - @group - @b{package} Greetings @b{is} - @b{procedure} Hello; - @b{procedure} Goodbye; - @b{end} Greetings; - - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{package} @b{body} Greetings @b{is} - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - - @b{procedure} Goodbye @b{is} - @b{begin} - Put_Line ("Goodbye WORLD!"); - @b{end} Goodbye; - @b{end} Greetings; - @end group - - @group - @b{with} Greetings; - @b{procedure} Gmain @b{is} - @b{begin} - Greetings.Hello; - Greetings.Goodbye; - @b{end} Gmain; - @end group - @end cartouche - @end smallexample - - @noindent - Following the one-unit-per-file rule, place this program in the - following three separate files: - - @table @file - @item greetings.ads - spec of package @code{Greetings} - - @item greetings.adb - body of package @code{Greetings} - - @item gmain.adb - body of main program - @end table - - @noindent - To build an executable version of - this program, we could use four separate steps to compile, bind, and link - the program, as follows: - - - @smallexample - $ @i{target}-gcc -c gmain.adb - $ @i{target}-gcc -c greetings.adb - $ @i{target}-gnatbind gmain - $ @i{target}-gnatlink gmain - @end smallexample - - @noindent - Note that there is no required order of compilation when using GNAT. - In particular it is perfectly fine to compile the main program first. - Also, it is not necessary to compile package specs in the case where - there is an accompanying body; you only need to compile the body. If you want - to submit these files to the compiler for semantic checking and not code generation, - then use the - @option{-gnatc} switch: - - - @smallexample - $ @i{target}-gcc -c greetings.ads -gnatc - @end smallexample - - @noindent - Although the compilation can be done in separate steps as in the - above example, in practice it is almost always more convenient - to use the @code{gnatmake} tool. All you need to know in this case - is the name of the main program's source file. The effect of the above four - commands can be achieved with a single one: - - - @smallexample - $ @i{target}-gnatmake gmain.adb - @end smallexample - - @noindent - In the next section we discuss the advantages of using @code{gnatmake} in - more detail. - - @node Using the gnatmake Utility - @section Using the @command{gnatmake} Utility - - @noindent - If you work on a program by compiling single components at a time using - @code{gcc}, you typically keep track of the units you modify. In order to - build a consistent system, you compile not only these units, but also any - units that depend on the units you have modified. - For example, in the preceding case, - if you edit @file{gmain.adb}, you only need to recompile that file. But if - you edit @file{greetings.ads}, you must recompile both - @file{greetings.adb} and @file{gmain.adb}, because both files contain - units that depend on @file{greetings.ads}. - - @code{gnatbind} will warn you if you forget one of these compilation - steps, so that it is impossible to generate an inconsistent program as a - result of forgetting to do a compilation. Nevertheless it is tedious and - error-prone to keep track of dependencies among units. - One approach to handle the dependency-bookkeeping is to use a - makefile. However, makefiles present maintenance problems of their own: - if the dependencies change as you change the program, you must make - sure that the makefile is kept up-to-date manually, which is also an - error-prone process. - - The @code{gnatmake} utility takes care of these details automatically. - Invoke it using either one of the following forms: - - - @smallexample - $ @i{target}-gnatmake gmain.adb - $ @i{target}-gnatmake gmain - @end smallexample - - @noindent - The argument is the name of the file containing the main program; - you may omit the extension. @code{gnatmake} - examines the environment, automatically recompiles any files that need - recompiling, and binds and links the resulting set of object files, - generating the executable file, @file{gmain}. - In a large program, it - can be extremely helpful to use @code{gnatmake}, because working out by hand - what needs to be recompiled can be difficult. - - Note that @code{gnatmake} - takes into account all the Ada 95 rules that - establish dependencies among units. These include dependencies that result - from inlining subprogram bodies, and from - generic instantiation. Unlike some other - Ada make tools, @code{gnatmake} does not rely on the dependencies that were - found by the compiler on a previous compilation, which may possibly - be wrong when sources change. @code{gnatmake} determines the exact set of - dependencies from scratch each time it is run. - - - @node Introduction to Glide and GVD - @section Introduction to Glide and GVD - @cindex Glide - @cindex GVD - @noindent - Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs. This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger. Additional information may be found in the on-line help for these tools. - - @menu - * Building a New Program with Glide:: - * Simple Debugging with GVD:: - * Other Glide Features:: - @end menu - - @node Building a New Program with Glide - @subsection Building a New Program with Glide - @noindent - The simplest way to invoke Glide is to enter @command{glide} at the command prompt. It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running: - - @smallexample - $ glide& - @end smallexample - - @noindent - Glide will start up with an initial screen displaying the top-level menu items as well as some other information. The menu selections are as follows - @itemize @bullet - @item @code{Buffers} - @item @code{Files} - @item @code{Tools} - @item @code{Edit} - @item @code{Search} - @item @code{Mule} - @item @code{Glide} - @item @code{Help} - @end itemize - - @noindent - For this introductory example, you will need to create a new Ada source file. First, select the @code{Files} menu. This will pop open a menu with around a dozen or so items. To create a file, select the @code{Open file...} choice. Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name. Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name. For this example enter @file{hello.adb} as the name of the file. - - A new buffer will now appear, occupying the entire Glide window, with the file name at the top. The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item. Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file. - - You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines. First, type the following text: - @smallexample - with Ada.Text_IO; use Ada.Text_IO; - procedure Hello is - begin - @end smallexample - - @noindent - Observe that Glide uses different colors to distinguish reserved words from identifiers. Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations. When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left. But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed. - - The main part of the program will be a @code{for} loop. Instead of entering the text explicitly, however, use a statement template. Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives. Choose @code{for loop}. You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed. You should see the beginning of a @code{for} loop appear in the source program window. You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case). Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction). Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax. - - Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop: - @smallexample - Put_Line("Hello, World" & Integer'Image(I)) - @end smallexample - - @noindent - Finally, type @code{end Hello;} as the last line in the program. Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection. You will see a message at the bottom of the buffer confirming that the file has been saved. - - You are now ready to attempt to build the program. Select the @code{Ada} item from the top menu bar. Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable. Thus select @code{Ada build}. This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools. Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window. The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected. - - Correct the error: type in a semicolon to terminate the statement. Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file. This time the build will succeed; the tool output window shows you the options that are supplied by default. The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched. - - To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window: - - @smallexample - Hello, world 1 - Hello, world 2 - Hello, world 3 - Hello, world 4 - Hello, world 5 - @end smallexample - - @node Simple Debugging with GVD - @subsection Simple Debugging with GVD - - @noindent - This section describes how to set breakpoints, examine/modify variables, and step through execution. - - In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}. If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect. You can then launch GVD, e.g. on the @code{hello} program, by issuing the command: - - @smallexample - $ gvd hello - @end smallexample - - @noindent - If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build. Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}. - - GVD comes up in a multi-part window. One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected. - - To the left of the source file pane, you will notice green dots adjacent to some lines. These are lines for which object code exists and where breakpoints can thus be set. You set/reset a breakpoint by clicking the green dot. When a breakpoint is set, the dot is replaced by an @code{X} in a red circle. Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot. - - For this example, set a breakpoint at the statement where @code{Put_Line} is invoked. - - Start program execution by selecting the @code{Run} button on the top menu bar. (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.) Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message. - - You can examine the values of variables in several ways. Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas. - - Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger. Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item. Enter @code{2} as the new value, and press @command{OK}. The box for @code{Ind} shows the update. - - Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}. - - Remove the breakpoint, and resume execution by selecting the @code{Cont} button. You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination. - - - @node Other Glide Features - @subsection Other Glide Features - - @noindent - You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu. These are @emph{shortcut keys} that you can use instead of selecting menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}. - - To abort a Glide command, type @key{Ctrl-g}. - - If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line: - - @smallexample - $ glide hello.adb& - @end smallexample - - @noindent - While you are using Glide, a number of @emph{buffers} exist. You create some explicitly; e.g., when you open/create a file. Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build. If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry. - - If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}. - - If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps: - @itemize @bullet - @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents) - @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu - @end itemize - - @noindent - To exit from Glide, choose @code{Files} @result{} @code{Exit}. - - @node The GNAT Compilation Model - @chapter The GNAT Compilation Model - @cindex GNAT compilation model - @cindex Compilation model - - @menu - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - @end menu - - @noindent - This chapter describes the compilation model used by GNAT. Although - similar to that used by other languages, such as C and C++, this model - is substantially different from the traditional Ada compilation models, - which are based on a library. The model is initially described without - reference to the library-based model. If you have not previously used an - Ada compiler, you need only read the first part of this chapter. The - last section describes and discusses the differences between the GNAT - model and the traditional Ada compiler models. If you have used other - Ada compilers, this section will help you to understand those - differences, and the advantages of the GNAT model. - - @node Source Representation - @section Source Representation - @cindex Latin-1 - - @noindent - Ada source programs are represented in standard text files, using - Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar - 7-bit ASCII set, plus additional characters used for - representing foreign languages (@pxref{Foreign Language Representation} - for support of non-USA character sets). The format effector characters - are represented using their standard ASCII encodings, as follows: - - @table @code - @item VT - @findex VT - Vertical tab, @code{16#0B#} - - @item HT - @findex HT - Horizontal tab, @code{16#09#} - - @item CR - @findex CR - Carriage return, @code{16#0D#} - - @item LF - @findex LF - Line feed, @code{16#0A#} - - @item FF - @findex FF - Form feed, @code{16#0C#} - @end table - - @noindent - Source files are in standard text file format. In addition, GNAT will - recognize a wide variety of stream formats, in which the end of physical - physical lines is marked by any of the following sequences: - @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful - in accommodating files that are imported from other operating systems. - - @cindex End of source file - @cindex Source file, end - @findex SUB - The end of a source file is normally represented by the physical end of - file. However, the control character @code{16#1A#} (@code{SUB}) is also - recognized as signalling the end of the source file. Again, this is - provided for compatibility with other operating systems where this - code is used to represent the end of file. - - Each file contains a single Ada compilation unit, including any pragmas - associated with the unit. For example, this means you must place a - package declaration (a package @dfn{spec}) and the corresponding body in - separate files. An Ada @dfn{compilation} (which is a sequence of - compilation units) is represented using a sequence of files. Similarly, - you will place each subunit or child unit in a separate file. - - @node Foreign Language Representation - @section Foreign Language Representation - - @noindent - GNAT supports the standard character sets defined in Ada 95 as well as - several other non-standard character sets for use in localized versions - of the compiler (@pxref{Character Set Control}). - @menu - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - @end menu - - @node Latin-1 - @subsection Latin-1 - @cindex Latin-1 - - @noindent - The basic character set is Latin-1. This character set is defined by ISO - standard 8859, part 1. The lower half (character codes @code{16#00#} - ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is - used to represent additional characters. These include extended letters - used by European languages, such as French accents, the vowels with umlauts - used in German, and the extra letter A-ring used in Swedish. - - @findex Ada.Characters.Latin_1 - For a complete list of Latin-1 codes and their encodings, see the source - file of library unit @code{Ada.Characters.Latin_1} in file - @file{a-chlat1.ads}. - You may use any of these extended characters freely in character or - string literals. In addition, the extended characters that represent - letters can be used in identifiers. - - @node Other 8-Bit Codes - @subsection Other 8-Bit Codes - - @noindent - GNAT also supports several other 8-bit coding schemes: - - @table @asis - @cindex Latin-2 - @item Latin-2 - Latin-2 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-3 - @cindex Latin-3 - Latin-3 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-4 - @cindex Latin-4 - Latin-4 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-5 - @cindex Latin-5 - @cindex Cyrillic - Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase - equivalence. - - @item IBM PC (code page 437) - @cindex code page 437 - This code page is the normal default for PCs in the U.S. It corresponds - to the original IBM PC character set. This set has some, but not all, of - the extended Latin-1 letters, but these letters do not have the same - encoding as Latin-1. In this mode, these letters are allowed in - identifiers with uppercase and lowercase equivalence. - - @item IBM PC (code page 850) - @cindex code page 850 - This code page is a modification of 437 extended to include all the - Latin-1 letters, but still not with the usual Latin-1 encoding. In this - mode, all these letters are allowed in identifiers with uppercase and - lowercase equivalence. - - @item Full Upper 8-bit - Any character in the range 80-FF allowed in identifiers, and all are - considered distinct. In other words, there are no uppercase and lowercase - equivalences in this range. This is useful in conjunction with - certain encoding schemes used for some foreign character sets (e.g. - the typical method of representing Chinese characters on the PC). - - @item No Upper-Half - No upper-half characters in the range 80-FF are allowed in identifiers. - This gives Ada 83 compatibility for identifier names. - @end table - - @noindent - For precise data on the encodings permitted, and the uppercase and lowercase - equivalences that are recognized, see the file @file{csets.adb} in - the GNAT compiler sources. You will need to obtain a full source release - of GNAT to obtain this file. - - @node Wide Character Encodings - @subsection Wide Character Encodings - - @noindent - GNAT allows wide character codes to appear in character and string - literals, and also optionally in identifiers, by means of the following - possible encoding schemes: - - @table @asis - - @item Hex Coding - In this encoding, a wide character is represented by the following five - character sequence: - - @smallexample - ESC a b c d - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ESC A345 is used to represent the wide character with code - @code{16#A345#}. - This scheme is compatible with use of the full Wide_Character set. - - @item Upper-Half Coding - @cindex Upper-Half Coding - The wide character with encoding @code{16#abcd#} where the upper bit is on (in - other words, "a" is in the range 8-F) is represented as two bytes, - @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control - character, but is not required to be in the upper half. This method can - be also used for shift-JIS or EUC, where the internal coding matches the - external coding. - - @item Shift JIS Coding - @cindex Shift JIS Coding - A wide character is represented by a two-character sequence, - @code{16#ab#} and - @code{16#cd#}, with the restrictions described for upper-half encoding as - described above. The internal character code is the corresponding JIS - character according to the standard algorithm for Shift-JIS - conversion. Only characters defined in the JIS code set table can be - used with this encoding method. - - @item EUC Coding - @cindex EUC Coding - A wide character is represented by a two-character sequence - @code{16#ab#} and - @code{16#cd#}, with both characters being in the upper half. The internal - character code is the corresponding JIS character according to the EUC - encoding algorithm. Only characters defined in the JIS code set table - can be used with this encoding method. - - @item UTF-8 Coding - A wide character is represented using - UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO - 10646-1/Am.2. Depending on the character value, the representation - is a one, two, or three byte sequence: - @smallexample - @iftex - @leftskip=.7cm - @end iftex - 16#0000#-16#007f#: 2#0xxxxxxx# - 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# - 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# - - @end smallexample - - @noindent - where the xxx bits correspond to the left-padded bits of the - 16-bit character value. Note that all lower half ASCII characters - are represented as ASCII bytes and all upper half characters and - other wide characters are represented as sequences of upper-half - (The full UTF-8 scheme allows for encoding 31-bit characters as - 6-byte sequences, but in this implementation, all UTF-8 sequences - of four or more bytes length will be treated as illegal). - @item Brackets Coding - In this encoding, a wide character is represented by the following eight - character sequence: - - @smallexample - [ " a b c d " ] - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ["A345"] is used to represent the wide character with code - @code{16#A345#}. It is also possible (though not required) to use the - Brackets coding for upper half characters. For example, the code - @code{16#A3#} can be represented as @code{["A3"]}. - - This scheme is compatible with use of the full Wide_Character set, - and is also the method used for wide character encoding in the standard - ACVC (Ada Compiler Validation Capability) test suite distributions. - - @end table - - @noindent - Note: Some of these coding schemes do not permit the full use of the - Ada 95 character set. For example, neither Shift JIS, nor EUC allow the - use of the upper half of the Latin-1 set. - - @node File Naming Rules - @section File Naming Rules - - @noindent - The default file name is determined by the name of the unit that the - file contains. The name is formed by taking the full expanded name of - the unit and replacing the separating dots with hyphens and using - lowercase for all letters. - - An exception arises if the file name generated by the above rules starts - with one of the characters - a,g,i, or s, - and the second character is a - minus. In this case, the character tilde is used in place - of the minus. The reason for this special rule is to avoid clashes with - the standard names for child units of the packages System, Ada, - Interfaces, and GNAT, which use the prefixes - s- a- i- and g- - respectively. - - The file extension is @file{.ads} for a spec and - @file{.adb} for a body. The following list shows some - examples of these rules. - - @table @file - @item main.ads - Main (spec) - @item main.adb - Main (body) - @item arith_functions.ads - Arith_Functions (package spec) - @item arith_functions.adb - Arith_Functions (package body) - @item func-spec.ads - Func.Spec (child package spec) - @item func-spec.adb - Func.Spec (child package body) - @item main-sub.adb - Sub (subunit of Main) - @item a~bad.adb - A.Bad (child package body) - @end table - - @noindent - Following these rules can result in excessively long - file names if corresponding - unit names are long (for example, if child units or subunits are - heavily nested). An option is available to shorten such long file names - (called file name "krunching"). This may be particularly useful when - programs being developed with GNAT are to be used on operating systems - with limited file name lengths. @xref{Using gnatkr}. - - Of course, no file shortening algorithm can guarantee uniqueness over - all possible unit names; if file name krunching is used, it is your - responsibility to ensure no name clashes occur. Alternatively you - can specify the exact file names that you want used, as described - in the next section. Finally, if your Ada programs are migrating from a - compiler with a different naming convention, you can use the gnatchop - utility to produce source files that follow the GNAT naming conventions. - (For details @pxref{Renaming Files Using gnatchop}.) - - @node Using Other File Names - @section Using Other File Names - @cindex File names - - @noindent - In the previous section, we have described the default rules used by - GNAT to determine the file name in which a given unit resides. It is - often convenient to follow these default rules, and if you follow them, - the compiler knows without being explicitly told where to find all - the files it needs. - - However, in some cases, particularly when a program is imported from - another Ada compiler environment, it may be more convenient for the - programmer to specify which file names contain which units. GNAT allows - arbitrary file names to be used by means of the Source_File_Name pragma. - The form of this pragma is as shown in the following examples: - @cindex Source_File_Name pragma - - @smallexample - @group - @cartouche - @b{pragma} Source_File_Name (My_Utilities.Stacks, - Spec_File_Name => "myutilst_a.ada"); - @b{pragma} Source_File_name (My_Utilities.Stacks, - Body_File_Name => "myutilst.ada"); - @end cartouche - @end group - @end smallexample - - @noindent - As shown in this example, the first argument for the pragma is the unit - name (in this example a child unit). The second argument has the form - of a named association. The identifier - indicates whether the file name is for a spec or a body; - the file name itself is given by a string literal. - - The source file name pragma is a configuration pragma, which means that - normally it will be placed in the @file{gnat.adc} - file used to hold configuration - pragmas that apply to a complete compilation environment. - For more details on how the @file{gnat.adc} file is created and used - @pxref{Handling of Configuration Pragmas} - @cindex @file{gnat.adc} - - GNAT allows completely arbitrary file names to be specified using the - source file name pragma. However, if the file name specified has an - extension other than @file{.ads} or @file{.adb} it is necessary to use a special - syntax when compiling the file. The name in this case must be preceded - by the special sequence @code{-x} followed by a space and the name of the - language, here @code{ada}, as in: - - @smallexample - $ gcc -c -x ada peculiar_file_name.sim - @end smallexample - - @noindent - @code{gnatmake} handles non-standard file names in the usual manner (the - non-standard file name for the main program is simply used as the - argument to gnatmake). Note that if the extension is also non-standard, - then it must be included in the gnatmake command, it may not be omitted. - - @node Alternative File Naming Schemes - @section Alternative File Naming Schemes - @cindex File naming schemes, alternative - @cindex File names - - In the previous section, we described the use of the @code{Source_File_Name} - pragma to allow arbitrary names to be assigned to individual source files. - However, this approach requires one pragma for each file, and especially in - large systems can result in very long @file{gnat.adc} files, and also create - a maintenance problem. - - GNAT also provides a facility for specifying systematic file naming schemes - other than the standard default naming scheme previously described. An - alternative scheme for naming is specified by the use of - @code{Source_File_Name} pragmas having the following format: - @cindex Source_File_Name pragma - - @smallexample - pragma Source_File_Name ( - Spec_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Body_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Subunit_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - FILE_NAME_PATTERN ::= STRING_LITERAL - CASING_SPEC ::= Lowercase | Uppercase | Mixedcase - - @end smallexample - - @noindent - The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. - It contains a single asterisk character, and the unit name is substituted - systematically for this asterisk. The optional parameter - @code{Casing} indicates - whether the unit name is to be all upper-case letters, all lower-case letters, - or mixed-case. If no - @code{Casing} parameter is used, then the default is all - lower-case. - - The optional @code{Dot_Replacement} string is used to replace any periods - that occur in subunit or child unit names. If no @code{Dot_Replacement} - argument is used then separating dots appear unchanged in the resulting - file name. - Although the above syntax indicates that the - @code{Casing} argument must appear - before the @code{Dot_Replacement} argument, but it - is also permissible to write these arguments in the opposite order. - - As indicated, it is possible to specify different naming schemes for - bodies, specs, and subunits. Quite often the rule for subunits is the - same as the rule for bodies, in which case, there is no need to give - a separate @code{Subunit_File_Name} rule, and in this case the - @code{Body_File_name} rule is used for subunits as well. - - The separate rule for subunits can also be used to implement the rather - unusual case of a compilation environment (e.g. a single directory) which - contains a subunit and a child unit with the same unit name. Although - both units cannot appear in the same partition, the Ada Reference Manual - allows (but does not require) the possibility of the two units coexisting - in the same environment. - - The file name translation works in the following steps: - - @itemize @bullet - - @item - If there is a specific @code{Source_File_Name} pragma for the given unit, - then this is always used, and any general pattern rules are ignored. - - @item - If there is a pattern type @code{Source_File_Name} pragma that applies to - the unit, then the resulting file name will be used if the file exists. If - more than one pattern matches, the latest one will be tried first, and the - first attempt resulting in a reference to a file that exists will be used. - - @item - If no pattern type @code{Source_File_Name} pragma that applies to the unit - for which the corresponding file exists, then the standard GNAT default - naming rules are used. - - @end itemize - - @noindent - As an example of the use of this mechanism, consider a commonly used scheme - in which file names are all lower case, with separating periods copied - unchanged to the resulting file name, and specs end with ".1.ada", and - bodies end with ".2.ada". GNAT will follow this scheme if the following - two pragmas appear: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.1.ada"); - pragma Source_File_Name - (Body_File_Name => "*.2.ada"); - @end smallexample - - @noindent - The default GNAT scheme is actually implemented by providing the following - default pragmas internally: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.ads", Dot_Replacement => "-"); - pragma Source_File_Name - (Body_File_Name => "*.adb", Dot_Replacement => "-"); - @end smallexample - - @noindent - Our final example implements a scheme typically used with one of the - Ada 83 compilers, where the separator character for subunits was "__" - (two underscores), specs were identified by adding @file{_.ADA}, bodies - by adding @file{.ADA}, and subunits by - adding @file{.SEP}. All file names were - upper case. Child units were not present of course since this was an - Ada 83 compiler, but it seems reasonable to extend this scheme to use - the same double underscore separator for child units. - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*_.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Body_File_Name => "*.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Subunit_File_Name => "*.SEP", - Dot_Replacement => "__", - Casing = Uppercase); - @end smallexample - - @node Generating Object Files - @section Generating Object Files - - @noindent - An Ada program consists of a set of source files, and the first step in - compiling the program is to generate the corresponding object files. - These are generated by compiling a subset of these source files. - The files you need to compile are the following: - - @itemize @bullet - @item - If a package spec has no body, compile the package spec to produce the - object file for the package. - - @item - If a package has both a spec and a body, compile the body to produce the - object file for the package. The source file for the package spec need - not be compiled in this case because there is only one object file, which - contains the code for both the spec and body of the package. - - @item - For a subprogram, compile the subprogram body to produce the object file - for the subprogram. The spec, if one is present, is as usual in a - separate file, and need not be compiled. - - @item - @cindex Subunits - In the case of subunits, only compile the parent unit. A single object - file is generated for the entire subunit tree, which includes all the - subunits. - - @item - Compile child units independently of their parent units - (though, of course, the spec of all the ancestor unit must be present in order - to compile a child unit). - - @item - @cindex Generics - Compile generic units in the same manner as any other units. The object - files in this case are small dummy files that contain at most the - flag used for elaboration checking. This is because GNAT always handles generic - instantiation by means of macro expansion. However, it is still necessary to - compile generic units, for dependency checking and elaboration purposes. - @end itemize - - @noindent - The preceding rules describe the set of files that must be compiled to - generate the object files for a program. Each object file has the same - name as the corresponding source file, except that the extension is - @file{.o} as usual. - - You may wish to compile other files for the purpose of checking their - syntactic and semantic correctness. For example, in the case where a - package has a separate spec and body, you would not normally compile the - spec. However, it is convenient in practice to compile the spec to make - sure it is error-free before compiling clients of this spec, because such - compilations will fail if there is an error in the spec. - - GNAT provides an option for compiling such files purely for the - purposes of checking correctness; such compilations are not required as - part of the process of building a program. To compile a file in this - checking mode, use the @option{-gnatc} switch. - - @node Source Dependencies - @section Source Dependencies - - @noindent - A given object file clearly depends on the source file which is compiled - to produce it. Here we are using @dfn{depends} in the sense of a typical - @code{make} utility; in other words, an object file depends on a source - file if changes to the source file require the object file to be - recompiled. - In addition to this basic dependency, a given object may depend on - additional source files as follows: - - @itemize @bullet - @item - If a file being compiled @code{with}'s a unit @var{X}, the object file - depends on the file containing the spec of unit @var{X}. This includes - files that are @code{with}'ed implicitly either because they are parents - of @code{with}'ed child units or they are run-time units required by the - language constructs used in a particular unit. - - @item - If a file being compiled instantiates a library level generic unit, the - object file depends on both the spec and body files for this generic - unit. - - @item - If a file being compiled instantiates a generic unit defined within a - package, the object file depends on the body file for the package as - well as the spec file. - - @item - @findex Inline - @cindex @option{-gnatn} switch - If a file being compiled contains a call to a subprogram for which - pragma @code{Inline} applies and inlining is activated with the - @option{-gnatn} switch, the object file depends on the file containing the - body of this subprogram as well as on the file containing the spec. Note - that for inlining to actually occur as a result of the use of this switch, - it is necessary to compile in optimizing mode. - - @cindex @option{-gnatN} switch - The use of @option{-gnatN} activates a more extensive inlining optimization - that is performed by the front end of the compiler. This inlining does - not require that the code generation be optimized. Like @option{-gnatn}, - the use of this switch generates additional dependencies. - - @item - If an object file O depends on the proper body of a subunit through inlining - or instantiation, it depends on the parent unit of the subunit. This means that - any modification of the parent unit or one of its subunits affects the - compilation of O. - - @item - The object file for a parent unit depends on all its subunit body files. - - @item - The previous two rules meant that for purposes of computing dependencies and - recompilation, a body and all its subunits are treated as an indivisible whole. - - @noindent - These rules are applied transitively: if unit @code{A} @code{with}'s - unit @code{B}, whose elaboration calls an inlined procedure in package - @code{C}, the object file for unit @code{A} will depend on the body of - @code{C}, in file @file{c.adb}. - - The set of dependent files described by these rules includes all the - files on which the unit is semantically dependent, as described in the - Ada 95 Language Reference Manual. However, it is a superset of what the - ARM describes, because it includes generic, inline, and subunit dependencies. - - An object file must be recreated by recompiling the corresponding source - file if any of the source files on which it depends are modified. For - example, if the @code{make} utility is used to control compilation, - the rule for an Ada object file must mention all the source files on - which the object file depends, according to the above definition. - The determination of the necessary - recompilations is done automatically when one uses @code{gnatmake}. - @end itemize - - @node The Ada Library Information Files - @section The Ada Library Information Files - @cindex Ada Library Information files - @cindex @file{ali} files - - @noindent - Each compilation actually generates two output files. The first of these - is the normal object file that has a @file{.o} extension. The second is a - text file containing full dependency information. It has the same - name as the source file, but an @file{.ali} extension. - This file is known as the Ada Library Information (@file{ali}) file. - The following information is contained in the @file{ali} file. - - @itemize @bullet - @item - Version information (indicates which version of GNAT was used to compile - the unit(s) in question) - - @item - Main program information (including priority and time slice settings, - as well as the wide character encoding used during compilation). - - @item - List of arguments used in the @code{gcc} command for the compilation - - @item - Attributes of the unit, including configuration pragmas used, an indication - of whether the compilation was successful, exception model used etc. - - @item - A list of relevant restrictions applying to the unit (used for consistency) - checking. - - @item - Categorization information (e.g. use of pragma @code{Pure}). - - @item - Information on all @code{with}'ed units, including presence of - @code{Elaborate} or @code{Elaborate_All} pragmas. - - @item - Information from any @code{Linker_Options} pragmas used in the unit - - @item - Information on the use of @code{Body_Version} or @code{Version} - attributes in the unit. - - @item - Dependency information. This is a list of files, together with - time stamp and checksum information. These are files on which - the unit depends in the sense that recompilation is required - if any of these units are modified. - - @item - Cross-reference data. Contains information on all entities referenced - in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to - provide cross-reference information. - - @end itemize - - @noindent - For a full detailed description of the format of the @file{ali} file, - see the source of the body of unit @code{Lib.Writ}, contained in file - @file{lib-writ.adb} in the GNAT compiler sources. - - @node Binding an Ada Program - @section Binding an Ada Program - - @noindent - When using languages such as C and C++, once the source files have been - compiled the only remaining step in building an executable program - is linking the object modules together. This means that it is possible to - link an inconsistent version of a program, in which two units have - included different versions of the same header. - - The rules of Ada do not permit such an inconsistent program to be built. - For example, if two clients have different versions of the same package, - it is illegal to build a program containing these two clients. - These rules are enforced by the GNAT binder, which also determines an - elaboration order consistent with the Ada rules. - - The GNAT binder is run after all the object files for a program have - been created. It is given the name of the main program unit, and from - this it determines the set of units required by the program, by reading the - corresponding ALI files. It generates error messages if the program is - inconsistent or if no valid order of elaboration exists. - - If no errors are detected, the binder produces a main program, in Ada by - default, that contains calls to the elaboration procedures of those - compilation unit that require them, followed by - a call to the main program. This Ada program is compiled to generate the - object file for the main program. The name of - the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec - @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the - main program unit. - - Finally, the linker is used to build the resulting executable program, - using the object from the main program from the bind step as well as the - object files for the Ada units of the program. - - @node Mixed Language Programming - @section Mixed Language Programming - @cindex Mixed Language Programming - - @menu - * Interfacing to C:: - * Calling Conventions:: - @end menu - - @node Interfacing to C - @subsection Interfacing to C - @noindent - There are two ways to - build a program that contains some Ada files and some other language - files depending on whether the main program is in Ada or not. - If the main program is in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake -c my_main.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind my_main.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. For instance: - @smallexample - gnatlink my_main.ali file1.o file2.o - @end smallexample - @end enumerate - - The three last steps can be grouped in a single command: - @smallexample - gnatmake my_main.adb -largs file1.o file2.o - @end smallexample - - @cindex Binder output file - @noindent - If the main program is in some language other than Ada, you may - have more than one entry point in the Ada subsystem. You must use a - special option of the binder to generate callable routines to initialize - and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). - Calls to the initialization and finalization routines must be inserted in - the main program, or some other appropriate point in the code. The call to - initialize the Ada units must occur before the first Ada subprogram is - called, and the call to finalize the Ada units must occur after the last - Ada subprogram returns. You use the same procedure for building the - program as described previously. In this case, however, the binder - only places the initialization and finalization subprograms into file - @file{b~@var{xxx}.adb} instead of the main program. - So, if the main program is not in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake -c entry_point1.adb - gnatmake -c entry_point2.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind -n entry_point1.ali entry_point2.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. You only need to give the last entry point here. For instance: - @smallexample - gnatlink entry_point2.ali file1.o file2.o - @end smallexample - @end enumerate - - @node Calling Conventions - @subsection Calling Conventions - @cindex Foreign Languages - @cindex Calling Conventions - GNAT follows standard calling sequence conventions and will thus interface - to any other language that also follows these conventions. The following - Convention identifiers are recognized by GNAT: - - @itemize @bullet - @cindex Interfacing to Ada - @cindex Other Ada compilers - @cindex Convention Ada - @item - Ada. This indicates that the standard Ada calling sequence will be - used and all Ada data items may be passed without any limitations in the - case where GNAT is used to generate both the caller and callee. It is also - possible to mix GNAT generated code and code generated by another Ada - compiler. In this case, the data types should be restricted to simple - cases, including primitive types. Whether complex data types can be passed - depends on the situation. Probably it is safe to pass simple arrays, such - as arrays of integers or floats. Records may or may not work, depending - on whether both compilers lay them out identically. Complex structures - involving variant records, access parameters, tasks, or protected types, - are unlikely to be able to be passed. - - Note that in the case of GNAT running - on a platform that supports DEC Ada 83, a higher degree of compatibility - can be guaranteed, and in particular records are layed out in an identical - manner in the two compilers. Note also that if output from two different - compilers is mixed, the program is responsible for dealing with elaboration - issues. Probably the safest approach is to write the main program in the - version of Ada other than GNAT, so that it takes care of its own elaboration - requirements, and then call the GNAT-generated adainit procedure to ensure - elaboration of the GNAT components. Consult the documentation of the other - Ada compiler for further details on elaboration. - - However, it is not possible to mix the tasking run time of GNAT and - DEC Ada 83, All the tasking operations must either be entirely within - GNAT compiled sections of the program, or entirely within DEC Ada 83 - compiled sections of the program. - - @cindex Interfacing to Assembly - @cindex Convention Assembler - @item - Assembler. Specifies assembler as the convention. In practice this has the - same effect as convention Ada (but is not equivalent in the sense of being - considered the same convention). - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembler. - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembly. - - @cindex Interfacing to COBOL - @cindex Convention COBOL - @findex COBOL - @item - COBOL. Data will be passed according to the conventions described - in section B.4 of the Ada 95 Reference Manual. - - @findex C - @cindex Interfacing to C - @cindex Convention C - @item - C. Data will be passed according to the conventions described - in section B.3 of the Ada 95 Reference Manual. - - @cindex Convention Default - @findex Default - @item - Default. Equivalent to C. - - @cindex Convention External - @findex External - @item - External. Equivalent to C. - - @findex C++ - @cindex Interfacing to C++ - @cindex Convention C++ - @item - CPP. This stands for C++. For most purposes this is identical to C. - See the separate description of the specialized GNAT pragmas relating to - C++ interfacing for further details. - - @findex Fortran - @cindex Interfacing to Fortran - @cindex Convention Fortran - @item - Fortran. Data will be passed according to the conventions described - in section B.5 of the Ada 95 Reference Manual. - - @item - Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95 - Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, - this means that the body of the subprogram is provided by the compiler itself, - usually by means of an efficient code sequence, and that the user does not - supply an explicit body for it. In an application program, the pragma can only - be applied to the following two sets of names, which the GNAT compiler - recognizes. - @itemize @bullet - @item - Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_- - Arithmetic. The corresponding subprogram declaration must have - two formal parameters. The - first one must be a signed integer type or a modular type with a binary - modulus, and the second parameter must be of type Natural. - The return type must be the same as the type of the first argument. The size - of this type can only be 8, 16, 32, or 64. - @item binary arithmetic operators: "+", "-", "*", "/" - The corresponding operator declaration must have parameters and result type - that have the same root numeric type (for example, all three are long_float - types). This simplifies the definition of operations that use type checking - to perform dimensional checks: - @smallexample - type Distance is new Long_Float; - type Time is new Long_Float; - type Velocity is new Long_Float; - function "/" (D : Distance; T : Time) - return Velocity; - pragma Import (Intrinsic, "/"); - @end smallexample - @noindent - This common idiom is often programmed with a generic definition and an explicit - body. The pragma makes it simpler to introduce such declarations. It incurs - no overhead in compilation time or code size, because it is implemented as a - single machine instruction. - @end itemize - @noindent - - @findex Stdcall - @cindex Convention Stdcall - @item - Stdcall. This is relevant only to NT/Win95 implementations of GNAT, - and specifies that the Stdcall calling sequence will be used, as defined - by the NT API. - - @findex DLL - @cindex Convention DLL - @item - DLL. This is equivalent to Stdcall. - - @findex Win32 - @cindex Convention Win32 - @item - Win32. This is equivalent to Stdcall. - - @findex Stubbed - @cindex Convention Stubbed - @item - Stubbed. This is a special convention that indicates that the compiler - should provide a stub body that raises @code{Program_Error}. - @end itemize - - @noindent - GNAT additionally provides a useful pragma @code{Convention_Identifier} - that can be used to parametrize conventions and allow additional synonyms - to be specified. For example if you have legacy code in which the convention - identifier Fortran77 was used for Fortran, you can use the configuration - pragma: - - @smallexample - pragma Convention_Identifier (Fortran77, Fortran); - @end smallexample - - @noindent - And from now on the identifier Fortran77 may be used as a convention - identifier (for example in an @code{Import} pragma) with the same - meaning as Fortran. - - @node Building Mixed Ada & C++ Programs - @section Building Mixed Ada & C++ Programs - - @noindent - Building a mixed application containing both Ada and C++ code may be a - challenge for the unaware programmer. As a matter of fact, this - interfacing has not been standardized in the Ada 95 reference manual due - to the immaturity and lack of standard of C++ at the time. This - section gives a few hints that should make this task easier. In - particular the first section addresses the differences with - interfacing with C. The second section looks into the delicate problem - of linking the complete application from its Ada and C++ parts. The last - section give some hints on how the GNAT run time can be adapted in order - to allow inter-language dispatching with a new C++ compiler. - - @menu - * Interfacing to C++:: - * Linking a Mixed C++ & Ada Program:: - * A Simple Example:: - * Adapting the Run Time to a New C++ Compiler:: - @end menu - - @node Interfacing to C++ - @subsection Interfacing to C++ - - @noindent - GNAT supports interfacing with C++ compilers generating code that is - compatible with the standard Application Binary Interface of the given - platform. - - @noindent - Interfacing can be done at 3 levels: simple data, subprograms and - classes. In the first 2 cases, GNAT offer a specific @var{Convention - CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle - names of subprograms and currently GNAT does not provide any help to - solve the demangling problem. This problem can be addressed in 2 ways: - @itemize @bullet - @item - by modifying the C++ code in order to force a C convention using - the @var{extern "C"} syntax. - - @item - by figuring out the mangled name and use it as the Link_Name argument of - the pragma import. - @end itemize - - @noindent - Interfacing at the class level can be achieved by using the GNAT specific - pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT - Reference Manual for additional information. - - @node Linking a Mixed C++ & Ada Program - @subsection Linking a Mixed C++ & Ada Program - - @noindent - Usually the linker of the C++ development system must be used to link - mixed applications because most C++ systems will resolve elaboration - issues (such as calling constructors on global class instances) - transparently during the link phase. GNAT has been adapted to ease the - use of a foreign linker for the last phase. Three cases can be - considered: - @enumerate - - @item - Using GNAT and G++ (GNU C++ compiler) from the same GCC - installation. The c++ linker can simply be called by using the c++ - specific driver called @code{c++}. Note that this setup is not - very common because it may request recompiling the whole GCC - tree from sources and it does not allow to upgrade easily to a new - version of one compiler for one of the two languages without taking the - risk of destabilizing the other. - - @smallexample - $ c++ -c file1.C - $ c++ -c file2.C - $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++ - @end smallexample - - @item - Using GNAT and G++ from 2 different GCC installations. If both compilers - are on the PATH, the same method can be used. It is important to be - aware that environment variables such as C_INCLUDE_PATH, - GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at - the same time and thus may make one of the 2 compilers operate - improperly if they are set for the other. In particular it is important - that the link command has access to the proper gcc library @file{libgcc.a}, - that is to say the one that is part of the C++ compiler - installation. The implicit link command as suggested in the gnatmake - command from the former example can be replaced by an explicit link - command with full verbosity in order to verify which library is used: - @smallexample - $ gnatbind ada_unit - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ - @end smallexample - If there is a problem due to interfering environment variables, it can - be workaround by using an intermediate script. The following example - shows the proper script to use when GNAT has not been installed at its - default location and g++ has been installed at its default location: - - @smallexample - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - unset BINUTILS_ROOT - unset GCC_ROOT - c++ $* - @end smallexample - - @item - Using a non GNU C++ compiler. The same set of command as previously - described can be used to insure that the c++ linker is - used. Nonetheless, you need to add the path to libgcc explicitely, since some - libraries needed by GNAT are located in this directory: - - @smallexample - - $ gnatlink ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - CC $* `gcc -print-libgcc-file-name` - - @end smallexample - - Where CC is the name of the non GNU C++ compiler. - - @end enumerate - - @node A Simple Example - @subsection A Simple Example - @noindent - The following example, provided as part of the GNAT examples, show how - to achieve procedural interfacing between Ada and C++ in both - directions. The C++ class A has 2 methods. The first method is exported - to Ada by the means of an extern C wrapper function. The second method - calls an Ada subprogram. On the Ada side, The C++ calls is modelized by - a limited record with a layout comparable to the C++ class. The Ada - subprogram, in turn, calls the c++ method. So from the C++ main program - the code goes back and forth between the 2 languages. - - @noindent - Here are the compilation commands - for a GNAT VxWorks/PowerPC configuration: - @smallexample - $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface - $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface - $ gnatlink simple_cpp_interface -o ada_part - $ c++ppc -c -DCPU=PPC604 -I/usr/windppc/target/h cpp_main.C - $ c++ppc -c -DCPU=PPC604 -I/usr/windppc/target/h ex7.C - $ ldppc -r -o my_main my_main.o ex7.o ada_part - @end smallexample - @noindent - Here are the corresponding sources: - @smallexample - - //cpp_main.C - - #include "ex7.h" - - extern "C" @{ - void adainit (void); - void adafinal (void); - void method1 (A *t); - @} - - void method1 (A *t) - @{ - t->method1 (); - @} - - int main () - @{ - A obj; - adainit (); - obj.method2 (3030); - adafinal (); - @} - - //ex7.h - - class Origin @{ - public: - int o_value; - @}; - class A : public Origin @{ - public: - void method1 (void); - virtual void method2 (int v); - A(); - int a_value; - @}; - - //ex7.C - - #include "ex7.h" - #include - - extern "C" @{ void ada_method2 (A *t, int v);@} - - void A::method1 (void) - @{ - a_value = 2020; - printf ("in A::method1, a_value = %d \n",a_value); - - @} - - void A::method2 (int v) - @{ - ada_method2 (this, v); - printf ("in A::method2, a_value = %d \n",a_value); - - @} - - A::A(void) - @{ - a_value = 1010; - printf ("in A::A, a_value = %d \n",a_value); - @} - - -- Ada sources - @b{package} @b{body} Simple_Cpp_Interface @b{is} - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is} - @b{begin} - Method1 (This); - This.A_Value := V; - @b{end} Ada_Method2; - - @b{end} Simple_Cpp_Interface; - - @b{package} Simple_Cpp_Interface @b{is} - @b{type} A @b{is} @b{limited} - @b{record} - O_Value : Integer; - A_Value : Integer; - @b{end} @b{record}; - @b{pragma} Convention (C, A); - - @b{procedure} Method1 (This : @b{in} @b{out} A); - @b{pragma} Import (C, Method1); - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer); - @b{pragma} Export (C, Ada_Method2); - - @b{end} Simple_Cpp_Interface; - @end smallexample - - @node Adapting the Run Time to a New C++ Compiler - @subsection Adapting the Run Time to a New C++ Compiler - @noindent - GNAT offers the capability to derive Ada 95 tagged types directly from - preexisting C++ classes and . See "Interfacing with C++" in the GNAT - reference manual. The mechanism used by GNAT for achieving such a goal - has been made user configurable through a GNAT library unit - @code{Interfaces.CPP}. The default version of this file is adapted to - the GNU c++ compiler. Internal knowledge of the virtual - table layout used by the new C++ compiler is needed to configure - properly this unit. The Interface of this unit is known by the compiler - and cannot be changed except for the value of the constants defining the - characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, - CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source - of this unit for more details. - - @node Comparison between GNAT and C/C++ Compilation Models - @section Comparison between GNAT and C/C++ Compilation Models - - @noindent - The GNAT model of compilation is close to the C and C++ models. You can - think of Ada specs as corresponding to header files in C. As in C, you - don't need to compile specs; they are compiled when they are used. The - Ada @code{with} is similar in effect to the @code{#include} of a C - header. - - One notable difference is that, in Ada, you may compile specs separately - to check them for semantic and syntactic accuracy. This is not always - possible with C headers because they are fragments of programs that have - less specific syntactic or semantic rules. - - The other major difference is the requirement for running the binder, - which performs two important functions. First, it checks for - consistency. In C or C++, the only defense against assembling - inconsistent programs lies outside the compiler, in a makefile, for - example. The binder satisfies the Ada requirement that it be impossible - to construct an inconsistent program when the compiler is used in normal - mode. - - @cindex Elaboration order control - The other important function of the binder is to deal with elaboration - issues. There are also elaboration issues in C++ that are handled - automatically. This automatic handling has the advantage of being - simpler to use, but the C++ programmer has no control over elaboration. - Where @code{gnatbind} might complain there was no valid order of - elaboration, a C++ compiler would simply construct a program that - malfunctioned at run time. - - @node Comparison between GNAT and Conventional Ada Library Models - @section Comparison between GNAT and Conventional Ada Library Models - - @noindent - This section is intended to be useful to Ada programmers who have - previously used an Ada compiler implementing the traditional Ada library - model, as described in the Ada 95 Language Reference Manual. If you - have not used such a system, please go on to the next section. - - @cindex GNAT library - In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of - source files themselves acts as the library. Compiling Ada programs does - not generate any centralized information, but rather an object file and - a ALI file, which are of interest only to the binder and linker. - In a traditional system, the compiler reads information not only from - the source file being compiled, but also from the centralized library. - This means that the effect of a compilation depends on what has been - previously compiled. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the version of the unit most recently compiled into the library. - - @item - Inlining is effective only if the necessary body has already been - compiled into the library. - - @item - Compiling a unit may obsolete other units in the library. - @end itemize - - @noindent - In GNAT, compiling one unit never affects the compilation of any other - units because the compiler reads only source files. Only changes to source - files can affect the results of a compilation. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the source version of the unit that is currently accessible to the - compiler. - - @item - @cindex Inlining - Inlining requires the appropriate source files for the package or - subprogram bodies to be available to the compiler. Inlining is always - effective, independent of the order in which units are complied. - - @item - Compiling a unit never affects any other compilations. The editing of - sources may cause previous compilations to be out of date if they - depended on the source file being modified. - @end itemize - - @noindent - The most important result of these differences is that order of compilation - is never significant in GNAT. There is no situation in which one is - required to do one compilation before another. What shows up as order of - compilation requirements in the traditional Ada library becomes, in - GNAT, simple source dependencies; in other words, there is only a set - of rules saying what source files must be present when a file is - compiled. - - @node Compiling Using gcc - @chapter Compiling Using @code{gcc} - - @noindent - This chapter discusses how to compile Ada programs using the @code{gcc} - command. It also describes the set of switches - that can be used to control the behavior of the compiler. - @menu - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - @end menu - - @node Compiling Programs - @section Compiling Programs - - @noindent - The first step in creating an executable program is to compile the units - of the program using the @code{gcc} command. You must compile the - following files: - - @itemize @bullet - @item - the body file (@file{.adb}) for a library level subprogram or generic - subprogram - - @item - the spec file (@file{.ads}) for a library level package or generic - package that has no body - - @item - the body file (@file{.adb}) for a library level package - or generic package that has a body - - @end itemize - - @noindent - You need @emph{not} compile the following files - - @itemize @bullet - - @item - the spec of a library unit which has a body - - @item - subunits - @end itemize - - @noindent - because they are compiled as part of compiling related units. GNAT - package specs - when the corresponding body is compiled, and subunits when the parent is - compiled. - @cindex No code generated - If you attempt to compile any of these files, you will get one of the - following error messages (where fff is the name of the file you compiled): - - @smallexample - No code generated for file @var{fff} (@var{package spec}) - No code generated for file @var{fff} (@var{subunit}) - @end smallexample - - @noindent - The basic command for compiling a file containing an Ada unit is - - @smallexample - $ gcc -c [@var{switches}] @file{file name} - @end smallexample - - @noindent - where @var{file name} is the name of the Ada file (usually - having an extension - @file{.ads} for a spec or @file{.adb} for a body). - You specify the - @code{-c} switch to tell @code{gcc} to compile, but not link, the file. - The result of a successful compilation is an object file, which has the - same name as the source file but an extension of @file{.o} and an Ada - Library Information (ALI) file, which also has the same name as the - source file, but with @file{.ali} as the extension. GNAT creates these - two output files in the current directory, but you may specify a source - file in any directory using an absolute or relative path specification - containing the directory information. - - @findex gnat1 - @code{gcc} is actually a driver program that looks at the extensions of - the file arguments and loads the appropriate compiler. For example, the - GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}. - These programs are in directories known to the driver program (in some - configurations via environment variables you set), but need not be in - your path. The @code{gcc} driver also calls the assembler and any other - utilities needed to complete the generation of the required object - files. - - It is possible to supply several file names on the same @code{gcc} - command. This causes @code{gcc} to call the appropriate compiler for - each file. For example, the following command lists three separate - files to be compiled: - - @smallexample - $ gcc -c x.adb y.adb z.c - @end smallexample - - @noindent - calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and - @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}. - The compiler generates three object files @file{x.o}, @file{y.o} and - @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the - Ada compilations. Any switches apply to all the files listed, - except for - @option{-gnat@var{x}} switches, which apply only to Ada compilations. - - @node Switches for gcc - @section Switches for @code{gcc} - - @noindent - The @code{gcc} command accepts switches that control the - compilation process. These switches are fully described in this section. - First we briefly list all the switches, in alphabetical order, then we - describe the switches in more detail in functionally grouped sections. - - @menu - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - @end menu - - @table @code - @cindex @code{-b} (@code{gcc}) - @item -b @var{target} - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gcc}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item -c - @cindex @code{-c} (@code{gcc}) - Compile. Always use this switch when compiling Ada programs. - - Note: for some other languages when using @code{gcc}, notably in - the case of C and C++, it is possible to use - use @code{gcc} without a @code{-c} switch to - compile and link in one step. In the case of GNAT, you - cannot use this approach, because the binder must be run - and @code{gcc} cannot be used to run the GNAT binder. - - @item -g - @cindex @code{-g} (@code{gcc}) - Generate debugging information. This information is stored in the object - file and copied from there to the final executable file by the linker, - where it can be read by the debugger. You must use the - @code{-g} switch if you plan on using the debugger. - - @item -I@var{dir} - @cindex @code{-I} (@code{gcc}) - @cindex RTL - Direct GNAT to search the @var{dir} directory for source files needed by - the current compilation - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -I- - @cindex @code{-I-} (@code{gcc}) - @cindex RTL - Except for the source file named in the command line, do not look for source files - in the directory containing the source file named in the command line - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -o @var{file} - @cindex @code{-o} (@code{gcc}) - This switch is used in @code{gcc} to redirect the generated object file - and its associated ALI file. Beware of this switch with GNAT, because it may - cause the object file and ALI file to have different names which in turn - may confuse the binder and the linker. - - @item -O[@var{n}] - @cindex @code{-O} (@code{gcc}) - @var{n} controls the optimization level. - - @table @asis - @item n = 0 - No optimization, the default setting if no @code{-O} appears - - @item n = 1 - Normal optimization, the default if you specify @code{-O} without - an operand. - - @item n = 2 - Extensive optimization - - @item n = 3 - Extensive optimization with automatic inlining. This applies only to - inlining within a unit. For details on control of inter-unit inlining - see @xref{Subprogram Inlining Control}. - @end table - - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gcc}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -S - @cindex @code{-S} (@code{gcc}) - Used in place of @code{-c} to - cause the assembler source file to be - generated, using @file{.s} as the extension, - instead of the object file. - This may be useful if you need to examine the generated assembly code. - - @item -v - @cindex @code{-v} (@code{gcc}) - Show commands generated by the @code{gcc} driver. Normally used only for - debugging purposes or if you need to be sure what version of the - compiler you are executing. - - @item -V @var{ver} - @cindex @code{-V} (@code{gcc}) - Execute @var{ver} version of the compiler. This is the @code{gcc} - version, not the GNAT version. - - @item -gnata - Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be - activated. - - @item -gnatA - Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored. - - @item -gnatb - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -gnatc - Check syntax and semantics only (no code generation attempted). - - @item -gnatC - Compress debug information and external symbol name table entries. - - @item -gnatD - Output expanded source files for source level debugging. This switch - also suppress generation of cross-reference information (see -gnatx). - - @item -gnatec@var{path} - Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files}) - - @item -gnatem@var{path} - Specify a mapping file. (see @ref{Units to Sources Mapping Files}) - - @item -gnatE - Full dynamic elaboration checks. - - @item -gnatf - Full errors. Multiple errors per line, all undefined references. - - @item -gnatF - Externals names are folded to all uppercase. - - @item -gnatg - Internal GNAT implementation mode. This should not be used for - applications programs, it is intended only for use by the compiler - and its run-time library. For documentation, see the GNAT sources. - - @item -gnatG - List generated expanded code in source form. - - @item -gnati@var{c} - Identifier character set - (@var{c}=1/2/3/4/8/9/p/f/n/w). - - @item -gnath - Output usage information. The output is written to @file{stdout}. - - @item -gnatk@var{n} - Limit file names to @var{n} (1-999) characters (@code{k} = krunch). - - @item -gnatl - Output full source listing with embedded error messages. - - @item -gnatm@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item -gnatn - Activate inlining across unit boundaries for subprograms for which - pragma @code{inline} is specified. - - @item -gnatN - Activate front end inlining. - - @item -fno-inline - Suppresses all inlining, even if other optimization or inlining switches - are set. - - @item -fstack-check - Activates stack checking. See separate section on stack checking for - details of the use of this option. - - @item -gnato - Enable numeric overflow checking (which is not normally enabled by - default). Not that division by zero is a separate check that is not - controlled by this switch (division by zero checking is on by default). - - @item -gnatp - Suppress all checks. - - @item -gnatq - Don't quit; try semantics, even if parse errors. - - @item -gnatQ - Don't quit; generate @file{ali} and tree files even if illegalities. - - @item -gnatP - Enable polling. This is required on some systems (notably Windows NT) to - obtain asynchronous abort and asynchronous transfer of control capability. - See the description of pragma Polling in the GNAT Reference Manual for - full details. - - @item -gnatR[0/1/2/3][s] - Output representation information for declared types and objects. - - @item -gnats - Syntax check only. - - @item -gnatt - Tree output file to be generated. - - @item -gnatT nnn - Set time slice to specified number of microseconds - - @item -gnatu - List units for this compilation. - - @item -gnatU - Tag all error messages with the unique string "error:" - - @item -gnatv - Verbose mode. Full error output with source lines to @file{stdout}. - - @item -gnatV - Control level of validity checking. See separate section describing - this feature. - - @item -gnatwxxx@var{xxx} - Warning mode where - @var{xxx} is a string of options describing the exact warnings that - are enabled or disabled. See separate section on warning control. - - @item -gnatW@var{e} - Wide character encoding method - (@var{e}=n/h/u/s/e/8). - - @item -gnatx - Suppress generation of cross-reference information. - - @item -gnaty - Enable built-in style checks. See separate section describing this feature. - - @item -gnatz@var{m} - Distribution stub generation and compilation - (@var{m}=r/c for receiver/caller stubs). - - @item -gnat83 - Enforce Ada 83 restrictions. - - @item -pass-exit-codes - Catch exit codes from the compiler and use the most meaningful as - exit status. - @end table - - You may combine a sequence of GNAT switches into a single switch. For - example, the combined switch - - @cindex Combining GNAT switches - @smallexample - -gnatofi3 - @end smallexample - - @noindent - is equivalent to specifying the following sequence of switches: - - @smallexample - -gnato -gnatf -gnati3 - @end smallexample - - @noindent - The following restrictions apply to the combination of switches - in this manner: - - @itemize @bullet - @item - The switch @option{-gnatc} if combined with other switches must come - first in the string. - - @item - The switch @option{-gnats} if combined with other switches must come - first in the string. - - @item - Once a "y" appears in the string (that is a use of the @option{-gnaty} - switch), then all further characters in the switch are interpreted - as style modifiers (see description of @option{-gnaty}). - - @item - Once a "d" appears in the string (that is a use of the @option{-gnatd} - switch), then all further characters in the switch are interpreted - as debug flags (see description of @option{-gnatd}). - - @item - Once a "w" appears in the string (that is a use of the @option{-gnatw} - switch), then all further characters in the switch are interpreted - as warning mode modifiers (see description of @option{-gnatw}). - - @item - Once a "V" appears in the string (that is a use of the @option{-gnatV} - switch), then all further characters in the switch are interpreted - as validity checking options (see description of @option{-gnatV}). - - @end itemize - - @node Output and Error Message Control - @subsection Output and Error Message Control - @findex stderr - - @noindent - The standard default format for error messages is called "brief format." - Brief format messages are written to @file{stderr} (the standard error - file) and have the following form: - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:4:20: ";" should be "is" - @end smallexample - - @noindent - The first integer after the file name is the line number in the file, - and the second integer is the column number within the line. - @code{glide} can parse the error messages - and point to the referenced character. - The following switches provide control over the error message - format: - - @table @code - @item -gnatv - @cindex @option{-gnatv} (@code{gcc}) - @findex stdout - The v stands for verbose. - The effect of this setting is to write long-format error - messages to @file{stdout} (the standard output file. - The same program compiled with the - @option{-gnatv} switch would generate: - - @smallexample - @group - @cartouche - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - @end cartouche - @end group - @end smallexample - - @noindent - The vertical bar indicates the location of the error, and the @samp{>>>} - prefix can be used to search for error messages. When this switch is - used the only source lines output are those with errors. - - @item -gnatl - @cindex @option{-gnatl} (@code{gcc}) - The @code{l} stands for list. - This switch causes a full listing of - the file to be generated. The output might look as follows: - - @smallexample - @group - @cartouche - 1. procedure E is - 2. V : Integer; - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - 5. begin - 6. return Q + Q; - 7. end; - 8. begin - 9. V := X + X; - 10.end E; - @end cartouche - @end group - @end smallexample - - @noindent - @findex stderr - When you specify the @option{-gnatv} or @option{-gnatl} switches and - standard output is redirected, a brief summary is written to - @file{stderr} (standard error) giving the number of error messages and - warning messages generated. - - @item -gnatU - @cindex @option{-gnatU} (@code{gcc}) - This switch forces all error messages to be preceded by the unique - string "error:". This means that error messages take a few more - characters in space, but allows easy searching for and identification - of error messages. - - @item -gnatb - @cindex @option{-gnatb} (@code{gcc}) - The @code{b} stands for brief. - This switch causes GNAT to generate the - brief format error messages to @file{stderr} (the standard error - file) as well as the verbose - format message or full listing (which as usual is written to - @file{stdout} (the standard output file). - - @item -gnatm@var{n} - @cindex @option{-gnatm} (@code{gcc}) - The @code{m} stands for maximum. - @var{n} is a decimal integer in the - range of 1 to 999 and limits the number of error messages to be - generated. For example, using @option{-gnatm2} might yield - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:5:35: missing ".." - fatal error: maximum errors reached - compilation abandoned - @end smallexample - - @item -gnatf - @cindex @option{-gnatf} (@code{gcc}) - @cindex Error messages, suppressing - The @code{f} stands for full. - Normally, the compiler suppresses error messages that are likely to be - redundant. This switch causes all error - messages to be generated. In particular, in the case of - references to undefined variables. If a given variable is referenced - several times, the normal format of messages is - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:7:07: "V" is undefined (more references follow) - @end smallexample - - @noindent - where the parenthetical comment warns that there are additional - references to the variable @code{V}. Compiling the same program with the - @option{-gnatf} switch yields - - @smallexample - e.adb:7:07: "V" is undefined - e.adb:8:07: "V" is undefined - e.adb:8:12: "V" is undefined - e.adb:8:16: "V" is undefined - e.adb:9:07: "V" is undefined - e.adb:9:12: "V" is undefined - @end smallexample - - @item -gnatq - @cindex @option{-gnatq} (@code{gcc}) - The @code{q} stands for quit (really "don't quit"). - In normal operation mode, the compiler first parses the program and - determines if there are any syntax errors. If there are, appropriate - error messages are generated and compilation is immediately terminated. - This switch tells - GNAT to continue with semantic analysis even if syntax errors have been - found. This may enable the detection of more errors in a single run. On - the other hand, the semantic analyzer is more likely to encounter some - internal fatal error when given a syntactically invalid tree. - - @item -gnatQ - In normal operation mode, the @file{ali} file is not generated if any - illegalities are detected in the program. The use of @option{-gnatQ} forces - generation of the @file{ali} file. This file is marked as being in - error, so it cannot be used for binding purposes, but it does contain - reasonably complete cross-reference information, and thus may be useful - for use by tools (e.g. semantic browsing tools or integrated development - environments) that are driven from the @file{ali} file. - - In addition, if @option{-gnatt} is also specified, then the tree file is - generated even if there are illegalities. It may be useful in this case - to also specify @option{-gnatq} to ensure that full semantic processing - occurs. The resulting tree file can be processed by ASIS, for the purpose - of providing partial information about illegal units, but if the error - causes the tree to be badly malformed, then ASIS may crash during the - analysis. - - @end table - - @noindent - In addition to error messages, which correspond to illegalities as defined - in the Ada 95 Reference Manual, the compiler detects two kinds of warning - situations. - - @cindex Warning messages - First, the compiler considers some constructs suspicious and generates a - warning message to alert you to a possible error. Second, if the - compiler detects a situation that is sure to raise an exception at - run time, it generates a warning message. The following shows an example - of warning messages: - @smallexample - @iftex - @leftskip=.2cm - @end iftex - e.adb:4:24: warning: creation of object may raise Storage_Error - e.adb:10:17: warning: static value out of range - e.adb:10:17: warning: "Constraint_Error" will be raised at run time - - @end smallexample - - @noindent - GNAT considers a large number of situations as appropriate - for the generation of warning messages. As always, warnings are not - definite indications of errors. For example, if you do an out-of-range - assignment with the deliberate intention of raising a - @code{Constraint_Error} exception, then the warning that may be - issued does not indicate an error. Some of the situations for which GNAT - issues warnings (at least some of the time) are given in the following - list, which is not necessarily complete. - - @itemize @bullet - @item - Possible infinitely recursive calls - - @item - Out-of-range values being assigned - - @item - Possible order of elaboration problems - - @item - Unreachable code - - @item - Fixed-point type declarations with a null range - - @item - Variables that are never assigned a value - - @item - Variables that are referenced before being initialized - - @item - Task entries with no corresponding accept statement - - @item - Duplicate accepts for the same task entry in a select - - @item - Objects that take too much storage - - @item - Unchecked conversion between types of differing sizes - - @item - Missing return statements along some execution paths in a function - - @item - Incorrect (unrecognized) pragmas - - @item - Incorrect external names - - @item - Allocation from empty storage pool - - @item - Potentially blocking operations in protected types - - @item - Suspicious parenthesization of expressions - - @item - Mismatching bounds in an aggregate - - @item - Attempt to return local value by reference - - @item - Unrecognized pragmas - - @item - Premature instantiation of a generic body - - @item - Attempt to pack aliased components - - @item - Out of bounds array subscripts - - @item - Wrong length on string assignment - - @item - Violations of style rules if style checking is enabled - - @item - Unused with clauses - - @item - Bit_Order usage that does not have any effect - - @item - Compile time biased rounding of floating-point constant - - @item - Standard.Duration used to resolve universal fixed expression - - @item - Dereference of possibly null value - - @item - Declaration that is likely to cause storage error - - @item - Internal GNAT unit with'ed by application unit - - @item - Values known to be out of range at compile time - - @item - Unreferenced labels and variables - - @item - Address overlays that could clobber memory - - @item - Unexpected initialization when address clause present - - @item - Bad alignment for address clause - - @item - Useless type conversions - - @item - Redundant assignment statements - - @item - Accidental hiding of name by child unit - - @item - Unreachable code - - @item - Access before elaboration detected at compile time - - @item - A range in a @code{for} loop that is known to be null or might be null - - @end itemize - - @noindent - The following switches are available to control the handling of - warning messages: - - @table @code - @item -gnatwa (activate all optional errors) - @cindex @option{-gnatwa} (@code{gcc}) - This switch activates most optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. The warnings that are not turned on by this - switch are @option{-gnatwb} (biased rounding), - @option{-gnatwd} (implicit dereferencing), - and @option{-gnatwh} (hiding). All other optional warnings are - turned on. - - @item -gnatwA (suppress all optional errors) - @cindex @option{-gnatwA} (@code{gcc}) - This switch suppresses all optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. - - @item -gnatwb (activate warnings on biased rounding) - @cindex @option{-gnatwb} (@code{gcc}) - @cindex Rounding, biased - @cindex Biased rounding - If a static floating-point expression has a value that is exactly half - way between two adjacent machine numbers, then the rules of Ada - (Ada Reference Manual, section 4.9(38)) require that this rounding - be done away from zero, even if the normal unbiased rounding rules - at run time would require rounding towards zero. This warning message - alerts you to such instances where compile-time rounding and run-time - rounding are not equivalent. If it is important to get proper run-time - rounding, then you can force this by making one of the operands into - a variable. The default is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwB (suppress warnings on biased rounding) - @cindex @option{-gnatwB} (@code{gcc}) - This switch disables warnings on biased rounding. - - @item -gnatwc (activate warnings on conditionals) - @cindex @option{-gnatwc} (@code{gcc}) - @cindex Conditionals, constant - This switch activates warnings for conditional expressions used in - tests that are known to be True or False at compile time. The default - is that such warnings are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwC (suppress warnings on conditionals) - @cindex @option{-gnatwC} (@code{gcc}) - This switch suppresses warnings for conditional expressions used in - tests that are known to be True or False at compile time. - - @item -gnatwd (activate warnings on implicit dereferencing) - @cindex @option{-gnatwd} (@code{gcc}) - If this switch is set, then the use of a prefix of an access type - in an indexed component, slice, or selected component without an - explicit @code{.all} will generate a warning. With this warning - enabled, access checks occur only at points where an explicit - @code{.all} appears in the source code (assuming no warnings are - generated as a result of this switch). The default is that such - warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwD (suppress warnings on implicit dereferencing) - @cindex @option{-gnatwD} (@code{gcc}) - @cindex Implicit dereferencing - @cindex Dereferencing, implicit - This switch suppresses warnings for implicit deferences in - indexed components, slices, and selected components. - - @item -gnatwe (treat warnings as errors) - @cindex @option{-gnatwe} (@code{gcc}) - @cindex Warnings, treat as error - This switch causes warning messages to be treated as errors. - The warning string still appears, but the warning messages are counted - as errors, and prevent the generation of an object file. - - @item -gnatwf (activate warnings on unreferenced formals) - @cindex @option{-gnatwf} (@code{gcc}) - @cindex Formals, unreferenced - This switch causes a warning to be generated if a formal parameter - is not referenced in the body of the subprogram. This warning can - also be turned on using @option{-gnatwa} or @option{-gnatwu}. - - @item -gnatwF (suppress warnings on unreferenced formals) - @cindex @option{-gnatwF} (@code{gcc}) - This switch suppresses warnings for unreferenced formal - parameters. Note that the - combination @option{-gnatwu} followed by @option{-gnatwF} has the - effect of warning on unreferenced entities other than subprogram - formals. - - @item -gnatwh (activate warnings on hiding) - @cindex @option{-gnatwh} (@code{gcc}) - @cindex Hiding of Declarations - This switch activates warnings on hiding declarations. - A declaration is considered hiding - if it is for a non-overloadable entity, and it declares an entity with the - same name as some other entity that is directly or use-visible. The default - is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of this warning option. - - @item -gnatwH (suppress warnings on hiding) - @cindex @option{-gnatwH} (@code{gcc}) - This switch suppresses warnings on hiding declarations. - - @item -gnatwi (activate warnings on implementation units). - @cindex @option{-gnatwi} (@code{gcc}) - This switch activates warnings for a @code{with} of an internal GNAT - implementation unit, defined as any unit from the @code{Ada}, - @code{Interfaces}, @code{GNAT}, - or @code{System} - hierarchies that is not - documented in either the Ada Reference Manual or the GNAT - Programmer's Reference Manual. Such units are intended only - for internal implementation purposes and should not be @code{with}'ed - by user programs. The default is that such warnings are generated - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwI (disable warnings on implementation units). - @cindex @option{-gnatwI} (@code{gcc}) - This switch disables warnings for a @code{with} of an internal GNAT - implementation unit. - - @item -gnatwl (activate warnings on elaboration pragmas) - @cindex @option{-gnatwl} (@code{gcc}) - @cindex Elaboration, warnings - This switch activates warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. The default is that such warnings - are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwL (suppress warnings on elaboration pragmas) - @cindex @option{-gnatwL} (@code{gcc}) - This switch suppresses warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. - - @item -gnatwo (activate warnings on address clause overlays) - @cindex @option{-gnatwo} (@code{gcc}) - @cindex Address Clauses, warnings - This switch activates warnings for possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. The default is that such warnings are generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwO (suppress warnings on address clause overlays) - @cindex @option{-gnatwO} (@code{gcc}) - This switch suppresses warnings on possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. - - @item -gnatwp (activate warnings on ineffective pragma Inlines) - @cindex @option{-gnatwp} (@code{gcc}) - @cindex Inlining, warnings - This switch activates warnings for failure of front end inlining - (activated by @option{-gnatN}) to inline a particular call. There are - many reasons for not being able to inline a call, including most - commonly that the call is too complex to inline. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwP (suppress warnings on ineffective pragma Inlines) - @cindex @option{-gnatwP} (@code{gcc}) - This switch suppresses warnings on ineffective pragma Inlines. If the - inlining mechanism cannot inline a call, it will simply ignore the - request silently. - - @item -gnatwr (activate warnings on redundant constructs) - @cindex @option{-gnatwr} (@code{gcc}) - This switch activates warnings for redundant constructs. The following - is the current list of constructs regarded as redundant: - This warning can also be turned on using @option{-gnatwa}. - - @itemize @bullet - @item - Assignment of an item to itself. - @item - Type conversion that converts an expression to its own type. - @item - Use of the attribute @code{Base} where @code{typ'Base} is the same - as @code{typ}. - @item - Use of pragma @code{Pack} when all components are placed by a record - representation clause. - @end itemize - - @item -gnatwR (suppress warnings on redundant constructs) - @cindex @option{-gnatwR} (@code{gcc}) - This switch suppresses warnings for redundant constructs. - - @item -gnatws (suppress all warnings) - @cindex @option{-gnatws} (@code{gcc}) - This switch completely suppresses the - output of all warning messages from the GNAT front end. - Note that it does not suppress warnings from the @code{gcc} back end. - To suppress these back end warnings as well, use the switch @code{-w} - in addition to @option{-gnatws}. - - @item -gnatwu (activate warnings on unused entities) - @cindex @option{-gnatwu} (@code{gcc}) - This switch activates warnings to be generated for entities that - are defined but not referenced, and for units that are @code{with}'ed - and not - referenced. In the case of packages, a warning is also generated if - no entities in the package are referenced. This means that if the package - is referenced but the only references are in @code{use} - clauses or @code{renames} - declarations, a warning is still generated. A warning is also generated - for a generic package that is @code{with}'ed but never instantiated. - In the case where a package or subprogram body is compiled, and there - is a @code{with} on the corresponding spec - that is only referenced in the body, - a warning is also generated, noting that the - @code{with} can be moved to the body. The default is that - such warnings are not generated. - This switch also activates warnings on unreferenced formals - (it is includes the effect of @option{-gnatwf}). - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwU (suppress warnings on unused entities) - @cindex @option{-gnatwU} (@code{gcc}) - This switch suppresses warnings for unused entities and packages. - It also turns off warnings on unreferenced formals (and thus includes - the effect of @option{-gnatwF}). - - @noindent - A string of warning parameters can be used in the same parameter. For example: - - @smallexample - -gnatwaLe - @end smallexample - - @noindent - Would turn on all optional warnings except for elaboration pragma warnings, - and also specify that warnings should be treated as errors. - - @item -w - @cindex @code{-w} - This switch suppresses warnings from the @code{gcc} backend. It may be - used in conjunction with @option{-gnatws} to ensure that all warnings - are suppressed during the entire compilation process. - - @end table - - @node Debugging and Assertion Control - @subsection Debugging and Assertion Control - - @table @code - @item -gnata - @cindex @option{-gnata} (@code{gcc}) - @findex Assert - @findex Debug - @cindex Assertions - - @noindent - The pragmas @code{Assert} and @code{Debug} normally have no effect and - are ignored. This switch, where @samp{a} stands for assert, causes - @code{Assert} and @code{Debug} pragmas to be activated. - - The pragmas have the form: - - @smallexample - @group - @cartouche - @b{pragma} Assert (@var{Boolean-expression} [, - @var{static-string-expression}]) - @b{pragma} Debug (@var{procedure call}) - @end cartouche - @end group - @end smallexample - - @noindent - The @code{Assert} pragma causes @var{Boolean-expression} to be tested. - If the result is @code{True}, the pragma has no effect (other than - possible side effects from evaluating the expression). If the result is - @code{False}, the exception @code{Assert_Failure} declared in the package - @code{System.Assertions} is - raised (passing @var{static-string-expression}, if present, as the - message associated with the exception). If no string expression is - given the default is a string giving the file name and line number - of the pragma. - - The @code{Debug} pragma causes @var{procedure} to be called. Note that - @code{pragma Debug} may appear within a declaration sequence, allowing - debugging procedures to be called between declarations. - - @end table - - @node Validity Checking - @subsection Validity Checking - @findex Validity Checking - - @noindent - The Ada 95 Reference Manual has specific requirements for checking - for invalid values. In particular, RM 13.9.1 requires that the - evaluation of invalid values (for example from unchecked conversions), - not result in erroneous execution. In GNAT, the result of such an - evaluation in normal default mode is to either use the value - unmodified, or to raise Constraint_Error in those cases where use - of the unmodified value would cause erroneous execution. The cases - where unmodified values might lead to erroneous execution are case - statements (where a wild jump might result from an invalid value), - and subscripts on the left hand side (where memory corruption could - occur as a result of an invalid value). - - The @option{-gnatVx} switch allows more control over the validity checking - mode. The @code{x} argument here is a string of letters which control which - validity checks are performed in addition to the default checks described - above. - - @itemize @bullet - @item - @option{-gnatVc} Validity checks for copies - - The right hand side of assignments, and the initializing values of - object declarations are validity checked. - - @item - @option{-gnatVd} Default (RM) validity checks - - Some validity checks are done by default following normal Ada semantics - (RM 13.9.1 (9-11)). - A check is done in case statements that the expression is within the range - of the subtype. If it is not, Constraint_Error is raised. - For assignments to array components, a check is done that the expression used - as index is within the range. If it is not, Constraint_Error is raised. - Both these validity checks may be turned off using switch @option{-gnatVD}. - They are turned on by default. If @option{-gnatVD} is specified, a subsequent - switch @option{-gnatVd} will leave the checks turned on. - Switch @option{-gnatVD} should be used only if you are sure that all such - expressions have valid values. If you use this switch and invalid values - are present, then the program is erroneous, and wild jumps or memory - overwriting may occur. - - @item - @option{-gnatVi} Validity checks for @code{in} mode parameters - - Arguments for parameters of mode @code{in} are validity checked in function - and procedure calls at the point of call. - - @item - @option{-gnatVm} Validity checks for @code{in out} mode parameters - - Arguments for parameters of mode @code{in out} are validity checked in - procedure calls at the point of call. The @code{'m'} here stands for - modify, since this concerns parameters that can be modified by the call. - Note that there is no specific option to test @code{out} parameters, - but any reference within the subprogram will be tested in the usual - manner, and if an invalid value is copied back, any reference to it - will be subject to validity checking. - - @item - @option{-gnatVo} Validity checks for operator and attribute operands - - Arguments for predefined operators and attributes are validity checked. - This includes all operators in package @code{Standard}, - the shift operators defined as intrinsic in package @code{Interfaces} - and operands for attributes such as @code{Pos}. - - @item - @option{-gnatVr} Validity checks for function returns - - The expression in @code{return} statements in functions is validity - checked. - - @item - @option{-gnatVs} Validity checks for subscripts - - All subscripts expressions are checked for validity, whether they appear - on the right side or left side (in default mode only left side subscripts - are validity checked). - - @item - @option{-gnatVt} Validity checks for tests - - Expressions used as conditions in @code{if}, @code{while} or @code{exit} - statements are checked, as well as guard expressions in entry calls. - - @item - @option{-gnatVf} Validity checks for floating-point values - - In the absence of this switch, validity checking occurs only for discrete - values. If @option{-gnatVf} is specified, then validity checking also applies - for floating-point values, and NaN's and infinities are considered invalid, - as well as out of range values for constrained types. Note that this means - that standard @code{IEEE} infinity mode is not allowed. The exact contexts - in which floating-point values are checked depends on the setting of other - options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does - not matter) specifies that floating-point parameters of mode @code{in} should - be validity checked. - - @item - @option{-gnatVa} All validity checks - - All the above validity checks are turned on. That is @option{-gnatVa} is - equivalent to @code{gnatVcdfimorst}. - - @item - @option{-gnatVn} No validity checks - - This switch turns off all validity checking, including the default checking - for case statements and left hand side subscripts. Note that the use of - the switch @option{-gnatp} supresses all run-time checks, including - validity checks, and thus implies @option{-gnatVn}. - - @end itemize - - The @option{-gnatV} switch may be followed by a string of letters to turn on - a series of validity checking options. For example, @option{-gnatVcr} specifies - that in addition to the default validity checking, copies and function - return expressions be validity checked. In order to make it easier to specify - a set of options, the upper case letters @code{CDFIMORST} may be used to turn - off the corresponding lower case option, so for example @option{-gnatVaM} turns - on all validity checking options except for checking of @code{in out} - procedure arguments. - - The specification of additional validity checking generates extra code (and - in the case of @option{-gnatva} the code expansion can be substantial. However, - these additional checks can be very useful in smoking out cases of - uninitialized variables, incorrect use of unchecked conversion, and other - errors leading to invalid values. The use of pragma @code{Initialize_Scalars} - is useful in conjunction with the extra validity checking, since this - ensures that wherever possible uninitialized variables have invalid values. - - See also the pragma @code{Validity_Checks} which allows modification of - the validity checking mode at the program source level, and also allows for - temporary disabling of validity checks. - - @node Style Checking - @subsection Style Checking - @findex Style checking - - @noindent - The -gnaty@var{x} switch causes the compiler to - enforce specified style rules. A limited set of style rules has been used - in writing the GNAT sources themselves. This switch allows user programs - to activate all or some of these checks. If the source program fails a - specified style check, an appropriate warning message is given, preceded by - the character sequence "(style)". - The string @var{x} is a sequence of letters or digits - indicating the particular style - checks to be performed. The following checks are defined: - - @table @code - @item 1-9 (specify indentation level) - If a digit from 1-9 appears in the string after @option{-gnaty} then proper - indentation is checked, with the digit indicating the indentation level - required. The general style of required indentation is as specified by - the examples in the Ada Reference Manual. Full line comments must be - aligned with the @code{--} starting on a column that is a multiple of - the alignment level. - - @item a (check attribute casing) - If the letter a appears in the string after @option{-gnaty} then - attribute names, including the case of keywords such as @code{digits} - used as attributes names, must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item b (blanks not allowed at statement end) - If the letter b appears in the string after @option{-gnaty} then - trailing blanks are not allowed at the end of statements. The purpose of this - rule, together with h (no horizontal tabs), is to enforce a canonical format - for the use of blanks to separate source tokens. - - @item c (check comments) - If the letter c appears in the string after @option{-gnaty} then - comments must meet the following set of rules: - - @itemize @bullet - - @item - The "--" that starts the column must either start in column one, or else - at least one blank must precede this sequence. - - @item - Comments that follow other tokens on a line must have at least one blank - following the "--" at the start of the comment. - - @item - Full line comments must have two blanks following the "--" that starts - the comment, with the following exceptions. - - @item - A line consisting only of the "--" characters, possibly preceded by blanks - is permitted. - - @item - A comment starting with "--x" where x is a special character is permitted. - This alows proper processing of the output generated by specialized tools - including @code{gnatprep} (where --! is used) and the SPARK annnotation - language (where --# is used). For the purposes of this rule, a special - character is defined as being in one of the ASCII ranges - 16#21#..16#2F# or 16#3A#..16#3F#. - - @item - A line consisting entirely of minus signs, possibly preceded by blanks, is - permitted. This allows the construction of box comments where lines of minus - signs are used to form the top and bottom of the box. - - @item - If a comment starts and ends with "--" is permitted as long as at least - one blank follows the initial "--". Together with the preceding rule, - this allows the construction of box comments, as shown in the following - example: - @smallexample - --------------------------- - -- This is a box comment -- - -- with two text lines. -- - --------------------------- - @end smallexample - @end itemize - - @item e (check end/exit labels) - If the letter e appears in the string after @option{-gnaty} then - optional labels on @code{end} statements ending subprograms and on - @code{exit} statements exiting named loops, are required to be present. - - @item f (no form feeds or vertical tabs) - If the letter f appears in the string after @option{-gnaty} then - neither form feeds nor vertical tab characters are not permitted - in the source text. - - @item h (no horizontal tabs) - If the letter h appears in the string after @option{-gnaty} then - horizontal tab characters are not permitted in the source text. - Together with the b (no blanks at end of line) check, this - enforces a canonical form for the use of blanks to separate - source tokens. - - @item i (check if-then layout) - If the letter i appears in the string after @option{-gnaty}, - then the keyword @code{then} must appear either on the same - line as corresponding @code{if}, or on a line on its own, lined - up under the @code{if} with at least one non-blank line in between - containing all or part of the condition to be tested. - - @item k (check keyword casing) - If the letter k appears in the string after @option{-gnaty} then - all keywords must be in lower case (with the exception of keywords - such as @code{digits} used as attribute names to which this check - does not apply). - - @item l (check layout) - If the letter l appears in the string after @option{-gnaty} then - layout of statement and declaration constructs must follow the - recommendations in the Ada Reference Manual, as indicated by the - form of the syntax rules. For example an @code{else} keyword must - be lined up with the corresponding @code{if} keyword. - - There are two respects in which the style rule enforced by this check - option are more liberal than those in the Ada Reference Manual. First - in the case of record declarations, it is permissible to put the - @code{record} keyword on the same line as the @code{type} keyword, and - then the @code{end} in @code{end record} must line up under @code{type}. - For example, either of the following two layouts is acceptable: - - @smallexample - @group - @cartouche - @b{type} q @b{is record} - a : integer; - b : integer; - @b{end record}; - - @b{type} q @b{is} - @b{record} - a : integer; - b : integer; - @b{end record}; - @end cartouche - @end group - @end smallexample - - @noindent - Second, in the case of a block statement, a permitted alternative - is to put the block label on the same line as the @code{declare} or - @code{begin} keyword, and then line the @code{end} keyword up under - the block label. For example both the following are permitted: - - @smallexample - @group - @cartouche - Block : @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - - Block : - @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - @end cartouche - @end group - @end smallexample - - @noindent - The same alternative format is allowed for loops. For example, both of - the following are permitted: - - @smallexample - @group - @cartouche - Clear : @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - - Clear : - @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - @end cartouche - @end group - @end smallexample - - @item m (check maximum line length) - If the letter m appears in the string after @option{-gnaty} - then the length of source lines must not exceed 79 characters, including - any trailing blanks. The value of 79 allows convenient display on an - 80 character wide device or window, allowing for possible special - treatment of 80 character lines. - - @item Mnnn (set maximum line length) - If the sequence Mnnn, where nnn is a decimal number, appears in - the string after @option{-gnaty} then the length of lines must not exceed the - given value. - - @item n (check casing of entities in Standard) - If the letter n appears in the string - after @option{-gnaty} then any identifier from Standard must be cased - to match the presentation in the Ada Reference Manual (for example, - @code{Integer} and @code{ASCII.NUL}). - - @item o (check order of subprogram bodies) - If the letter o appears in the string - after @option{-gnaty} then all subprogram bodies in a given scope - (e.g. a package body) must be in alphabetical order. The ordering - rule uses normal Ada rules for comparing strings, ignoring casing - of letters, except that if there is a trailing numeric suffix, then - the value of this suffix is used in the ordering (e.g. Junk2 comes - before Junk10). - - @item p (check pragma casing) - If the letter p appears in the string after @option{-gnaty} then - pragma names must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item r (check references) - If the letter r appears in the string after @option{-gnaty} - then all identifier references must be cased in the same way as the - corresponding declaration. No specific casing style is imposed on - identifiers. The only requirement is for consistency of references - with declarations. - - @item s (check separate specs) - If the letter s appears in the string after @option{-gnaty} then - separate declarations ("specs") are required for subprograms (a - body is not allowed to serve as its own declaration). The only - exception is that parameterless library level procedures are - not required to have a separate declaration. This exception covers - the most frequent form of main program procedures. - - @item t (check token spacing) - If the letter t appears in the string after @option{-gnaty} then - the following token spacing rules are enforced: - - @itemize @bullet - - @item - The keywords @code{abs} and @code{not} must be followed by a space. - - @item - The token @code{=>} must be surrounded by spaces. - - @item - The token @code{<>} must be preceded by a space or a left parenthesis. - - @item - Binary operators other than @code{**} must be surrounded by spaces. - There is no restriction on the layout of the @code{**} binary operator. - - @item - Colon must be surrounded by spaces. - - @item - Colon-equal (assignment) must be surrounded by spaces. - - @item - Comma must be the first non-blank character on the line, or be - immediately preceded by a non-blank character, and must be followed - by a space. - - @item - If the token preceding a left paren ends with a letter or digit, then - a space must separate the two tokens. - - @item - A right parenthesis must either be the first non-blank character on - a line, or it must be preceded by a non-blank character. - - @item - A semicolon must not be preceded by a space, and must not be followed by - a non-blank character. - - @item - A unary plus or minus may not be followed by a space. - - @item - A vertical bar must be surrounded by spaces. - @end itemize - - @noindent - In the above rules, appearing in column one is always permitted, that is, - counts as meeting either a requirement for a required preceding space, - or as meeting a requirement for no preceding space. - - Appearing at the end of a line is also always permitted, that is, counts - as meeting either a requirement for a following space, or as meeting - a requirement for no following space. - - @end table - - @noindent - If any of these style rules is violated, a message is generated giving - details on the violation. The initial characters of such messages are - always "(style)". Note that these messages are treated as warning - messages, so they normally do not prevent the generation of an object - file. The @option{-gnatwe} switch can be used to treat warning messages, - including style messages, as fatal errors. - - @noindent - The switch - @option{-gnaty} on its own (that is not followed by any letters or digits), - is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking - options are enabled with - the exception of -gnatyo, - with an indentation level of 3. This is the standard - checking option that is used for the GNAT sources. - - @node Run-Time Checks - @subsection Run-Time Checks - @cindex Division by zero - @cindex Access before elaboration - @cindex Checks, division by zero - @cindex Checks, access before elaboration - - @noindent - If you compile with the default options, GNAT will insert many run-time - checks into the compiled code, including code that performs range - checking against constraints, but not arithmetic overflow checking for - integer operations (including division by zero) or checks for access - before elaboration on subprogram calls. All other run-time checks, as - required by the Ada 95 Reference Manual, are generated by default. - The following @code{gcc} switches refine this default behavior: - - @table @code - @item -gnatp - @cindex @option{-gnatp} (@code{gcc}) - @cindex Suppressing checks - @cindex Checks, suppressing - @findex Suppress - Suppress all run-time checks as though @code{pragma Suppress (all_checks}) - had been present in the source. Validity checks are also suppressed (in - other words @option{-gnatp} also implies @option{-gnatVn}. - Use this switch to improve the performance - of the code at the expense of safety in the presence of invalid data or - program bugs. - - @item -gnato - @cindex @option{-gnato} (@code{gcc}) - @cindex Overflow checks - @cindex Check, overflow - Enables overflow checking for integer operations. - This causes GNAT to generate slower and larger executable - programs by adding code to check for overflow (resulting in raising - @code{Constraint_Error} as required by standard Ada - semantics). These overflow checks correspond to situations in which - the true value of the result of an operation may be outside the base - range of the result type. The following example shows the distinction: - - @smallexample - X1 : Integer := Integer'Last; - X2 : Integer range 1 .. 5 := 5; - ... - X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error - X2 := X2 + 1; -- range check, @option{-gnato} has no effect here - @end smallexample - - @noindent - Here the first addition results in a value that is outside the base range - of Integer, and hence requires an overflow check for detection of the - constraint error. The second increment operation results in a violation - of the explicit range constraint, and such range checks are always - performed. Basically the compiler can assume that in the absence of - the @option{-gnato} switch that any value of type @code{xxx} is - in range of the base type of @code{xxx}. - - @findex Machine_Overflows - Note that the @option{-gnato} switch does not affect the code generated - for any floating-point operations; it applies only to integer - semantics). - For floating-point, GNAT has the @code{Machine_Overflows} - attribute set to @code{False} and the normal mode of operation is to - generate IEEE NaN and infinite values on overflow or invalid operations - (such as dividing 0.0 by 0.0). - - The reason that we distinguish overflow checking from other kinds of - range constraint checking is that a failure of an overflow check can - generate an incorrect value, but cannot cause erroneous behavior. This - is unlike the situation with a constraint check on an array subscript, - where failure to perform the check can result in random memory description, - or the range check on a case statement, where failure to perform the check - can cause a wild jump. - - Note again that @option{-gnato} is off by default, so overflow checking is - not performed in default mode. This means that out of the box, with the - default settings, GNAT does not do all the checks expected from the - language description in the Ada Reference Manual. If you want all constraint - checks to be performed, as described in this Manual, then you must - explicitly use the -gnato switch either on the @code{gnatmake} or - @code{gcc} command. - - @item -gnatE - @cindex @option{-gnatE} (@code{gcc}) - @cindex Elaboration checks - @cindex Check, elaboration - Enables dynamic checks for access-before-elaboration - on subprogram calls and generic instantiations. - For full details of the effect and use of this switch, - @xref{Compiling Using gcc}. - @end table - - @findex Unsuppress - @noindent - The setting of these switches only controls the default setting of the - checks. You may modify them using either @code{Suppress} (to remove - checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in - the program source. - - @node Stack Overflow Checking - @subsection Stack Overflow Checking - @cindex Stack Overflow Checking - @cindex -fstack-check - - @noindent - For most operating systems, @code{gcc} does not perform stack overflow - checking by default. This means that if the main environment task or - some other task exceeds the available stack space, then unpredictable - behavior will occur. - - To activate stack checking, compile all units with the gcc option - @code{-fstack-check}. For example: - - @smallexample - gcc -c -fstack-check package1.adb - @end smallexample - - @noindent - Units compiled with this option will generate extra instructions to check - that any use of the stack (for procedure calls or for declaring local - variables in declare blocks) do not exceed the available stack space. - If the space is exceeded, then a @code{Storage_Error} exception is raised. - - For declared tasks, the stack size is always controlled by the size - given in an applicable @code{Storage_Size} pragma (or is set to - the default size if no pragma is used. - - For the environment task, the stack size depends on - system defaults and is unknown to the compiler. The stack - may even dynamically grow on some systems, precluding the - normal Ada semantics for stack overflow. In the worst case, - unbounded stack usage, causes unbounded stack expansion - resulting in the system running out of virtual memory. - - The stack checking may still work correctly if a fixed - size stack is allocated, but this cannot be guaranteed. - To ensure that a clean exception is signalled for stack - overflow, set the environment variable - @code{GNAT_STACK_LIMIT} to indicate the maximum - stack area that can be used, as in: - @cindex GNAT_STACK_LIMIT - - @smallexample - SET GNAT_STACK_LIMIT 1600 - @end smallexample - - @noindent - The limit is given in kilobytes, so the above declaration would - set the stack limit of the environment task to 1.6 megabytes. - Note that the only purpose of this usage is to limit the amount - of stack used by the environment task. If it is necessary to - increase the amount of stack for the environment task, then this - is an operating systems issue, and must be addressed with the - appropriate operating systems commands. - - @node Run-Time Control - @subsection Run-Time Control - - @table @code - @item -gnatT nnn - @cindex @option{-gnatT} (@code{gcc}) - @cindex Time Slicing - - @noindent - The @code{gnatT} switch can be used to specify the time-slicing value - to be used for task switching between equal priority tasks. The value - @code{nnn} is given in microseconds as a decimal integer. - - Setting the time-slicing value is only effective if the underlying thread - control system can accommodate time slicing. Check the documentation of - your operating system for details. Note that the time-slicing value can - also be set by use of pragma @code{Time_Slice} or by use of the - @code{t} switch in the gnatbind step. The pragma overrides a command - line argument if both are present, and the @code{t} switch for gnatbind - overrides both the pragma and the @code{gcc} command line switch. - @end table - - @node Using gcc for Syntax Checking - @subsection Using @code{gcc} for Syntax Checking - @table @code - @item -gnats - @cindex @option{-gnats} (@code{gcc}) - - @noindent - The @code{s} stands for syntax. - - Run GNAT in syntax checking only mode. For - example, the command - - @smallexample - $ gcc -c -gnats x.adb - @end smallexample - - @noindent - compiles file @file{x.adb} in syntax-check-only mode. You can check a - series of files in a single command - , and can use wild cards to specify such a group of files. - Note that you must specify the @code{-c} (compile - only) flag in addition to the @option{-gnats} flag. - . - - You may use other switches in conjunction with @option{-gnats}. In - particular, @option{-gnatl} and @option{-gnatv} are useful to control the - format of any generated error messages. - - The output is simply the error messages, if any. No object file or ALI - file is generated by a syntax-only compilation. Also, no units other - than the one specified are accessed. For example, if a unit @code{X} - @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax - check only mode does not access the source file containing unit - @code{Y}. - - @cindex Multiple units, syntax checking - Normally, GNAT allows only a single unit in a source file. However, this - restriction does not apply in syntax-check-only mode, and it is possible - to check a file containing multiple compilation units concatenated - together. This is primarily used by the @code{gnatchop} utility - (@pxref{Renaming Files Using gnatchop}). - @end table - - @node Using gcc for Semantic Checking - @subsection Using @code{gcc} for Semantic Checking - @table @code - @item -gnatc - @cindex @option{-gnatc} (@code{gcc}) - - @noindent - The @code{c} stands for check. - Causes the compiler to operate in semantic check mode, - with full checking for all illegalities specified in the - Ada 95 Reference Manual, but without generation of any object code - (no object file is generated). - - Because dependent files must be accessed, you must follow the GNAT - semantic restrictions on file structuring to operate in this mode: - - @itemize @bullet - @item - The needed source files must be accessible - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item - Each file must contain only one compilation unit. - - @item - The file name and unit name must match (@pxref{File Naming Rules}). - @end itemize - - The output consists of error messages as appropriate. No object file is - generated. An @file{ALI} file is generated for use in the context of - cross-reference tools, but this file is marked as not being suitable - for binding (since no object file is generated). - The checking corresponds exactly to the notion of - legality in the Ada 95 Reference Manual. - - Any unit can be compiled in semantics-checking-only mode, including - units that would not normally be compiled (subunits, - and specifications where a separate body is present). - @end table - - @node Compiling Ada 83 Programs - @subsection Compiling Ada 83 Programs - @table @code - @cindex Ada 83 compatibility - @item -gnat83 - @cindex @option{-gnat83} (@code{gcc}) - @cindex ACVC, Ada 83 tests - - @noindent - Although GNAT is primarily an Ada 95 compiler, it accepts this switch to - specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify - this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics - where this can be done easily. - It is not possible to guarantee this switch does a perfect - job; for example, some subtle tests, such as are - found in earlier ACVC tests (that have been removed from the ACVC suite for Ada - 95), may not compile correctly. However, for most purposes, using - this switch should help to ensure that programs that compile correctly - under the @option{-gnat83} switch can be ported easily to an Ada 83 - compiler. This is the main use of the switch. - - With few exceptions (most notably the need to use @code{<>} on - @cindex Generic formal parameters - unconstrained generic formal parameters, the use of the new Ada 95 - keywords, and the use of packages - with optional bodies), it is not necessary to use the - @option{-gnat83} switch when compiling Ada 83 programs, because, with rare - exceptions, Ada 95 is upwardly compatible with Ada 83. This - means that a correct Ada 83 program is usually also a correct Ada 95 - program. - - @end table - - @node Character Set Control - @subsection Character Set Control - @table @code - @item -gnati@var{c} - @cindex @code{-gnati} (@code{gcc}) - - @noindent - Normally GNAT recognizes the Latin-1 character set in source program - identifiers, as described in the Ada 95 Reference Manual. - This switch causes - GNAT to recognize alternate character sets in identifiers. @var{c} is a - single character indicating the character set, as follows: - - @table @code - @item 1 - Latin-1 identifiers - - @item 2 - Latin-2 letters allowed in identifiers - - @item 3 - Latin-3 letters allowed in identifiers - - @item 4 - Latin-4 letters allowed in identifiers - - @item 5 - Latin-5 (Cyrillic) letters allowed in identifiers - - @item 9 - Latin-9 letters allowed in identifiers - - @item p - IBM PC letters (code page 437) allowed in identifiers - - @item 8 - IBM PC letters (code page 850) allowed in identifiers - - @item f - Full upper-half codes allowed in identifiers - - @item n - No upper-half codes allowed in identifiers - - @item w - Wide-character codes (that is, codes greater than 255) - allowed in identifiers - @end table - - @xref{Foreign Language Representation}, for full details on the - implementation of these character sets. - - @item -gnatW@var{e} - @cindex @code{-gnatW} (@code{gcc}) - Specify the method of encoding for wide characters. - @var{e} is one of the following: - - @table @code - - @item h - Hex encoding (brackets coding also recognized) - - @item u - Upper half encoding (brackets encoding also recognized) - - @item s - Shift/JIS encoding (brackets encoding also recognized) - - @item e - EUC encoding (brackets encoding also recognized) - - @item 8 - UTF-8 encoding (brackets encoding also recognized) - - @item b - Brackets encoding only (default value) - @end table - For full details on the these encoding - methods see @xref{Wide Character Encodings}. - Note that brackets coding is always accepted, even if one of the other - options is specified, so for example @option{-gnatW8} specifies that both - brackets and @code{UTF-8} encodings will be recognized. The units that are - with'ed directly or indirectly will be scanned using the specified - representation scheme, and so if one of the non-brackets scheme is - used, it must be used consistently throughout the program. However, - since brackets encoding is always recognized, it may be conveniently - used in standard libraries, allowing these libraries to be used with - any of the available coding schemes. - scheme. If no @option{-gnatW?} parameter is present, then the default - representation is Brackets encoding only. - - Note that the wide character representation that is specified (explicitly - or by default) for the main program also acts as the default encoding used - for Wide_Text_IO files if not specifically overridden by a WCEM form - parameter. - - @end table - @node File Naming Control - @subsection File Naming Control - - @table @code - @item -gnatk@var{n} - @cindex @option{-gnatk} (@code{gcc}) - Activates file name "krunching". @var{n}, a decimal integer in the range - 1-999, indicates the maximum allowable length of a file name (not - including the @file{.ads} or @file{.adb} extension). The default is not - to enable file name krunching. - - For the source file naming rules, @xref{File Naming Rules}. - @end table - - @node Subprogram Inlining Control - @subsection Subprogram Inlining Control - - @table @code - @item -gnatn - @cindex @option{-gnatn} (@code{gcc}) - The @code{n} here is intended to suggest the first syllable of the - word "inline". - GNAT recognizes and processes @code{Inline} pragmas. However, for the - inlining to actually occur, optimization must be enabled. To enable - inlining across unit boundaries, this is, inlining a call in one unit of - a subprogram declared in a @code{with}'ed unit, you must also specify - this switch. - In the absence of this switch, GNAT does not attempt - inlining across units and does not need to access the bodies of - subprograms for which @code{pragma Inline} is specified if they are not - in the current unit. - - If you specify this switch the compiler will access these bodies, - creating an extra source dependency for the resulting object file, and - where possible, the call will be inlined. - For further details on when inlining is possible - see @xref{Inlining of Subprograms}. - - @item -gnatN - @cindex @option{-gnatN} (@code{gcc}) - The front end inlining activated by this switch is generally more extensive, - and quite often more effective than the standard @option{-gnatn} inlining mode. - It will also generate additional dependencies. - - @end table - - @node Auxiliary Output Control - @subsection Auxiliary Output Control - - @table @code - @item -gnatt - @cindex @option{-gnatt} (@code{gcc}) - @cindex Writing internal trees - @cindex Internal trees, writing to file - Causes GNAT to write the internal tree for a unit to a file (with the - extension @file{.adt}. - This not normally required, but is used by separate analysis tools. - Typically - these tools do the necessary compilations automatically, so you should - not have to specify this switch in normal operation. - - @item -gnatu - @cindex @option{-gnatu} (@code{gcc}) - Print a list of units required by this compilation on @file{stdout}. - The listing includes all units on which the unit being compiled depends - either directly or indirectly. - - @item -pass-exit-codes - @cindex @code{-pass-exit-codes} (@code{gcc}) - If this switch is not used, the exit code returned by @code{gcc} when - compiling multiple files indicates whether all source files have - been successfully used to generate object files or not. - - When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended - exit status and allows an integrated development environment to better - react to a compilation failure. Those exit status are: - - @table @asis - @item 5 - There was an error in at least one source file. - @item 3 - At least one source file did not generate an object file. - @item 2 - The compiler died unexpectedly (internal error for example). - @item 0 - An object file has been generated for every source file. - @end table - @end table - - @node Debugging Control - @subsection Debugging Control - - @table @code - @cindex Debugging options - @item -gnatd@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - outputs desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Debug} unit in the compiler source - file @file{debug.adb}. - - @item -gnatG - @cindex @option{-gnatG} (@code{gcc}) - This switch causes the compiler to generate auxiliary output containing - a pseudo-source listing of the generated expanded code. Like most Ada - compilers, GNAT works by first transforming the high level Ada code into - lower level constructs. For example, tasking operations are transformed - into calls to the tasking run-time routines. A unique capability of GNAT - is to list this expanded code in a form very close to normal Ada source. - This is very useful in understanding the implications of various Ada - usage on the efficiency of the generated code. There are many cases in - Ada (e.g. the use of controlled types), where simple Ada statements can - generate a lot of run-time code. By using @option{-gnatG} you can identify - these cases, and consider whether it may be desirable to modify the coding - approach to improve efficiency. - - The format of the output is very similar to standard Ada source, and is - easily understood by an Ada programmer. The following special syntactic - additions correspond to low level features used in the generated code that - do not have any exact analogies in pure Ada source form. The following - is a partial list of these special constructions. See the specification - of package @code{Sprint} in file @file{sprint.ads} for a full list. - - @table @code - @item new @var{xxx} [storage_pool = @var{yyy}] - Shows the storage pool being used for an allocator. - - @item at end @var{procedure-name}; - Shows the finalization (cleanup) procedure for a scope. - - @item (if @var{expr} then @var{expr} else @var{expr}) - Conditional expression equivalent to the @code{x?y:z} construction in C. - - @item @var{target}^(@var{source}) - A conversion with floating-point truncation instead of rounding. - - @item @var{target}?(@var{source}) - A conversion that bypasses normal Ada semantic checking. In particular - enumeration types and fixed-point types are treated simply as integers. - - @item @var{target}?^(@var{source}) - Combines the above two cases. - - @item @var{x} #/ @var{y} - @itemx @var{x} #mod @var{y} - @itemx @var{x} #* @var{y} - @itemx @var{x} #rem @var{y} - A division or multiplication of fixed-point values which are treated as - integers without any kind of scaling. - - @item free @var{expr} [storage_pool = @var{xxx}] - Shows the storage pool associated with a @code{free} statement. - - @item freeze @var{typename} [@var{actions}] - Shows the point at which @var{typename} is frozen, with possible - associated actions to be performed at the freeze point. - - @item reference @var{itype} - Reference (and hence definition) to internal type @var{itype}. - - @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) - Intrinsic function call. - - @item @var{labelname} : label - Declaration of label @var{labelname}. - - @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr} - A multiple concatenation (same effect as @var{expr} & @var{expr} & - @var{expr}, but handled more efficiently). - - @item [constraint_error] - Raise the @code{Constraint_Error} exception. - - @item @var{expression}'reference - A pointer to the result of evaluating @var{expression}. - - @item @var{target-type}!(@var{source-expression}) - An unchecked conversion of @var{source-expression} to @var{target-type}. - - @item [@var{numerator}/@var{denominator}] - Used to represent internal real literals (that) have no exact - representation in base 2-16 (for example, the result of compile time - evaluation of the expression 1.0/27.0). - - @item -gnatD - @cindex @option{-gnatD} (@code{gcc}) - This switch is used in conjunction with @option{-gnatG} to cause the expanded - source, as described above to be written to files with names - @file{xxx.dg}, where @file{xxx} is the normal file name, - for example, if the source file name is @file{hello.adb}, - then a file @file{hello.adb.dg} will be written. - The debugging information generated - by the @code{gcc} @code{-g} switch will refer to the generated - @file{xxx.dg} file. This allows you to do source level debugging using - the generated code which is sometimes useful for complex code, for example - to find out exactly which part of a complex construction raised an - exception. This switch also suppress generation of cross-reference - information (see -gnatx). - - @item -gnatC - @cindex @option{-gnatE} (@code{gcc}) - In the generated debugging information, and also in the case of long external - names, the compiler uses a compression mechanism if the name is very long. - This compression method uses a checksum, and avoids trouble on some operating - systems which have difficulty with very long names. The @option{-gnatC} switch - forces this compression approach to be used on all external names and names - in the debugging information tables. This reduces the size of the generated - executable, at the expense of making the naming scheme more complex. The - compression only affects the qualification of the name. Thus a name in - the source: - - @smallexample - Very_Long_Package.Very_Long_Inner_Package.Var - @end smallexample - - @noindent - would normally appear in these tables as: - - @smallexample - very_long_package__very_long_inner_package__var - @end smallexample - - @noindent - but if the @option{-gnatC} switch is used, then the name appears as - - @smallexample - XCb7e0c705__var - @end smallexample - - @noindent - Here b7e0c705 is a compressed encoding of the qualification prefix. - The GNAT Ada aware version of GDB understands these encoded prefixes, so if this - debugger is used, the encoding is largely hidden from the user of the compiler. - - @end table - - @item -gnatR[0|1|2|3][s] - @cindex @option{-gnatR} (@code{gcc}) - This switch controls output from the compiler of a listing showing - representation information for declared types and objects. For - @option{-gnatR0}, no information is output (equivalent to omitting - the @option{-gnatR} switch). For @option{-gnatR1} (which is the default, - so @option{-gnatR} with no parameter has the same effect), size and alignment - information is listed for declared array and record types. For - @option{-gnatR2}, size and alignment information is listed for all - expression information for values that are computed at run time for - variant records. These symbolic expressions have a mostly obvious - format with #n being used to represent the value of the n'th - discriminant. See source files @file{repinfo.ads/adb} in the - @code{GNAT} sources for full detalis on the format of @option{-gnatR3} - output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then - the output is to a file with the name @file{file.rep} where - file is the name of the corresponding source file. - - @item -gnatx - @cindex @option{-gnatx} (@code{gcc}) - Normally the compiler generates full cross-referencing information in - the @file{ALI} file. This information is used by a number of tools, - including @code{gnatfind} and @code{gnatxref}. The -gnatx switch - suppresses this information. This saves some space and may slightly - speed up compilation, but means that these tools cannot be used. - @end table - - @node Units to Sources Mapping Files - @subsection Units to Sources Mapping Files - - @table @code - - @item -gnatem@var{path} - @cindex @option{-gnatem} (@code{gcc}) - A mapping file is a way to communicate to the compiler two mappings: - from unit names to file names (without any directory information) and from - file names to path names (with full directory information). These mappings - are used by the compiler to short-circuit the path search. - - A mapping file is a sequence of sets of three lines. In each set, - the first line is the unit name, in lower case, with "%s" appended for - specifications and "%b" appended for bodies; the second line is the file - name; and the third line is the path name. - - Example: - @smallexample - main%b - main.2.ada - /gnat/project1/sources/main.2.ada - @end smallexample - - When the switch @option{-gnatem} is specified, the compiler will create - in memory the two mappings from the specified file. If there is any problem - (non existent file, truncated file or duplicate entries), no mapping - will be created. - - Several @option{-gnatem} switches may be specified; however, only the last - one on the command line will be taken into account. - - When using a project file, @code{gnatmake} create a temporary mapping file - and communicates it to the compiler using this switch. - - @end table - - @node Search Paths and the Run-Time Library (RTL) - @section Search Paths and the Run-Time Library (RTL) - - @noindent - With the GNAT source-based library system, the compiler must be able to - find source files for units that are needed by the unit being compiled. - Search paths are used to guide this process. - - The compiler compiles one source file whose name must be given - explicitly on the command line. In other words, no searching is done - for this file. To find all other source files that are needed (the most - common being the specs of units), the compiler examines the following - directories, in the following order: - - @enumerate - @item - The directory containing the source file of the main unit being compiled - (the file name on the command line). - - @item - Each directory named by an @code{-I} switch given on the @code{gcc} - command line, in the order given. - - @item - @findex ADA_INCLUDE_PATH - Each of the directories listed in the value of the - @code{ADA_INCLUDE_PATH} environment variable. - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version). - @item - The content of the "ada_source_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) source files. - @ref{Installing an Ada Library} - @end enumerate - - @noindent - Specifying the switch @code{-I-} - inhibits the use of the directory - containing the source file named in the command line. You can still - have this directory on your search path, but in this case it must be - explicitly requested with a @code{-I} switch. - - Specifying the switch @code{-nostdinc} - inhibits the search of the default location for the GNAT Run Time - Library (RTL) source files. - - The compiler outputs its object files and ALI files in the current - working directory. - Caution: The object file can be redirected with the @code{-o} switch; - however, @code{gcc} and @code{gnat1} have not been coordinated on this - so the ALI file will not go to the right place. Therefore, you should - avoid using the @code{-o} switch. - - @findex System.IO - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT RTL, together with the simple @code{System.IO} - package used in the "Hello World" example. The sources for these units - are needed by the compiler and are kept together in one directory. Not - all of the bodies are needed, but all of the sources are kept together - anyway. In a normal installation, you need not specify these directory - names when compiling or binding. Either the environment variables or - the built-in defaults cause these files to be found. - - In addition to the language-defined hierarchies (System, Ada and - Interfaces), the GNAT distribution provides a fourth hierarchy, - consisting of child units of GNAT. This is a collection of generally - useful routines. See the GNAT Reference Manual for further details. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Order of Compilation Issues - @section Order of Compilation Issues - - @noindent - If, in our earlier example, there was a spec for the @code{hello} - procedure, it would be contained in the file @file{hello.ads}; yet this - file would not have to be explicitly compiled. This is the result of the - model we chose to implement library management. Some of the consequences - of this model are as follows: - - @itemize @bullet - @item - There is no point in compiling specs (except for package - specs with no bodies) because these are compiled as needed by clients. If - you attempt a useless compilation, you will receive an error message. - It is also useless to compile subunits because they are compiled as needed - by the parent. - - @item - There are no order of compilation requirements: performing a - compilation never obsoletes anything. The only way you can obsolete - something and require recompilations is to modify one of the - source files on which it depends. - - @item - There is no library as such, apart from the ALI files - (@pxref{The Ada Library Information Files}, for information on the format of these - files). For now we find it convenient to create separate ALI files, but - eventually the information therein may be incorporated into the object - file directly. - - @item - When you compile a unit, the source files for the specs of all units - that it @code{with}'s, all its subunits, and the bodies of any generics it - instantiates must be available (reachable by the search-paths mechanism - described above), or you will receive a fatal error message. - @end itemize - - @node Examples - @section Examples - - @noindent - The following are some typical Ada compilation command line examples: - - @table @code - @item $ gcc -c xyz.adb - Compile body in file @file{xyz.adb} with all default options. - - @item $ gcc -c -O2 -gnata xyz-def.adb - - Compile the child unit package in file @file{xyz-def.adb} with extensive - optimizations, and pragma @code{Assert}/@code{Debug} statements - enabled. - - @item $ gcc -c -gnatc abc-def.adb - Compile the subunit in file @file{abc-def.adb} in semantic-checking-only - mode. - @end table - - @node Binding Using gnatbind - @chapter Binding Using @code{gnatbind} - @findex gnatbind - - @menu - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - @end menu - - @noindent - This chapter describes the GNAT binder, @code{gnatbind}, which is used - to bind compiled GNAT objects. The @code{gnatbind} program performs - four separate functions: - - @enumerate - @item - Checks that a program is consistent, in accordance with the rules in - Chapter 10 of the Ada 95 Reference Manual. In particular, error - messages are generated if a program uses inconsistent versions of a - given unit. - - @item - Checks that an acceptable order of elaboration exists for the program - and issues an error message if it cannot find an order of elaboration - that satisfies the rules in Chapter 10 of the Ada 95 Language Manual. - - @item - Generates a main program incorporating the given elaboration order. - This program is a small Ada package (body and spec) that - must be subsequently compiled - using the GNAT compiler. The necessary compilation step is usually - performed automatically by @code{gnatlink}. The two most important - functions of this program - are to call the elaboration routines of units in an appropriate order - and to call the main program. - - @item - Determines the set of object files required by the given main program. - This information is output in the forms of comments in the generated program, - to be read by the @code{gnatlink} utility used to link the Ada application. - @end enumerate - - @node Running gnatbind - @section Running @code{gnatbind} - - @noindent - The form of the @code{gnatbind} command is - - @smallexample - $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}] - @end smallexample - - @noindent - where @var{mainprog}.adb is the Ada file containing the main program - unit body. If no switches are specified, @code{gnatbind} constructs an Ada - package in two files which names are - @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}. - For example, if given the - parameter @samp{hello.ali}, for a main program contained in file - @file{hello.adb}, the binder output files would be @file{b~hello.ads} - and @file{b~hello.adb}. - - When doing consistency checking, the binder takes into consideration - any source files it can locate. For example, if the binder determines - that the given main program requires the package @code{Pack}, whose - @file{.ali} - file is @file{pack.ali} and whose corresponding source spec file is - @file{pack.ads}, it attempts to locate the source file @file{pack.ads} - (using the same search path conventions as previously described for the - @code{gcc} command). If it can locate this source file, it checks that - the time stamps - or source checksums of the source and its references to in @file{ali} files - match. In other words, any @file{ali} files that mentions this spec must have - resulted from compiling this version of the source file (or in the case - where the source checksums match, a version close enough that the - difference does not matter). - - @cindex Source files, use by binder - The effect of this consistency checking, which includes source files, is - that the binder ensures that the program is consistent with the latest - version of the source files that can be located at bind time. Editing a - source file without compiling files that depend on the source file cause - error messages to be generated by the binder. - - For example, suppose you have a main program @file{hello.adb} and a - package @code{P}, from file @file{p.ads} and you perform the following - steps: - - @enumerate - @item - Enter @code{gcc -c hello.adb} to compile the main program. - - @item - Enter @code{gcc -c p.ads} to compile package @code{P}. - - @item - Edit file @file{p.ads}. - - @item - Enter @code{gnatbind hello}. - @end enumerate - - At this point, the file @file{p.ali} contains an out-of-date time stamp - because the file @file{p.ads} has been edited. The attempt at binding - fails, and the binder generates the following error messages: - - @smallexample - error: "hello.adb" must be recompiled ("p.ads" has been modified) - error: "p.ads" has been modified and must be recompiled - @end smallexample - - @noindent - Now both files must be recompiled as indicated, and then the bind can - succeed, generating a main program. You need not normally be concerned - with the contents of this file, but it is similar to the following which - is the binder file generated for a simple "hello world" program. - - @smallexample - @iftex - @leftskip=0cm - @end iftex - -- The package is called Ada_Main unless this name is actually used - -- as a unit name in the partition, in which case some other unique - -- name is used. - - with System; - package ada_main is - - Elab_Final_Code : Integer; - pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); - - -- The main program saves the parameters (argument count, - -- argument values, environment pointer) in global variables - -- for later access by other units including - -- Ada.Command_Line. - - gnat_argc : Integer; - gnat_argv : System.Address; - gnat_envp : System.Address; - - -- The actual variables are stored in a library routine. This - -- is useful for some shared library situations, where there - -- are problems if variables are not in the library. - - pragma Import (C, gnat_argc); - pragma Import (C, gnat_argv); - pragma Import (C, gnat_envp); - - -- The exit status is similarly an external location - - gnat_exit_status : Integer; - pragma Import (C, gnat_exit_status); - - GNAT_Version : constant String := - "GNAT Version: 3.15w (20010315)"; - pragma Export (C, GNAT_Version, "__gnat_version"); - - -- This is the generated adafinal routine that performs - -- finalization at the end of execution. In the case where - -- Ada is the main program, this main program makes a call - -- to adafinal at program termination. - - procedure adafinal; - pragma Export (C, adafinal, "adafinal"); - - -- This is the generated adainit routine that performs - -- initialization at the start of execution. In the case - -- where Ada is the main program, this main program makes - -- a call to adainit at program startup. - - procedure adainit; - pragma Export (C, adainit, "adainit"); - - -- This routine is called at the start of execution. It is - -- a dummy routine that is used by the debugger to breakpoint - -- at the start of execution. - - procedure Break_Start; - pragma Import (C, Break_Start, "__gnat_break_start"); - - -- This is the actual generated main program (it would be - -- suppressed if the no main program switch were used). As - -- required by standard system conventions, this program has - -- the external name main. - - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer; - pragma Export (C, main, "main"); - - -- The following set of constants give the version - -- identification values for every unit in the bound - -- partition. This identification is computed from all - -- dependent semantic units, and corresponds to the - -- string that would be returned by use of the - -- Body_Version or Version attributes. - - type Version_32 is mod 2 ** 32; - u00001 : constant Version_32 := 16#7880BEB3#; - u00002 : constant Version_32 := 16#0D24CBD0#; - u00003 : constant Version_32 := 16#3283DBEB#; - u00004 : constant Version_32 := 16#2359F9ED#; - u00005 : constant Version_32 := 16#664FB847#; - u00006 : constant Version_32 := 16#68E803DF#; - u00007 : constant Version_32 := 16#5572E604#; - u00008 : constant Version_32 := 16#46B173D8#; - u00009 : constant Version_32 := 16#156A40CF#; - u00010 : constant Version_32 := 16#033DABE0#; - u00011 : constant Version_32 := 16#6AB38FEA#; - u00012 : constant Version_32 := 16#22B6217D#; - u00013 : constant Version_32 := 16#68A22947#; - u00014 : constant Version_32 := 16#18CC4A56#; - u00015 : constant Version_32 := 16#08258E1B#; - u00016 : constant Version_32 := 16#367D5222#; - u00017 : constant Version_32 := 16#20C9ECA4#; - u00018 : constant Version_32 := 16#50D32CB6#; - u00019 : constant Version_32 := 16#39A8BB77#; - u00020 : constant Version_32 := 16#5CF8FA2B#; - u00021 : constant Version_32 := 16#2F1EB794#; - u00022 : constant Version_32 := 16#31AB6444#; - u00023 : constant Version_32 := 16#1574B6E9#; - u00024 : constant Version_32 := 16#5109C189#; - u00025 : constant Version_32 := 16#56D770CD#; - u00026 : constant Version_32 := 16#02F9DE3D#; - u00027 : constant Version_32 := 16#08AB6B2C#; - u00028 : constant Version_32 := 16#3FA37670#; - u00029 : constant Version_32 := 16#476457A0#; - u00030 : constant Version_32 := 16#731E1B6E#; - u00031 : constant Version_32 := 16#23C2E789#; - u00032 : constant Version_32 := 16#0F1BD6A1#; - u00033 : constant Version_32 := 16#7C25DE96#; - u00034 : constant Version_32 := 16#39ADFFA2#; - u00035 : constant Version_32 := 16#571DE3E7#; - u00036 : constant Version_32 := 16#5EB646AB#; - u00037 : constant Version_32 := 16#4249379B#; - u00038 : constant Version_32 := 16#0357E00A#; - u00039 : constant Version_32 := 16#3784FB72#; - u00040 : constant Version_32 := 16#2E723019#; - u00041 : constant Version_32 := 16#623358EA#; - u00042 : constant Version_32 := 16#107F9465#; - u00043 : constant Version_32 := 16#6843F68A#; - u00044 : constant Version_32 := 16#63305874#; - u00045 : constant Version_32 := 16#31E56CE1#; - u00046 : constant Version_32 := 16#02917970#; - u00047 : constant Version_32 := 16#6CCBA70E#; - u00048 : constant Version_32 := 16#41CD4204#; - u00049 : constant Version_32 := 16#572E3F58#; - u00050 : constant Version_32 := 16#20729FF5#; - u00051 : constant Version_32 := 16#1D4F93E8#; - u00052 : constant Version_32 := 16#30B2EC3D#; - u00053 : constant Version_32 := 16#34054F96#; - u00054 : constant Version_32 := 16#5A199860#; - u00055 : constant Version_32 := 16#0E7F912B#; - u00056 : constant Version_32 := 16#5760634A#; - u00057 : constant Version_32 := 16#5D851835#; - - -- The following Export pragmas export the version numbers - -- with symbolic names ending in B (for body) or S - -- (for spec) so that they can be located in a link. The - -- information provided here is sufficient to track down - -- the exact versions of units used in a given build. - - pragma Export (C, u00001, "helloB"); - pragma Export (C, u00002, "system__standard_libraryB"); - pragma Export (C, u00003, "system__standard_libraryS"); - pragma Export (C, u00004, "adaS"); - pragma Export (C, u00005, "ada__text_ioB"); - pragma Export (C, u00006, "ada__text_ioS"); - pragma Export (C, u00007, "ada__exceptionsB"); - pragma Export (C, u00008, "ada__exceptionsS"); - pragma Export (C, u00009, "gnatS"); - pragma Export (C, u00010, "gnat__heap_sort_aB"); - pragma Export (C, u00011, "gnat__heap_sort_aS"); - pragma Export (C, u00012, "systemS"); - pragma Export (C, u00013, "system__exception_tableB"); - pragma Export (C, u00014, "system__exception_tableS"); - pragma Export (C, u00015, "gnat__htableB"); - pragma Export (C, u00016, "gnat__htableS"); - pragma Export (C, u00017, "system__exceptionsS"); - pragma Export (C, u00018, "system__machine_state_operationsB"); - pragma Export (C, u00019, "system__machine_state_operationsS"); - pragma Export (C, u00020, "system__machine_codeS"); - pragma Export (C, u00021, "system__storage_elementsB"); - pragma Export (C, u00022, "system__storage_elementsS"); - pragma Export (C, u00023, "system__secondary_stackB"); - pragma Export (C, u00024, "system__secondary_stackS"); - pragma Export (C, u00025, "system__parametersB"); - pragma Export (C, u00026, "system__parametersS"); - pragma Export (C, u00027, "system__soft_linksB"); - pragma Export (C, u00028, "system__soft_linksS"); - pragma Export (C, u00029, "system__stack_checkingB"); - pragma Export (C, u00030, "system__stack_checkingS"); - pragma Export (C, u00031, "system__tracebackB"); - pragma Export (C, u00032, "system__tracebackS"); - pragma Export (C, u00033, "ada__streamsS"); - pragma Export (C, u00034, "ada__tagsB"); - pragma Export (C, u00035, "ada__tagsS"); - pragma Export (C, u00036, "system__string_opsB"); - pragma Export (C, u00037, "system__string_opsS"); - pragma Export (C, u00038, "interfacesS"); - pragma Export (C, u00039, "interfaces__c_streamsB"); - pragma Export (C, u00040, "interfaces__c_streamsS"); - pragma Export (C, u00041, "system__file_ioB"); - pragma Export (C, u00042, "system__file_ioS"); - pragma Export (C, u00043, "ada__finalizationB"); - pragma Export (C, u00044, "ada__finalizationS"); - pragma Export (C, u00045, "system__finalization_rootB"); - pragma Export (C, u00046, "system__finalization_rootS"); - pragma Export (C, u00047, "system__finalization_implementationB"); - pragma Export (C, u00048, "system__finalization_implementationS"); - pragma Export (C, u00049, "system__string_ops_concat_3B"); - pragma Export (C, u00050, "system__string_ops_concat_3S"); - pragma Export (C, u00051, "system__stream_attributesB"); - pragma Export (C, u00052, "system__stream_attributesS"); - pragma Export (C, u00053, "ada__io_exceptionsS"); - pragma Export (C, u00054, "system__unsigned_typesS"); - pragma Export (C, u00055, "system__file_control_blockS"); - pragma Export (C, u00056, "ada__finalization__list_controllerB"); - pragma Export (C, u00057, "ada__finalization__list_controllerS"); - - -- BEGIN ELABORATION ORDER - -- ada (spec) - -- gnat (spec) - -- gnat.heap_sort_a (spec) - -- gnat.heap_sort_a (body) - -- gnat.htable (spec) - -- gnat.htable (body) - -- interfaces (spec) - -- system (spec) - -- system.machine_code (spec) - -- system.parameters (spec) - -- system.parameters (body) - -- interfaces.c_streams (spec) - -- interfaces.c_streams (body) - -- system.standard_library (spec) - -- ada.exceptions (spec) - -- system.exception_table (spec) - -- system.exception_table (body) - -- ada.io_exceptions (spec) - -- system.exceptions (spec) - -- system.storage_elements (spec) - -- system.storage_elements (body) - -- system.machine_state_operations (spec) - -- system.machine_state_operations (body) - -- system.secondary_stack (spec) - -- system.stack_checking (spec) - -- system.soft_links (spec) - -- system.soft_links (body) - -- system.stack_checking (body) - -- system.secondary_stack (body) - -- system.standard_library (body) - -- system.string_ops (spec) - -- system.string_ops (body) - -- ada.tags (spec) - -- ada.tags (body) - -- ada.streams (spec) - -- system.finalization_root (spec) - -- system.finalization_root (body) - -- system.string_ops_concat_3 (spec) - -- system.string_ops_concat_3 (body) - -- system.traceback (spec) - -- system.traceback (body) - -- ada.exceptions (body) - -- system.unsigned_types (spec) - -- system.stream_attributes (spec) - -- system.stream_attributes (body) - -- system.finalization_implementation (spec) - -- system.finalization_implementation (body) - -- ada.finalization (spec) - -- ada.finalization (body) - -- ada.finalization.list_controller (spec) - -- ada.finalization.list_controller (body) - -- system.file_control_block (spec) - -- system.file_io (spec) - -- system.file_io (body) - -- ada.text_io (spec) - -- ada.text_io (body) - -- hello (body) - -- END ELABORATION ORDER - - end ada_main; - - -- The following source file name pragmas allow the generated file - -- names to be unique for different main programs. They are needed - -- since the package name will always be Ada_Main. - - pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads"); - pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb"); - - -- Generated package body for Ada_Main starts here - - package body ada_main is - - -- The actual finalization is performed by calling the - -- library routine in System.Standard_Library.Adafinal - - procedure Do_Finalize; - pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); - - ------------- - -- adainit -- - ------------- - - @findex adainit - procedure adainit is - - -- These booleans are set to True once the associated unit has - -- been elaborated. It is also used to avoid elaborating the - -- same unit twice. - - E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E"); - E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E"); - E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E"); - E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E"); - E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E"); - E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E"); - E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E"); - E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E"); - E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E"); - E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E"); - E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E"); - E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E"); - E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E"); - E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E"); - E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E"); - E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E"); - E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E"); - - -- Set_Globals is a library routine that stores away the - -- value of the indicated set of global values in global - -- variables within the library. - - procedure Set_Globals - (Main_Priority : Integer; - Time_Slice_Value : Integer; - WC_Encoding : Character; - Locking_Policy : Character; - Queuing_Policy : Character; - Task_Dispatching_Policy : Character; - Adafinal : System.Address; - Unreserve_All_Interrupts : Integer; - Exception_Tracebacks : Integer); - @findex __gnat_set_globals - pragma Import (C, Set_Globals, "__gnat_set_globals"); - - -- SDP_Table_Build is a library routine used to build the - -- exception tables. See unit Ada.Exceptions in files - -- a-except.ads/adb for full details of how zero cost - -- exception handling works. This procedure, the call to - -- it, and the two following tables are all omitted if the - -- build is in longjmp/setjump exception mode. - - @findex SDP_Table_Build - @findex Zero Cost Exceptions - procedure SDP_Table_Build - (SDP_Addresses : System.Address; - SDP_Count : Natural; - Elab_Addresses : System.Address; - Elab_Addr_Count : Natural); - pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); - - -- Table of Unit_Exception_Table addresses. Used for zero - -- cost exception handling to build the top level table. - - ST : aliased constant array (1 .. 23) of System.Address := ( - Hello'UET_Address, - Ada.Text_Io'UET_Address, - Ada.Exceptions'UET_Address, - Gnat.Heap_Sort_A'UET_Address, - System.Exception_Table'UET_Address, - System.Machine_State_Operations'UET_Address, - System.Secondary_Stack'UET_Address, - System.Parameters'UET_Address, - System.Soft_Links'UET_Address, - System.Stack_Checking'UET_Address, - System.Traceback'UET_Address, - Ada.Streams'UET_Address, - Ada.Tags'UET_Address, - System.String_Ops'UET_Address, - Interfaces.C_Streams'UET_Address, - System.File_Io'UET_Address, - Ada.Finalization'UET_Address, - System.Finalization_Root'UET_Address, - System.Finalization_Implementation'UET_Address, - System.String_Ops_Concat_3'UET_Address, - System.Stream_Attributes'UET_Address, - System.File_Control_Block'UET_Address, - Ada.Finalization.List_Controller'UET_Address); - - -- Table of addresses of elaboration routines. Used for - -- zero cost exception handling to make sure these - -- addresses are included in the top level procedure - -- address table. - - EA : aliased constant array (1 .. 23) of System.Address := ( - adainit'Code_Address, - Do_Finalize'Code_Address, - Ada.Exceptions'Elab_Spec'Address, - System.Exceptions'Elab_Spec'Address, - Interfaces.C_Streams'Elab_Spec'Address, - System.Exception_Table'Elab_Body'Address, - Ada.Io_Exceptions'Elab_Spec'Address, - System.Stack_Checking'Elab_Spec'Address, - System.Soft_Links'Elab_Body'Address, - System.Secondary_Stack'Elab_Body'Address, - Ada.Tags'Elab_Spec'Address, - Ada.Tags'Elab_Body'Address, - Ada.Streams'Elab_Spec'Address, - System.Finalization_Root'Elab_Spec'Address, - Ada.Exceptions'Elab_Body'Address, - System.Finalization_Implementation'Elab_Spec'Address, - System.Finalization_Implementation'Elab_Body'Address, - Ada.Finalization'Elab_Spec'Address, - Ada.Finalization.List_Controller'Elab_Spec'Address, - System.File_Control_Block'Elab_Spec'Address, - System.File_Io'Elab_Body'Address, - Ada.Text_Io'Elab_Spec'Address, - Ada.Text_Io'Elab_Body'Address); - - -- Start of processing for adainit - - begin - - -- Call SDP_Table_Build to build the top level procedure - -- table for zero cost exception handling (omitted in - -- longjmp/setjump mode). - - SDP_Table_Build (ST'Address, 23, EA'Address, 23); - - -- Call Set_Globals to record various information for - -- this partition. The values are derived by the binder - -- from information stored in the ali files by the compiler. - - @findex __gnat_set_globals - Set_Globals - (Main_Priority => -1, - -- Priority of main program, -1 if no pragma Priority used - - Time_Slice_Value => -1, - -- Time slice from Time_Slice pragma, -1 if none used - - WC_Encoding => 'b', - -- Wide_Character encoding used, default is brackets - - Locking_Policy => ' ', - -- Locking_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Queuing_Policy => ' ', - -- Queuing_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Task_Dispatching_Policy => ' ', - -- Task_Dispatching_Policy used, default of space means - -- not specified, otherwise first character of the - -- policy name. - - Adafinal => System.Null_Address, - -- Address of Adafinal routine, not used anymore - - Unreserve_All_Interrupts => 0, - -- Set true if pragma Unreserve_All_Interrupts was used - - Exception_Tracebacks => 0); - -- Indicates if exception tracebacks are enabled - - Elab_Final_Code := 1; - - -- Now we have the elaboration calls for all units in the partition. - -- The Elab_Spec and Elab_Body attributes generate references to the - -- implicit elaboration procedures generated by the compiler for - -- each unit that requires elaboration. - - if not E040 then - Interfaces.C_Streams'Elab_Spec; - end if; - E040 := True; - if not E008 then - Ada.Exceptions'Elab_Spec; - end if; - if not E014 then - System.Exception_Table'Elab_Body; - E014 := True; - end if; - if not E053 then - Ada.Io_Exceptions'Elab_Spec; - E053 := True; - end if; - if not E017 then - System.Exceptions'Elab_Spec; - E017 := True; - end if; - if not E030 then - System.Stack_Checking'Elab_Spec; - end if; - if not E028 then - System.Soft_Links'Elab_Body; - E028 := True; - end if; - E030 := True; - if not E024 then - System.Secondary_Stack'Elab_Body; - E024 := True; - end if; - if not E035 then - Ada.Tags'Elab_Spec; - end if; - if not E035 then - Ada.Tags'Elab_Body; - E035 := True; - end if; - if not E033 then - Ada.Streams'Elab_Spec; - E033 := True; - end if; - if not E046 then - System.Finalization_Root'Elab_Spec; - end if; - E046 := True; - if not E008 then - Ada.Exceptions'Elab_Body; - E008 := True; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Spec; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Body; - E048 := True; - end if; - if not E044 then - Ada.Finalization'Elab_Spec; - end if; - E044 := True; - if not E057 then - Ada.Finalization.List_Controller'Elab_Spec; - end if; - E057 := True; - if not E055 then - System.File_Control_Block'Elab_Spec; - E055 := True; - end if; - if not E042 then - System.File_Io'Elab_Body; - E042 := True; - end if; - if not E006 then - Ada.Text_Io'Elab_Spec; - end if; - if not E006 then - Ada.Text_Io'Elab_Body; - E006 := True; - end if; - - Elab_Final_Code := 0; - end adainit; - - -------------- - -- adafinal -- - -------------- - - @findex adafinal - procedure adafinal is - begin - Do_Finalize; - end adafinal; - - ---------- - -- main -- - ---------- - - -- main is actually a function, as in the ANSI C standard, - -- defined to return the exit status. The three parameters - -- are the argument count, argument values and environment - -- pointer. - - @findex Main Program - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer - is - -- The initialize routine performs low level system - -- initialization using a standard library routine which - -- sets up signal handling and performs any other - -- required setup. The routine can be found in file - -- a-init.c. - - @findex __gnat_initialize - procedure initialize; - pragma Import (C, initialize, "__gnat_initialize"); - - -- The finalize routine performs low level system - -- finalization using a standard library routine. The - -- routine is found in file a-final.c and in the standard - -- distribution is a dummy routine that does nothing, so - -- really this is a hook for special user finalization. - - @findex __gnat_finalize - procedure finalize; - pragma Import (C, finalize, "__gnat_finalize"); - - -- We get to the main program of the partition by using - -- pragma Import because if we try to with the unit and - -- call it Ada style, then not only do we waste time - -- recompiling it, but also, we don't really know the right - -- switches (e.g. identifier character set) to be used - -- to compile it. - - procedure Ada_Main_Program; - pragma Import (Ada, Ada_Main_Program, "_ada_hello"); - - -- Start of processing for main - - begin - -- Save global variables - - gnat_argc := argc; - gnat_argv := argv; - gnat_envp := envp; - - -- Call low level system initialization - - Initialize; - - -- Call our generated Ada initialization routine - - adainit; - - -- This is the point at which we want the debugger to get - -- control - - Break_Start; - - -- Now we call the main program of the partition - - Ada_Main_Program; - - -- Perform Ada finalization - - adafinal; - - -- Perform low level system finalization - - Finalize; - - -- Return the proper exit status - return (gnat_exit_status); - end; - - -- This section is entirely comments, so it has no effect on the - -- compilation of the Ada_Main package. It provides the list of - -- object files and linker options, as well as some standard - -- libraries needed for the link. The gnatlink utility parses - -- this b~hello.adb file to read these comment lines to generate - -- the appropriate command line arguments for the call to the - -- system linker. The BEGIN/END lines are used for sentinels for - -- this parsing operation. - - -- The exact file names will of course depend on the environment, - -- host/target and location of files on the host system. - - @findex Object file list - -- BEGIN Object file/option list - -- ./hello.o - -- -L./ - -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ - -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a - -- END Object file/option list - - end ada_main; - - @end smallexample - - @noindent - The Ada code in the above example is exactly what is generated by the - binder. We have added comments to more clearly indicate the function - of each part of the generated @code{Ada_Main} package. - - The code is standard Ada in all respects, and can be processed by any - tools that handle Ada. In particular, it is possible to use the debugger - in Ada mode to debug the generated Ada_Main package. For example, suppose - that for reasons that you do not understand, your program is blowing up - during elaboration of the body of @code{Ada.Text_IO}. To chase this bug - down, you can place a breakpoint on the call: - - @smallexample - Ada.Text_Io'Elab_Body; - @end smallexample - - @noindent - and trace the elaboration routine for this package to find out where - the problem might be (more usually of course you would be debugging - elaboration code in your own application). - - @node Generating the Binder Program in C - @section Generating the Binder Program in C - @noindent - In most normal usage, the default mode of @code{gnatbind} which is to - generate the main package in Ada, as described in the previous section. - In particular, this means that any Ada programmer can read and understand - the generated main program. It can also be debugged just like any other - Ada code provided the @code{-g} switch is used for @code{gnatbind} - and @code{gnatlink}. - - However for some purposes it may be convenient to generate the main - program in C rather than Ada. This may for example be helpful when you - are generating a mixed language program with the main program in C. The - GNAT compiler itself is an example. The use of the @code{-C} switch - for both @code{gnatbind} and @code{gnatlink} will cause the program to - be generated in C (and compiled using the gnu C compiler). The - following shows the C code generated for the same "Hello World" - program: - - @smallexample - - #ifdef __STDC__ - #define PARAMS(paramlist) paramlist - #else - #define PARAMS(paramlist) () - #endif - - extern void __gnat_set_globals - PARAMS ((int, int, int, int, int, int, - void (*) PARAMS ((void)), int, int)); - extern void adafinal PARAMS ((void)); - extern void adainit PARAMS ((void)); - extern void system__standard_library__adafinal PARAMS ((void)); - extern int main PARAMS ((int, char **, char **)); - extern void exit PARAMS ((int)); - extern void __gnat_break_start PARAMS ((void)); - extern void _ada_hello PARAMS ((void)); - extern void __gnat_initialize PARAMS ((void)); - extern void __gnat_finalize PARAMS ((void)); - - extern void ada__exceptions___elabs PARAMS ((void)); - extern void system__exceptions___elabs PARAMS ((void)); - extern void interfaces__c_streams___elabs PARAMS ((void)); - extern void system__exception_table___elabb PARAMS ((void)); - extern void ada__io_exceptions___elabs PARAMS ((void)); - extern void system__stack_checking___elabs PARAMS ((void)); - extern void system__soft_links___elabb PARAMS ((void)); - extern void system__secondary_stack___elabb PARAMS ((void)); - extern void ada__tags___elabs PARAMS ((void)); - extern void ada__tags___elabb PARAMS ((void)); - extern void ada__streams___elabs PARAMS ((void)); - extern void system__finalization_root___elabs PARAMS ((void)); - extern void ada__exceptions___elabb PARAMS ((void)); - extern void system__finalization_implementation___elabs PARAMS ((void)); - extern void system__finalization_implementation___elabb PARAMS ((void)); - extern void ada__finalization___elabs PARAMS ((void)); - extern void ada__finalization__list_controller___elabs PARAMS ((void)); - extern void system__file_control_block___elabs PARAMS ((void)); - extern void system__file_io___elabb PARAMS ((void)); - extern void ada__text_io___elabs PARAMS ((void)); - extern void ada__text_io___elabb PARAMS ((void)); - - extern int __gnat_inside_elab_final_code; - - extern int gnat_argc; - extern char **gnat_argv; - extern char **gnat_envp; - extern int gnat_exit_status; - - char __gnat_version[] = "GNAT Version: 3.15w (20010315)"; - void adafinal () @{ - system__standard_library__adafinal (); - @} - - void adainit () - @{ - extern char ada__exceptions_E; - extern char system__exceptions_E; - extern char interfaces__c_streams_E; - extern char system__exception_table_E; - extern char ada__io_exceptions_E; - extern char system__secondary_stack_E; - extern char system__stack_checking_E; - extern char system__soft_links_E; - extern char ada__tags_E; - extern char ada__streams_E; - extern char system__finalization_root_E; - extern char system__finalization_implementation_E; - extern char ada__finalization_E; - extern char ada__finalization__list_controller_E; - extern char system__file_control_block_E; - extern char system__file_io_E; - extern char ada__text_io_E; - - extern void *__gnat_hello__SDP; - extern void *__gnat_ada__text_io__SDP; - extern void *__gnat_ada__exceptions__SDP; - extern void *__gnat_gnat__heap_sort_a__SDP; - extern void *__gnat_system__exception_table__SDP; - extern void *__gnat_system__machine_state_operations__SDP; - extern void *__gnat_system__secondary_stack__SDP; - extern void *__gnat_system__parameters__SDP; - extern void *__gnat_system__soft_links__SDP; - extern void *__gnat_system__stack_checking__SDP; - extern void *__gnat_system__traceback__SDP; - extern void *__gnat_ada__streams__SDP; - extern void *__gnat_ada__tags__SDP; - extern void *__gnat_system__string_ops__SDP; - extern void *__gnat_interfaces__c_streams__SDP; - extern void *__gnat_system__file_io__SDP; - extern void *__gnat_ada__finalization__SDP; - extern void *__gnat_system__finalization_root__SDP; - extern void *__gnat_system__finalization_implementation__SDP; - extern void *__gnat_system__string_ops_concat_3__SDP; - extern void *__gnat_system__stream_attributes__SDP; - extern void *__gnat_system__file_control_block__SDP; - extern void *__gnat_ada__finalization__list_controller__SDP; - - void **st[23] = @{ - &__gnat_hello__SDP, - &__gnat_ada__text_io__SDP, - &__gnat_ada__exceptions__SDP, - &__gnat_gnat__heap_sort_a__SDP, - &__gnat_system__exception_table__SDP, - &__gnat_system__machine_state_operations__SDP, - &__gnat_system__secondary_stack__SDP, - &__gnat_system__parameters__SDP, - &__gnat_system__soft_links__SDP, - &__gnat_system__stack_checking__SDP, - &__gnat_system__traceback__SDP, - &__gnat_ada__streams__SDP, - &__gnat_ada__tags__SDP, - &__gnat_system__string_ops__SDP, - &__gnat_interfaces__c_streams__SDP, - &__gnat_system__file_io__SDP, - &__gnat_ada__finalization__SDP, - &__gnat_system__finalization_root__SDP, - &__gnat_system__finalization_implementation__SDP, - &__gnat_system__string_ops_concat_3__SDP, - &__gnat_system__stream_attributes__SDP, - &__gnat_system__file_control_block__SDP, - &__gnat_ada__finalization__list_controller__SDP@}; - - extern void ada__exceptions___elabs (); - extern void system__exceptions___elabs (); - extern void interfaces__c_streams___elabs (); - extern void system__exception_table___elabb (); - extern void ada__io_exceptions___elabs (); - extern void system__stack_checking___elabs (); - extern void system__soft_links___elabb (); - extern void system__secondary_stack___elabb (); - extern void ada__tags___elabs (); - extern void ada__tags___elabb (); - extern void ada__streams___elabs (); - extern void system__finalization_root___elabs (); - extern void ada__exceptions___elabb (); - extern void system__finalization_implementation___elabs (); - extern void system__finalization_implementation___elabb (); - extern void ada__finalization___elabs (); - extern void ada__finalization__list_controller___elabs (); - extern void system__file_control_block___elabs (); - extern void system__file_io___elabb (); - extern void ada__text_io___elabs (); - extern void ada__text_io___elabb (); - - void (*ea[23]) () = @{ - adainit, - system__standard_library__adafinal, - ada__exceptions___elabs, - system__exceptions___elabs, - interfaces__c_streams___elabs, - system__exception_table___elabb, - ada__io_exceptions___elabs, - system__stack_checking___elabs, - system__soft_links___elabb, - system__secondary_stack___elabb, - ada__tags___elabs, - ada__tags___elabb, - ada__streams___elabs, - system__finalization_root___elabs, - ada__exceptions___elabb, - system__finalization_implementation___elabs, - system__finalization_implementation___elabb, - ada__finalization___elabs, - ada__finalization__list_controller___elabs, - system__file_control_block___elabs, - system__file_io___elabb, - ada__text_io___elabs, - ada__text_io___elabb@}; - - __gnat_SDP_Table_Build (&st, 23, ea, 23); - __gnat_set_globals ( - -1, /* Main_Priority */ - -1, /* Time_Slice_Value */ - 'b', /* WC_Encoding */ - ' ', /* Locking_Policy */ - ' ', /* Queuing_Policy */ - ' ', /* Tasking_Dispatching_Policy */ - 0, /* Finalization routine address, not used anymore */ - 0, /* Unreserve_All_Interrupts */ - 0); /* Exception_Tracebacks */ - - __gnat_inside_elab_final_code = 1; - - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabs (); - @} - if (system__exceptions_E == 0) @{ - system__exceptions___elabs (); - system__exceptions_E++; - @} - if (interfaces__c_streams_E == 0) @{ - interfaces__c_streams___elabs (); - @} - interfaces__c_streams_E = 1; - if (system__exception_table_E == 0) @{ - system__exception_table___elabb (); - system__exception_table_E++; - @} - if (ada__io_exceptions_E == 0) @{ - ada__io_exceptions___elabs (); - ada__io_exceptions_E++; - @} - if (system__stack_checking_E == 0) @{ - system__stack_checking___elabs (); - @} - if (system__soft_links_E == 0) @{ - system__soft_links___elabb (); - system__soft_links_E++; - @} - system__stack_checking_E = 1; - if (system__secondary_stack_E == 0) @{ - system__secondary_stack___elabb (); - system__secondary_stack_E++; - @} - if (ada__tags_E == 0) @{ - ada__tags___elabs (); - @} - if (ada__tags_E == 0) @{ - ada__tags___elabb (); - ada__tags_E++; - @} - if (ada__streams_E == 0) @{ - ada__streams___elabs (); - ada__streams_E++; - @} - if (system__finalization_root_E == 0) @{ - system__finalization_root___elabs (); - @} - system__finalization_root_E = 1; - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabb (); - ada__exceptions_E++; - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabs (); - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabb (); - system__finalization_implementation_E++; - @} - if (ada__finalization_E == 0) @{ - ada__finalization___elabs (); - @} - ada__finalization_E = 1; - if (ada__finalization__list_controller_E == 0) @{ - ada__finalization__list_controller___elabs (); - @} - ada__finalization__list_controller_E = 1; - if (system__file_control_block_E == 0) @{ - system__file_control_block___elabs (); - system__file_control_block_E++; - @} - if (system__file_io_E == 0) @{ - system__file_io___elabb (); - system__file_io_E++; - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabs (); - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabb (); - ada__text_io_E++; - @} - - __gnat_inside_elab_final_code = 0; - @} - int main (argc, argv, envp) - int argc; - char **argv; - char **envp; - @{ - gnat_argc = argc; - gnat_argv = argv; - gnat_envp = envp; - - __gnat_initialize (); - adainit (); - __gnat_break_start (); - - _ada_hello (); - - system__standard_library__adafinal (); - __gnat_finalize (); - exit (gnat_exit_status); - @} - unsigned helloB = 0x7880BEB3; - unsigned system__standard_libraryB = 0x0D24CBD0; - unsigned system__standard_libraryS = 0x3283DBEB; - unsigned adaS = 0x2359F9ED; - unsigned ada__text_ioB = 0x47C85FC4; - unsigned ada__text_ioS = 0x496FE45C; - unsigned ada__exceptionsB = 0x74F50187; - unsigned ada__exceptionsS = 0x6736945B; - unsigned gnatS = 0x156A40CF; - unsigned gnat__heap_sort_aB = 0x033DABE0; - unsigned gnat__heap_sort_aS = 0x6AB38FEA; - unsigned systemS = 0x0331C6FE; - unsigned system__exceptionsS = 0x20C9ECA4; - unsigned system__exception_tableB = 0x68A22947; - unsigned system__exception_tableS = 0x394BADD5; - unsigned gnat__htableB = 0x08258E1B; - unsigned gnat__htableS = 0x367D5222; - unsigned system__machine_state_operationsB = 0x4F3B7492; - unsigned system__machine_state_operationsS = 0x182F5CF4; - unsigned system__storage_elementsB = 0x2F1EB794; - unsigned system__storage_elementsS = 0x102C83C7; - unsigned system__secondary_stackB = 0x1574B6E9; - unsigned system__secondary_stackS = 0x708E260A; - unsigned system__parametersB = 0x56D770CD; - unsigned system__parametersS = 0x237E39BE; - unsigned system__soft_linksB = 0x08AB6B2C; - unsigned system__soft_linksS = 0x1E2491F3; - unsigned system__stack_checkingB = 0x476457A0; - unsigned system__stack_checkingS = 0x5299FCED; - unsigned system__tracebackB = 0x2971EBDE; - unsigned system__tracebackS = 0x2E9C3122; - unsigned ada__streamsS = 0x7C25DE96; - unsigned ada__tagsB = 0x39ADFFA2; - unsigned ada__tagsS = 0x769A0464; - unsigned system__string_opsB = 0x5EB646AB; - unsigned system__string_opsS = 0x63CED018; - unsigned interfacesS = 0x0357E00A; - unsigned interfaces__c_streamsB = 0x3784FB72; - unsigned interfaces__c_streamsS = 0x2E723019; - unsigned system__file_ioB = 0x623358EA; - unsigned system__file_ioS = 0x31F873E6; - unsigned ada__finalizationB = 0x6843F68A; - unsigned ada__finalizationS = 0x63305874; - unsigned system__finalization_rootB = 0x31E56CE1; - unsigned system__finalization_rootS = 0x23169EF3; - unsigned system__finalization_implementationB = 0x6CCBA70E; - unsigned system__finalization_implementationS = 0x604AA587; - unsigned system__string_ops_concat_3B = 0x572E3F58; - unsigned system__string_ops_concat_3S = 0x01F57876; - unsigned system__stream_attributesB = 0x1D4F93E8; - unsigned system__stream_attributesS = 0x30B2EC3D; - unsigned ada__io_exceptionsS = 0x34054F96; - unsigned system__unsigned_typesS = 0x7B9E7FE3; - unsigned system__file_control_blockS = 0x2FF876A8; - unsigned ada__finalization__list_controllerB = 0x5760634A; - unsigned ada__finalization__list_controllerS = 0x5D851835; - - /* BEGIN ELABORATION ORDER - ada (spec) - gnat (spec) - gnat.heap_sort_a (spec) - gnat.htable (spec) - gnat.htable (body) - interfaces (spec) - system (spec) - system.parameters (spec) - system.standard_library (spec) - ada.exceptions (spec) - system.exceptions (spec) - system.parameters (body) - gnat.heap_sort_a (body) - interfaces.c_streams (spec) - interfaces.c_streams (body) - system.exception_table (spec) - system.exception_table (body) - ada.io_exceptions (spec) - system.storage_elements (spec) - system.storage_elements (body) - system.machine_state_operations (spec) - system.machine_state_operations (body) - system.secondary_stack (spec) - system.stack_checking (spec) - system.soft_links (spec) - system.soft_links (body) - system.stack_checking (body) - system.secondary_stack (body) - system.standard_library (body) - system.string_ops (spec) - system.string_ops (body) - ada.tags (spec) - ada.tags (body) - ada.streams (spec) - system.finalization_root (spec) - system.finalization_root (body) - system.string_ops_concat_3 (spec) - system.string_ops_concat_3 (body) - system.traceback (spec) - system.traceback (body) - ada.exceptions (body) - system.unsigned_types (spec) - system.stream_attributes (spec) - system.stream_attributes (body) - system.finalization_implementation (spec) - system.finalization_implementation (body) - ada.finalization (spec) - ada.finalization (body) - ada.finalization.list_controller (spec) - ada.finalization.list_controller (body) - system.file_control_block (spec) - system.file_io (spec) - system.file_io (body) - ada.text_io (spec) - ada.text_io (body) - hello (body) - END ELABORATION ORDER */ - - /* BEGIN Object file/option list - ./hello.o - -L./ - -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/ - /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a - -lexc - END Object file/option list */ - - @end smallexample - - @noindent - Here again, the C code is exactly what is generated by the binder. The - functions of the various parts of this code correspond in an obvious - manner with the commented Ada code shown in the example in the previous - section. - - @node Consistency-Checking Modes - @section Consistency-Checking Modes - - @noindent - As described in the previous section, by default @code{gnatbind} checks - that object files are consistent with one another and are consistent - with any source files it can locate. The following switches control binder - access to sources. - - @table @code - @item -s - @cindex @code{-s} (@code{gnatbind}) - Require source files to be present. In this mode, the binder must be - able to locate all source files that are referenced, in order to check - their consistency. In normal mode, if a source file cannot be located it - is simply ignored. If you specify this switch, a missing source - file is an error. - - @item -x - @cindex @code{-x} (@code{gnatbind}) - Exclude source files. In this mode, the binder only checks that ALI - files are consistent with one another. Source files are not accessed. - The binder runs faster in this mode, and there is still a guarantee that - the resulting program is self-consistent. - If a source file has been edited since it was last compiled, and you - specify this switch, the binder will not detect that the object - file is out of date with respect to the source file. Note that this is the - mode that is automatically used by @code{gnatmake} because in this - case the checking against sources has already been performed by - @code{gnatmake} in the course of compilation (i.e. before binding). - - @end table - - @node Binder Error Message Control - @section Binder Error Message Control - - @noindent - The following switches provide control over the generation of error - messages from the binder: - - @table @code - @item -v - @cindex @code{-v} (@code{gnatbind}) - Verbose mode. In the normal mode, brief error messages are generated to - @file{stderr}. If this switch is present, a header is written - to @file{stdout} and any error messages are directed to @file{stdout}. - All that is written to @file{stderr} is a brief summary message. - - @item -b - @cindex @code{-b} (@code{gnatbind}) - Generate brief error messages to @file{stderr} even if verbose mode is - specified. This is relevant only when used with the - @code{-v} switch. - - @item -m@var{n} - @cindex @code{-m} (@code{gnatbind}) - Limits the number of error messages to @var{n}, a decimal integer in the - range 1-999. The binder terminates immediately if this limit is reached. - - @item -M@var{xxx} - @cindex @code{-M} (@code{gnatbind}) - Renames the generated main program from @code{main} to @code{xxx}. - This is useful in the case of some cross-building environments, where - the actual main program is separate from the one generated - by @code{gnatbind}. - - @item -ws - @cindex @code{-ws} (@code{gnatbind}) - @cindex Warnings - Suppress all warning messages. - - @item -we - @cindex @code{-we} (@code{gnatbind}) - Treat any warning messages as fatal errors. - - - @item -t - @cindex @code{-t} (@code{gnatbind}) - @cindex Time stamp checks, in binder - @cindex Binder consistency checks - @cindex Consistency checks, in binder - The binder performs a number of consistency checks including: - - @itemize @bullet - @item - Check that time stamps of a given source unit are consistent - @item - Check that checksums of a given source unit are consistent - @item - Check that consistent versions of @code{GNAT} were used for compilation - @item - Check consistency of configuration pragmas as required - @end itemize - - @noindent - Normally failure of such checks, in accordance with the consistency - requirements of the Ada Reference Manual, causes error messages to be - generated which abort the binder and prevent the output of a binder - file and subsequent link to obtain an executable. - - The @code{-t} switch converts these error messages - into warnings, so that - binding and linking can continue to completion even in the presence of such - errors. The result may be a failed link (due to missing symbols), or a - non-functional executable which has undefined semantics. - @emph{This means that - @code{-t} should be used only in unusual situations, - with extreme care.} - @end table - - @node Elaboration Control - @section Elaboration Control - - @noindent - The following switches provide additional control over the elaboration - order. For full details see @xref{Elaboration Order Handling in GNAT}. - - @table @code - @item -p - @cindex @code{-h} (@code{gnatbind}) - Normally the binder attempts to choose an elaboration order that is - likely to minimize the likelihood of an elaboration order error resulting - in raising a @code{Program_Error} exception. This switch reverses the - action of the binder, and requests that it deliberately choose an order - that is likely to maximize the likelihood of an elaboration error. - This is useful in ensuring portability and avoiding dependence on - accidental fortuitous elaboration ordering. - - Normally it only makes sense to use the @code{-p} switch if dynamic - elaboration checking is used (@option{-gnatE} switch used for compilation). - This is because in the default static elaboration mode, all necessary - @code{Elaborate_All} pragmas are implicitly inserted. These implicit - pragmas are still respected by the binder in @code{-p} mode, so a - safe elaboration order is assured. - @end table - - @node Output Control - @section Output Control - - @noindent - The following switches allow additional control over the output - generated by the binder. - - @table @code - - @item -A - @cindex @code{-A} (@code{gnatbind}) - Generate binder program in Ada (default). The binder program is named - @file{b~@var{mainprog}.adb} by default. This can be changed with - @code{-o} @code{gnatbind} option. - - @item -c - @cindex @code{-c} (@code{gnatbind}) - Check only. Do not generate the binder output file. In this mode the - binder performs all error checks but does not generate an output file. - - @item -C - @cindex @code{-C} (@code{gnatbind}) - Generate binder program in C. The binder program is named - @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind} - option. - - @item -e - @cindex @code{-e} (@code{gnatbind}) - Output complete list of elaboration-order dependencies, showing the - reason for each dependency. This output can be rather extensive but may - be useful in diagnosing problems with elaboration order. The output is - written to @file{stdout}. - - @item -h - @cindex @code{-h} (@code{gnatbind}) - Output usage information. The output is written to @file{stdout}. - - @item -K - @cindex @code{-K} (@code{gnatbind}) - Output linker options to @file{stdout}. Includes library search paths, - contents of pragmas Ident and Linker_Options, and libraries added - by @code{gnatbind}. - - @item -l - @cindex @code{-l} (@code{gnatbind}) - Output chosen elaboration order. The output is written to @file{stdout}. - - @item -O - @cindex @code{-O} (@code{gnatbind}) - Output full names of all the object files that must be linked to provide - the Ada component of the program. The output is written to @file{stdout}. - This list includes the files explicitly supplied and referenced by the user - as well as implicitly referenced run-time unit files. The latter are - omitted if the corresponding units reside in shared libraries. The - directory names for the run-time units depend on the system configuration. - - @item -o @var{file} - @cindex @code{-o} (@code{gnatbind}) - Set name of output file to @var{file} instead of the normal - @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada - binder generated body filename. In C mode you would normally give - @var{file} an extension of @file{.c} because it will be a C source program. - Note that if this option is used, then linking must be done manually. - It is not possible to use gnatlink in this case, since it cannot locate - the binder file. - - @item -r - @cindex @code{-r} (@code{gnatbind}) - Generate list of @code{pragma Rerstrictions} that could be applied to - the current unit. This is useful for code audit purposes, and also may - be used to improve code generation in some cases. - - @end table - - @node Binding with Non-Ada Main Programs - @section Binding with Non-Ada Main Programs - - @noindent - In our description so far we have assumed that the main - program is in Ada, and that the task of the binder is to generate a - corresponding function @code{main} that invokes this Ada main - program. GNAT also supports the building of executable programs where - the main program is not in Ada, but some of the called routines are - written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). - The following switch is used in this situation: - - @table @code - @item -n - @cindex @code{-n} (@code{gnatbind}) - No main program. The main program is not in Ada. - @end table - - @noindent - In this case, most of the functions of the binder are still required, - but instead of generating a main program, the binder generates a file - containing the following callable routines: - - @table @code - @item adainit - @findex adainit - You must call this routine to initialize the Ada part of the program by - calling the necessary elaboration routines. A call to @code{adainit} is - required before the first call to an Ada subprogram. - - Note that it is assumed that the basic execution environment must be setup - to be appropriate for Ada execution at the point where the first Ada - subprogram is called. In particular, if the Ada code will do any - floating-point operations, then the FPU must be setup in an appropriate - manner. For the case of the x86, for example, full precision mode is - required. The procedure GNAT.Float_Control.Reset may be used to ensure - that the FPU is in the right state. - - @item adafinal - @findex adafinal - You must call this routine to perform any library-level finalization - required by the Ada subprograms. A call to @code{adafinal} is required - after the last call to an Ada subprogram, and before the program - terminates. - @end table - - @noindent - If the @code{-n} switch - @cindex Binder, multiple input files - is given, more than one ALI file may appear on - the command line for @code{gnatbind}. The normal @dfn{closure} - calculation is performed for each of the specified units. Calculating - the closure means finding out the set of units involved by tracing - @code{with} references. The reason it is necessary to be able to - specify more than one ALI file is that a given program may invoke two or - more quite separate groups of Ada units. - - The binder takes the name of its output file from the last specified ALI - file, unless overridden by the use of the @code{-o file}. - The output is an Ada unit in source form that can - be compiled with GNAT unless the -C switch is used in which case the - output is a C source file, which must be compiled using the C compiler. - This compilation occurs automatically as part of the @code{gnatlink} - processing. - - Currently the GNAT run time requires a FPU using 80 bits mode - precision. Under targets where this is not the default it is required to - call GNAT.Float_Control.Reset before using floating point numbers (this - include float computation, float input and output) in the Ada code. A - side effect is that this could be the wrong mode for the foreign code - where floating point computation could be broken after this call. - - @node Binding Programs with No Main Subprogram - @section Binding Programs with No Main Subprogram - - @noindent - It is possible to have an Ada program which does not have a main - subprogram. This program will call the elaboration routines of all the - packages, then the finalization routines. - - The following switch is used to bind programs organized in this manner: - - @table @code - @item -z - @cindex @code{-z} (@code{gnatbind}) - Normally the binder checks that the unit name given on the command line - corresponds to a suitable main subprogram. When this switch is used, - a list of ALI files can be given, and the execution of the program - consists of elaboration of these units in an appropriate order. - @end table - - @node Summary of Binder Switches - @section Summary of Binder Switches - - @noindent - The following are the switches available with @code{gnatbind}: - - @table @code - @item -aO - Specify directory to be searched for ALI files. - - @item -aI - Specify directory to be searched for source file. - - @item -A - Generate binder program in Ada (default) - - @item -b - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -c - Check only, no generation of binder output file. - - @item -C - Generate binder program in C - - @item -e - Output complete list of elaboration-order dependencies. - - @item -E - Store tracebacks in exception occurrences when the target supports it. - This is the default with the zero cost exception mechanism. - This option is currently supported on the following targets: - all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. - See also the packages @code{GNAT.Traceback} and - @code{GNAT.Traceback.Symbolic} for more information. - Note that on x86 ports, you must not use @code{-fomit-frame-pointer} - @code{gcc} option. - - @item -h - Output usage (help) information - - @item -I - Specify directory to be searched for source and ALI files. - - @item -I- - Do not look for sources in the current directory where @code{gnatbind} was - invoked, and do not look for ALI files in the directory containing the - ALI file named in the @code{gnatbind} command line. - - @item -l - Output chosen elaboration order. - - @item -Lxxx - Binds the units for library building. In this case the adainit and - adafinal procedures (See @pxref{Binding with Non-Ada Main Programs}) - are renamed to xxxinit and xxxfinal. Implies -n. - See @pxref{GNAT and Libraries} for more details. - - @item -Mxyz - Rename generated main program from main to xyz - - @item -m@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item -n - No main program. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatbind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -o @var{file} - Name the output file @var{file} (default is @file{b~@var{xxx}.adb}). - Note that if this option is used, then linking must be done manually, - gnatlink cannot be used. - - @item -O - Output object list. - - @item -p - Pessimistic (worst-case) elaboration order - - @item -s - Require all source files to be present. - - @item -static - Link against a static GNAT run time. - - @item -shared - Link against a shared GNAT run time when available. - - @item -t - Tolerate time stamp and other consistency errors - - @item -T@var{n} - Set the time slice value to n microseconds. A value of zero means no time - slicing and also indicates to the tasking run time to match as close as - possible to the annex D requirements of the RM. - - @item -v - Verbose mode. Write error messages, header, summary output to - @file{stdout}. - - @item -w@var{x} - Warning mode (@var{x}=s/e for suppress/treat as error) - - - @item -x - Exclude source files (check object consistency only). - - - @item -z - No main subprogram. - - @end table - - You may obtain this listing by running the program @code{gnatbind} with - no arguments. - - @node Command-Line Access - @section Command-Line Access - - @noindent - The package @code{Ada.Command_Line} provides access to the command-line - arguments and program name. In order for this interface to operate - correctly, the two variables - - @smallexample - @group - @cartouche - int gnat_argc; - char **gnat_argv; - @end cartouche - @end group - @end smallexample - - @noindent - @findex gnat_argv - @findex gnat_argc - are declared in one of the GNAT library routines. These variables must - be set from the actual @code{argc} and @code{argv} values passed to the - main program. With no @code{n} present, @code{gnatbind} - generates the C main program to automatically set these variables. - If the @code{n} switch is used, there is no automatic way to - set these variables. If they are not set, the procedures in - @code{Ada.Command_Line} will not be available, and any attempt to use - them will raise @code{Constraint_Error}. If command line access is - required, your main program must set @code{gnat_argc} and - @code{gnat_argv} from the @code{argc} and @code{argv} values passed to - it. - - @node Search Paths for gnatbind - @section Search Paths for @code{gnatbind} - - @noindent - The binder takes the name of an ALI file as its argument and needs to - locate source files as well as other ALI files to verify object consistency. - - For source files, it follows exactly the same search rules as @code{gcc} - (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the - directories searched are: - - @enumerate - @item - The directory containing the ALI file named in the command line, unless - the switch @code{-I-} is specified. - - @item - All directories specified by @code{-I} - switches on the @code{gnatbind} - command line, in the order given. - - @item - @findex ADA_OBJECTS_PATH - Each of the directories listed in the value of the - @code{ADA_OBJECTS_PATH} environment variable. - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version - of GNAT). - - @item - The content of the "ada_object_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is - specified. - @ref{Installing an Ada Library} - @end enumerate - - @noindent - In the binder the switch @code{-I} - is used to specify both source and - library file paths. Use @code{-aI} - instead if you want to specify - source paths only, and @code{-aO} - if you want to specify library paths - only. This means that for the binder - @code{-I}@var{dir} is equivalent to - @code{-aI}@var{dir} - @code{-aO}@var{dir}. - The binder generates the bind file (a C language source file) in the - current working directory. - - @findex Ada - @findex System - @findex Interfaces - @findex GNAT - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT Run-Time Library, together with the package - GNAT and its children, which contain a set of useful additional - library functions provided by GNAT. The sources for these units are - needed by the compiler and are kept together in one directory. The ALI - files and object files generated by compiling the RTL are needed by the - binder and the linker and are kept together in one directory, typically - different from the directory containing the sources. In a normal - installation, you need not specify these directory names when compiling - or binding. Either the environment variables or the built-in defaults - cause these files to be found. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Examples of gnatbind Usage - @section Examples of @code{gnatbind} Usage - - @noindent - This section contains a number of examples of using the GNAT binding - utility @code{gnatbind}. - - @table @code - @item gnatbind hello - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{b~hello.adb}. This is the normal, default use of the binder. - - @item gnatbind hello -o mainprog.adb - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{mainprog.adb} with the associated spec in - @file{mainprog.ads}. Note that you must specify the body here not the - spec, in the case where the output is in Ada. Note that if this option - is used, then linking must be done manually, since gnatlink will not - be able to find the generated file. - - @item gnatbind main -C -o mainprog.c -x - The main program @code{Main} (source program in - @file{main.adb}) is bound, excluding source files from the - consistency checking, generating - the file @file{mainprog.c}. - - @item gnatbind -x main_program -C -o mainprog.c - This command is exactly the same as the previous example. Switches may - appear anywhere in the command line, and single letter switches may be - combined into a single switch. - - @item gnatbind -n math dbase -C -o ada-control.c - The main program is in a language other than Ada, but calls to - subprograms in packages @code{Math} and @code{Dbase} appear. This call - to @code{gnatbind} generates the file @file{ada-control.c} containing - the @code{adainit} and @code{adafinal} routines to be called before and - after accessing the Ada units. - @end table - - @node Linking Using gnatlink - @chapter Linking Using @code{gnatlink} - @findex gnatlink - - @noindent - This chapter discusses @code{gnatlink}, a utility program used to link - Ada programs and build an executable file. This is a simple program - that invokes the Unix linker (via the @code{gcc} - command) with a correct list of object files and library references. - @code{gnatlink} automatically determines the list of files and - references for the Ada part of a program. It uses the binder file - generated by the binder to determine this list. - - @menu - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - @end menu - - @node Running gnatlink - @section Running @code{gnatlink} - - @noindent - The form of the @code{gnatlink} command is - - @smallexample - $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}] - [@var{linker options}] - @end smallexample - - @noindent - @file{@var{mainprog}.ali} references the ALI file of the main program. - The @file{.ali} extension of this file can be omitted. From this - reference, @code{gnatlink} locates the corresponding binder file - @file{b~@var{mainprog}.adb} and, using the information in this file along - with the list of non-Ada objects and linker options, constructs a Unix - linker command file to create the executable. - - The arguments following @file{@var{mainprog}.ali} are passed to the - linker uninterpreted. They typically include the names of object files - for units written in other languages than Ada and any library references - required to resolve references in any of these foreign language units, - or in @code{pragma Import} statements in any Ada units. - - @var{linker options} is an optional list of linker specific - switches. The default linker called by gnatlink is @var{gcc} which in - turn calls the appropriate system linker usually called - @var{ld}. Standard options for the linker such as @code{-lmy_lib} or - @code{-Ldir} can be added as is. For options that are not recognized by - @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or - @code{-Wl,} shall be used. Refer to the GCC documentation for - details. Here is an example showing how to generate a linker map - assuming that the underlying linker is GNU ld: - - @smallexample - $ gnatlink my_prog -Wl,-Map,MAPFILE - @end smallexample - - Using @var{linker options} it is possible to set the program stack and - heap size. See @pxref{Setting Stack Size from gnatlink} and - @pxref{Setting Heap Size from gnatlink}. - - @code{gnatlink} determines the list of objects required by the Ada - program and prepends them to the list of objects passed to the linker. - @code{gnatlink} also gathers any arguments set by the use of - @code{pragma Linker_Options} and adds them to the list of arguments - presented to the linker. - - - @node Switches for gnatlink - @section Switches for @code{gnatlink} - - @noindent - The following switches are available with the @code{gnatlink} utility: - - @table @code - - @item -A - @cindex @code{-A} (@code{gnatlink}) - The binder has generated code in Ada. This is the default. - - @item -C - @cindex @code{-C} (@code{gnatlink}) - If instead of generating a file in Ada, the binder has generated one in - C, then the linker needs to know about it. Use this switch to signal - to @code{gnatlink} that the binder has generated C code rather than - Ada code. - - @item -f - @cindex Command line length - @cindex @code{-f} (@code{gnatlink}) - On some targets, the command line length is limited, and @code{gnatlink} - will generate a separate file for the linker if the list of object files - is too long. The @code{-f} flag forces this file to be generated even if - the limit is not exceeded. This is useful in some cases to deal with - special situations where the command line length is exceeded. - - @item -g - @cindex Debugging information, including - @cindex @code{-g} (@code{gnatlink}) - The option to include debugging information causes the Ada bind file (in - other words, @file{b~@var{mainprog}.adb}) to be compiled with - @code{-g}. - In addition, the binder does not delete the @file{b~@var{mainprog}.adb}, - @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files. - Without @code{-g}, the binder removes these files by - default. The same procedure apply if a C bind file was generated using - @code{-C} @code{gnatbind} option, in this case the filenames are - @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}. - - @item -n - @cindex @code{-n} (@code{gnatlink}) - Do not compile the file generated by the binder. This may be used when - a link is rerun with different options, but there is no need to recompile - the binder file. - - @item -v - @cindex @code{-v} (@code{gnatlink}) - Causes additional information to be output, including a full list of the - included object files. This switch option is most useful when you want - to see what set of object files are being used in the link step. - - @item -v -v - @cindex @code{-v -v} (@code{gnatlink}) - Very verbose mode. Requests that the compiler operate in verbose mode when - it compiles the binder file, and that the system linker run in verbose mode. - - @item -o @var{exec-name} - @cindex @code{-o} (@code{gnatlink}) - @var{exec-name} specifies an alternate name for the generated - executable program. If this switch is omitted, the executable has the same - name as the main unit. For example, @code{gnatlink try.ali} creates - an executable called @file{try}. - - @item -b @var{target} - @cindex @code{-b} (@code{gnatlink}) - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gnatlink}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatlink}) - Program used for compiling the binder file. The default is - `@code{gcc}'. You need to use quotes around @var{compiler_name} if - @code{compiler_name} contains spaces or other separator characters. As - an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use - @code{foo -x -y} as your compiler. Note that switch @code{-c} is always - inserted after your command name. Thus in the above example the compiler - command that will be used by @code{gnatlink} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --LINK=@var{name} - @cindex @code{--LINK=} (@code{gnatlink}) - @var{name} is the name of the linker to be invoked. This is especially - useful in mixed language programs since languages such as c++ require - their own linker to be used. When this switch is omitted, the default - name for the linker is (@file{gcc}). When this switch is used, the - specified linker is called instead of (@file{gcc}) with exactly the same - parameters that would have been passed to (@file{gcc}) so if the desired - linker requires different parameters it is necessary to use a wrapper - script that massages the parameters before invoking the real linker. It - may be useful to control the exact invocation by using the verbose - switch. - - - - @end table - - @node Setting Stack Size from gnatlink - @section Setting Stack Size from @code{gnatlink} - - @noindent - It is possible to specify the program stack size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --stack=0x10000,0x1000 - @end smallexample - - This set the stack reserve size to 0x10000 bytes and the stack commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--stack=0x1000000 - @end smallexample - - This set the stack reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the stack commit size - because the coma is a separator for this option. - - @end itemize - - @node Setting Heap Size from gnatlink - @section Setting Heap Size from @code{gnatlink} - - @noindent - It is possible to specify the program heap size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --heap=0x10000,0x1000 - @end smallexample - - This set the heap reserve size to 0x10000 bytes and the heap commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--heap=0x1000000 - @end smallexample - - This set the heap reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the heap commit size - because the coma is a separator for this option. - - @end itemize - - @node The GNAT Make Program gnatmake - @chapter The GNAT Make Program @code{gnatmake} - @findex gnatmake - - @menu - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - @end menu - @noindent - A typical development cycle when working on an Ada program consists of - the following steps: - - @enumerate - @item - Edit some sources to fix bugs. - - @item - Add enhancements. - - @item - Compile all sources affected. - - @item - Rebind and relink. - - @item - Test. - @end enumerate - - @noindent - The third step can be tricky, because not only do the modified files - @cindex Dependency rules - have to be compiled, but any files depending on these files must also be - recompiled. The dependency rules in Ada can be quite complex, especially - in the presence of overloading, @code{use} clauses, generics and inlined - subprograms. - - @code{gnatmake} automatically takes care of the third and fourth steps - of this process. It determines which sources need to be compiled, - compiles them, and binds and links the resulting object files. - - Unlike some other Ada make programs, the dependencies are always - accurately recomputed from the new sources. The source based approach of - the GNAT compilation model makes this possible. This means that if - changes to the source program cause corresponding changes in - dependencies, they will always be tracked exactly correctly by - @code{gnatmake}. - - @node Running gnatmake - @section Running @code{gnatmake} - - @noindent - The usual form of the @code{gnatmake} command is - - @smallexample - $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}] - @end smallexample - - @noindent - The only required argument is one @var{file_name}, which specifies - a compilation unit that is a main program. Several @var{file_names} can be - specified: this will result in several executables being built. - If @code{switches} are present, they can be placed before the first - @var{file_name}, between @var{file_names} or after the last @var{file_name}. - If @var{mode_switches} are present, they must always be placed after - the last @var{file_name} and all @code{switches}. - - If you are using standard file extensions (.adb and .ads), then the - extension may be omitted from the @var{file_name} arguments. However, if - you are using non-standard extensions, then it is required that the - extension be given. A relative or absolute directory path can be - specified in a @var{file_name}, in which case, the input source file will - be searched for in the specified directory only. Otherwise, the input - source file will first be searched in the directory where - @code{gnatmake} was invoked and if it is not found, it will be search on - the source path of the compiler as described in - @ref{Search Paths and the Run-Time Library (RTL)}. - - When several @var{file_names} are specified, if an executable needs to be - rebuilt and relinked, all subsequent executables will be rebuilt and - relinked, even if this would not be absolutely necessary. - - All @code{gnatmake} output (except when you specify - @code{-M}) is to - @file{stderr}. The output produced by the - @code{-M} switch is send to - @file{stdout}. - - @node Switches for gnatmake - @section Switches for @code{gnatmake} - - @noindent - You may specify any of the following switches to @code{gnatmake}: - - @table @code - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatmake}) - Program used for compiling. The default is `@code{gcc}'. You need to use - quotes around @var{compiler_name} if @code{compiler_name} contains - spaces or other separator characters. As an example @code{--GCC="foo -x - -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your - compiler. Note that switch @code{-c} is always inserted after your - command name. Thus in the above example the compiler command that will - be used by @code{gnatmake} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --GNATBIND=@var{binder_name} - @cindex @code{--GNATBIND=binder_name} (@code{gnatmake}) - Program used for binding. The default is `@code{gnatbind}'. You need to - use quotes around @var{binder_name} if @var{binder_name} contains spaces - or other separator characters. As an example @code{--GNATBIND="bar -x - -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your - binder. Binder switches that are normally appended by @code{gnatmake} to - `@code{gnatbind}' are now appended to the end of @code{bar -x -y}. - - @item --GNATLINK=@var{linker_name} - @cindex @code{--GNATLINK=linker_name} (@code{gnatmake}) - Program used for linking. The default is `@code{gnatlink}'. You need to - use quotes around @var{linker_name} if @var{linker_name} contains spaces - or other separator characters. As an example @code{--GNATLINK="lan -x - -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your - linker. Linker switches that are normally appended by @code{gnatmake} to - `@code{gnatlink}' are now appended to the end of @code{lan -x -y}. - - - @item -a - @cindex @code{-a} (@code{gnatmake}) - Consider all files in the make process, even the GNAT internal system - files (for example, the predefined Ada library files), as well as any - locked files. Locked files are files whose ALI file is write-protected. - By default, - @code{gnatmake} does not check these files, - because the assumption is that the GNAT internal files are properly up - to date, and also that any write protected ALI files have been properly - installed. Note that if there is an installation problem, such that one - of these files is not up to date, it will be properly caught by the - binder. - You may have to specify this switch if you are working on GNAT - itself. @code{-a} is also useful in conjunction with - @code{-f} - if you need to recompile an entire application, - including run-time files, using special configuration pragma settings, - such as a non-standard @code{Float_Representation} pragma. - By default - @code{gnatmake -a} compiles all GNAT - internal files with - @code{gcc -c -gnatpg} rather than @code{gcc -c}. - - @item -b - @cindex @code{-b} (@code{gnatmake}) - Bind only. Can be combined with @code{-c} to do compilation - and binding, but no link. Can be combined with @code{-l} - to do binding and linking. When not combined with @code{-c} - all the units in the closure of the main program must have been previously - compiled and must be up to date. The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item -c - @cindex @code{-c} (@code{gnatmake}) - Compile only. Do not perform binding, except when @code{-b} - is also specified. Do not perform linking, except if both - @code{-b} and - @code{-l} are also specified. - If the root unit specified by @var{file_name} is not a main unit, this is the - default. Otherwise @code{gnatmake} will attempt binding and linking - unless all objects are up to date and the executable is more recent than - the objects. - - @item -C - @cindex @code{-C} (@code{gnatmake}) - Use a mapping file. A mapping file is a way to communicate to the compiler - two mappings: from unit names to file names (without any directory information) - and from file names to path names (with full directory information). - These mappings are used by the compiler to short-circuit the path search. - When @code{gnatmake} is invoked with this switch, it will create a mapping - file, initially populated by the project manager, if @code{-P} is used, - otherwise initially empty. Each invocation of the compiler will add the newly - accessed sources to the mapping file. This will improve the source search - during the next invocation of the compiler. - - @item -f - @cindex @code{-f} (@code{gnatmake}) - Force recompilations. Recompile all sources, even though some object - files may be up to date, but don't recompile predefined or GNAT internal - files or locked files (files with a write-protected ALI file), - unless the @code{-a} switch is also specified. - - @item - @item -i - @cindex @code{-i} (@code{gnatmake}) - In normal mode, @code{gnatmake} compiles all object files and ALI files - into the current directory. If the @code{-i} switch is used, - then instead object files and ALI files that already exist are overwritten - in place. This means that once a large project is organized into separate - directories in the desired manner, then @code{gnatmake} will automatically - maintain and update this organization. If no ALI files are found on the - Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), - the new object and ALI files are created in the - directory containing the source being compiled. If another organization - is desired, where objects and sources are kept in different directories, - a useful technique is to create dummy ALI files in the desired directories. - When detecting such a dummy file, @code{gnatmake} will be forced to recompile - the corresponding source file, and it will be put the resulting object - and ALI files in the directory where it found the dummy file. - - @item -j@var{n} - @cindex @code{-j} (@code{gnatmake}) - @cindex Parallel make - Use @var{n} processes to carry out the (re)compilations. On a - multiprocessor machine compilations will occur in parallel. In the - event of compilation errors, messages from various compilations might - get interspersed (but @code{gnatmake} will give you the full ordered - list of failing compiles at the end). If this is problematic, rerun - the make process with n set to 1 to get a clean list of messages. - - @item -k - @cindex @code{-k} (@code{gnatmake}) - Keep going. Continue as much as possible after a compilation error. To - ease the programmer's task in case of compilation errors, the list of - sources for which the compile fails is given when @code{gnatmake} - terminates. - - If @code{gnatmake} is invoked with several @file{file_names} and with this - switch, if there are compilation errors when building an executable, - @code{gnatmake} will not attempt to build the following executables. - - @item -l - @cindex @code{-l} (@code{gnatmake}) - Link only. Can be combined with @code{-b} to binding - and linking. Linking will not be performed if combined with - @code{-c} - but not with @code{-b}. - When not combined with @code{-b} - all the units in the closure of the main program must have been previously - compiled and must be up to date, and the main program need to have been bound. - The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item -m - @cindex @code{-m} (@code{gnatmake}) - Specifies that the minimum necessary amount of recompilations - be performed. In this mode @code{gnatmake} ignores time - stamp differences when the only - modifications to a source file consist in adding/removing comments, - empty lines, spaces or tabs. This means that if you have changed the - comments in a source file or have simply reformatted it, using this - switch will tell gnatmake not to recompile files that depend on it - (provided other sources on which these files depend have undergone no - semantic modifications). Note that the debugging information may be - out of date with respect to the sources if the @code{-m} switch causes - a compilation to be switched, so the use of this switch represents a - trade-off between compilation time and accurate debugging information. - - @item -M - @cindex Dependencies, producing list - @cindex @code{-M} (@code{gnatmake}) - Check if all objects are up to date. If they are, output the object - dependences to @file{stdout} in a form that can be directly exploited in - a @file{Makefile}. By default, each source file is prefixed with its - (relative or absolute) directory name. This name is whatever you - specified in the various @code{-aI} - and @code{-I} switches. If you use - @code{gnatmake -M} - @code{-q} - (see below), only the source file names, - without relative paths, are output. If you just specify the - @code{-M} - switch, dependencies of the GNAT internal system files are omitted. This - is typically what you want. If you also specify - the @code{-a} switch, - dependencies of the GNAT internal files are also listed. Note that - dependencies of the objects in external Ada libraries (see switch - @code{-aL}@var{dir} in the following list) are never reported. - - @item -n - @cindex @code{-n} (@code{gnatmake}) - Don't compile, bind, or link. Checks if all objects are up to date. - If they are not, the full name of the first file that needs to be - recompiled is printed. - Repeated use of this option, followed by compiling the indicated source - file, will eventually result in recompiling all required units. - - @item -o @var{exec_name} - @cindex @code{-o} (@code{gnatmake}) - Output executable name. The name of the final executable program will be - @var{exec_name}. If the @code{-o} switch is omitted the default - name for the executable will be the name of the input file in appropriate form - for an executable file on the host system. - - This switch cannot be used when invoking @code{gnatmake} with several - @file{file_names}. - - @item -q - @cindex @code{-q} (@code{gnatmake}) - Quiet. When this flag is not set, the commands carried out by - @code{gnatmake} are displayed. - - @item -s - @cindex @code{-s} (@code{gnatmake}) - Recompile if compiler switches have changed since last compilation. - All compiler switches but -I and -o are taken into account in the - following way: - orders between different ``first letter'' switches are ignored, but - orders between same switches are taken into account. For example, - @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent - to @code{-O -g}. - - @item -u - @cindex @code{-u} (@code{gnatmake}) - Unique. Recompile at most the main file. It implies -c. Combined with - -f, it is equivalent to calling the compiler directly. - - @item -v - @cindex @code{-v} (@code{gnatmake}) - Verbose. Displays the reason for all recompilations @code{gnatmake} - decides are necessary. - - @item -z - @cindex @code{-z} (@code{gnatmake}) - No main subprogram. Bind and link the program even if the unit name - given on the command line is a package name. The resulting executable - will execute the elaboration routines of the package and its closure, - then the finalization routines. - - @item @code{gcc} @asis{switches} - The switch @code{-g} or any uppercase switch (other than @code{-A}, - @code{-L} or - @code{-S}) or any switch that is more than one character is passed to - @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.) - @end table - - @noindent - Source and library search path switches: - - @table @code - @item -aI@var{dir} - @cindex @code{-aI} (@code{gnatmake}) - When looking for source files also look in directory @var{dir}. - The order in which source files search is undertaken is - described in @ref{Search Paths and the Run-Time Library (RTL)}. - - @item -aL@var{dir} - @cindex @code{-aL} (@code{gnatmake}) - Consider @var{dir} as being an externally provided Ada library. - Instructs @code{gnatmake} to skip compilation units whose @file{.ali} - files have been located in directory @var{dir}. This allows you to have - missing bodies for the units in @var{dir} and to ignore out of date bodies - for the same units. You still need to specify - the location of the specs for these units by using the switches - @code{-aI@var{dir}} - or @code{-I@var{dir}}. - Note: this switch is provided for compatibility with previous versions - of @code{gnatmake}. The easier method of causing standard libraries - to be excluded from consideration is to write-protect the corresponding - ALI files. - - @item -aO@var{dir} - @cindex @code{-aO} (@code{gnatmake}) - When searching for library and object files, look in directory - @var{dir}. The order in which library files are searched is described in - @ref{Search Paths for gnatbind}. - - @item -A@var{dir} - @cindex Search paths, for @code{gnatmake} - @cindex @code{-A} (@code{gnatmake}) - Equivalent to @code{-aL@var{dir} - -aI@var{dir}}. - - @item -I@var{dir} - @cindex @code{-I} (@code{gnatmake}) - Equivalent to @code{-aO@var{dir} - -aI@var{dir}}. - - @item -I- - @cindex @code{-I-} (@code{gnatmake}) - @cindex Source files, suppressing search - Do not look for source files in the directory containing the source - file named in the command line. - Do not look for ALI or object files in the directory - where @code{gnatmake} was invoked. - - @item -L@var{dir} - @cindex @code{-L} (@code{gnatmake}) - @cindex Linker libraries - Add directory @var{dir} to the list of directories in which the linker - will search for libraries. This is equivalent to - @code{-largs -L}@var{dir}. - - @item -nostdinc - @cindex @code{-nostdinc} (@code{gnatmake}) - Do not look for source files in the system default directory. - - @item -nostdlib - @cindex @code{-nostdlib} (@code{gnatmake}) - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatmake}) - Specifies the default location of the runtime library. We look for the runtime - in the following directories, and stop as soon as a valid runtime is found - ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present): - - @itemize @bullet - @item /$rts_path - - @item /$rts_path - - @item /rts-$rts_path - @end itemize - - @noindent - The selected path is handled like a normal RTS path. - - @end table - - @node Mode Switches for gnatmake - @section Mode Switches for @code{gnatmake} - - @noindent - The mode switches (referred to as @code{mode_switches}) allow the - inclusion of switches that are to be passed to the compiler itself, the - binder or the linker. The effect of a mode switch is to cause all - subsequent switches up to the end of the switch list, or up to the next - mode switch, to be interpreted as switches to be passed on to the - designated component of GNAT. - - @table @code - @item -cargs @var{switches} - @cindex @code{-cargs} (@code{gnatmake}) - Compiler switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all compile steps performed by @code{gnatmake}. - - @item -bargs @var{switches} - @cindex @code{-bargs} (@code{gnatmake}) - Binder switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all bind steps performed by @code{gnatmake}. - - @item -largs @var{switches} - @cindex @code{-largs} (@code{gnatmake}) - Linker switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all link steps performed by @code{gnatmake}. - @end table - - @node Notes on the Command Line - @section Notes on the Command Line - - @noindent - This section contains some additional useful notes on the operation - of the @code{gnatmake} command. - - @itemize @bullet - @item - @cindex Recompilation, by @code{gnatmake} - If @code{gnatmake} finds no ALI files, it recompiles the main program - and all other units required by the main program. - This means that @code{gnatmake} - can be used for the initial compile, as well as during subsequent steps of - the development cycle. - - @item - If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb} - is a subunit or body of a generic unit, @code{gnatmake} recompiles - @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a - warning. - - @item - In @code{gnatmake} the switch @code{-I} - is used to specify both source and - library file paths. Use @code{-aI} - instead if you just want to specify - source paths only and @code{-aO} - if you want to specify library paths - only. - - @item - @code{gnatmake} examines both an ALI file and its corresponding object file - for consistency. If an ALI is more recent than its corresponding object, - or if the object file is missing, the corresponding source will be recompiled. - Note that @code{gnatmake} expects an ALI and the corresponding object file - to be in the same directory. - - @item - @code{gnatmake} will ignore any files whose ALI file is write-protected. - This may conveniently be used to exclude standard libraries from - consideration and in particular it means that the use of the - @code{-f} switch will not recompile these files - unless @code{-a} is also specified. - - @item - @code{gnatmake} has been designed to make the use of Ada libraries - particularly convenient. Assume you have an Ada library organized - as follows: @var{obj-dir} contains the objects and ALI files for - of your Ada compilation units, - whereas @var{include-dir} contains the - specs of these units, but no bodies. Then to compile a unit - stored in @code{main.adb}, which uses this Ada library you would just type - - @smallexample - $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main - @end smallexample - - @item - Using @code{gnatmake} along with the - @code{-m (minimal recompilation)} - switch provides a mechanism for avoiding unnecessary rcompilations. Using - this switch, - you can update the comments/format of your - source files without having to recompile everything. Note, however, that - adding or deleting lines in a source files may render its debugging - info obsolete. If the file in question is a spec, the impact is rather - limited, as that debugging info will only be useful during the - elaboration phase of your program. For bodies the impact can be more - significant. In all events, your debugger will warn you if a source file - is more recent than the corresponding object, and alert you to the fact - that the debugging information may be out of date. - @end itemize - - @node How gnatmake Works - @section How @code{gnatmake} Works - - @noindent - Generally @code{gnatmake} automatically performs all necessary - recompilations and you don't need to worry about how it works. However, - it may be useful to have some basic understanding of the @code{gnatmake} - approach and in particular to understand how it uses the results of - previous compilations without incorrectly depending on them. - - First a definition: an object file is considered @dfn{up to date} if the - corresponding ALI file exists and its time stamp predates that of the - object file and if all the source files listed in the - dependency section of this ALI file have time stamps matching those in - the ALI file. This means that neither the source file itself nor any - files that it depends on have been modified, and hence there is no need - to recompile this file. - - @code{gnatmake} works by first checking if the specified main unit is up - to date. If so, no compilations are required for the main unit. If not, - @code{gnatmake} compiles the main program to build a new ALI file that - reflects the latest sources. Then the ALI file of the main unit is - examined to find all the source files on which the main program depends, - and @code{gnatmake} recursively applies the above procedure on all these files. - - This process ensures that @code{gnatmake} only trusts the dependencies - in an existing ALI file if they are known to be correct. Otherwise it - always recompiles to determine a new, guaranteed accurate set of - dependencies. As a result the program is compiled "upside down" from what may - be more familiar as the required order of compilation in some other Ada - systems. In particular, clients are compiled before the units on which - they depend. The ability of GNAT to compile in any order is critical in - allowing an order of compilation to be chosen that guarantees that - @code{gnatmake} will recompute a correct set of new dependencies if - necessary. - - When invoking @code{gnatmake} with several @var{file_names}, if a unit is - imported by several of the executables, it will be recompiled at most once. - - @node Examples of gnatmake Usage - @section Examples of @code{gnatmake} Usage - - @table @code - @item gnatmake hello.adb - Compile all files necessary to bind and link the main program - @file{hello.adb} (containing unit @code{Hello}) and bind and link the - resulting object files to generate an executable file @file{hello}. - - @item gnatmake main1 main2 main3 - Compile all files necessary to bind and link the main programs - @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb} - (containing unit @code{Main2}) and @file{main3.adb} - (containing unit @code{Main3}) and bind and link the resulting object files - to generate three executable files @file{main1}, - @file{main2} - and @file{main3}. - - @item gnatmake -q Main_Unit -cargs -O2 -bargs -l - - Compile all files necessary to bind and link the main program unit - @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will - be done with optimization level 2 and the order of elaboration will be - listed by the binder. @code{gnatmake} will operate in quiet mode, not - displaying commands it is executing. - @end table - - @node Renaming Files Using gnatchop - @chapter Renaming Files Using @code{gnatchop} - @findex gnatchop - - @noindent - This chapter discusses how to handle files with multiple units by using - the @code{gnatchop} utility. This utility is also useful in renaming - files to meet the standard GNAT default file naming conventions. - - @menu - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - @end menu - - @node Handling Files with Multiple Units - @section Handling Files with Multiple Units - - @noindent - The basic compilation model of GNAT requires that a file submitted to the - compiler have only one unit and there be a strict correspondence - between the file name and the unit name. - - The @code{gnatchop} utility allows both of these rules to be relaxed, - allowing GNAT to process files which contain multiple compilation units - and files with arbitrary file names. @code{gnatchop} - reads the specified file and generates one or more output files, - containing one unit per file. The unit and the file name correspond, - as required by GNAT. - - If you want to permanently restructure a set of "foreign" files so that - they match the GNAT rules, and do the remaining development using the - GNAT structure, you can simply use @code{gnatchop} once, generate the - new set of files and work with them from that point on. - - Alternatively, if you want to keep your files in the "foreign" format, - perhaps to maintain compatibility with some other Ada compilation - system, you can set up a procedure where you use @code{gnatchop} each - time you compile, regarding the source files that it writes as temporary - files that you throw away. - - @node Operating gnatchop in Compilation Mode - @section Operating gnatchop in Compilation Mode - - @noindent - The basic function of @code{gnatchop} is to take a file with multiple units - and split it into separate files. The boundary between files is reasonably - clear, except for the issue of comments and pragmas. In default mode, the - rule is that any pragmas between units belong to the previous unit, except - that configuration pragmas always belong to the following unit. Any comments - belong to the following unit. These rules - almost always result in the right choice of - the split point without needing to mark it explicitly and most users will - find this default to be what they want. In this default mode it is incorrect to - submit a file containing only configuration pragmas, or one that ends in - configuration pragmas, to @code{gnatchop}. - - However, using a special option to activate "compilation mode", - @code{gnatchop} - can perform another function, which is to provide exactly the semantics - required by the RM for handling of configuration pragmas in a compilation. - In the absence of configuration pragmas (at the main file level), this - option has no effect, but it causes such configuration pragmas to be handled - in a quite different manner. - - First, in compilation mode, if @code{gnatchop} is given a file that consists of - only configuration pragmas, then this file is appended to the - @file{gnat.adc} file in the current directory. This behavior provides - the required behavior described in the RM for the actions to be taken - on submitting such a file to the compiler, namely that these pragmas - should apply to all subsequent compilations in the same compilation - environment. Using GNAT, the current directory, possibly containing a - @file{gnat.adc} file is the representation - of a compilation environment. For more information on the - @file{gnat.adc} file, see the section on handling of configuration - pragmas @pxref{Handling of Configuration Pragmas}. - - Second, in compilation mode, if @code{gnatchop} - is given a file that starts with - configuration pragmas, and contains one or more units, then these - configuration pragmas are prepended to each of the chopped files. This - behavior provides the required behavior described in the RM for the - actions to be taken on compiling such a file, namely that the pragmas - apply to all units in the compilation, but not to subsequently compiled - units. - - Finally, if configuration pragmas appear between units, they are appended - to the previous unit. This results in the previous unit being illegal, - since the compiler does not accept configuration pragmas that follow - a unit. This provides the required RM behavior that forbids configuration - pragmas other than those preceding the first compilation unit of a - compilation. - - For most purposes, @code{gnatchop} will be used in default mode. The - compilation mode described above is used only if you need exactly - accurate behavior with respect to compilations, and you have files - that contain multiple units and configuration pragmas. In this - circumstance the use of @code{gnatchop} with the compilation mode - switch provides the required behavior, and is for example the mode - in which GNAT processes the ACVC tests. - - @node Command Line for gnatchop - @section Command Line for @code{gnatchop} - - @noindent - The @code{gnatchop} command has the form: - - @smallexample - $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...] - [@var{directory}] - @end smallexample - - @noindent - The only required argument is the file name of the file to be chopped. - There are no restrictions on the form of this file name. The file itself - contains one or more Ada units, in normal GNAT format, concatenated - together. As shown, more than one file may be presented to be chopped. - - When run in default mode, @code{gnatchop} generates one output file in - the current directory for each unit in each of the files. - - @var{directory}, if specified, gives the name of the directory to which - the output files will be written. If it is not specified, all files are - written to the current directory. - - For example, given a - file called @file{hellofiles} containing - - @smallexample - @group - @cartouche - @b{procedure} hello; - - @b{with} Text_IO; @b{use} Text_IO; - @b{procedure} hello @b{is} - @b{begin} - Put_Line ("Hello"); - @b{end} hello; - @end cartouche - @end group - @end smallexample - - @noindent - the command - - @smallexample - $ gnatchop hellofiles - @end smallexample - - @noindent - generates two files in the current directory, one called - @file{hello.ads} containing the single line that is the procedure spec, - and the other called @file{hello.adb} containing the remaining text. The - original file is not affected. The generated files can be compiled in - the normal manner. - - @node Switches for gnatchop - @section Switches for @code{gnatchop} - - @noindent - @code{gnatchop} recognizes the following switches: - - @table @code - - @item -c - @cindex @code{-c} (@code{gnatchop}) - Causes @code{gnatchop} to operate in compilation mode, in which - configuration pragmas are handled according to strict RM rules. See - previous section for a full description of this mode. - - @item -gnatxxx - This passes the given @option{-gnatxxx} switch to @code{gnat} which is - used to parse the given file. Not all @code{xxx} options make sense, - but for example, the use of @option{-gnati2} allows @code{gnatchop} to - process a source file that uses Latin-2 coding for identifiers. - - @item -h - Causes @code{gnatchop} to generate a brief help summary to the standard - output file showing usage information. - - @item -k@var{mm} - @cindex @code{-k} (@code{gnatchop}) - Limit generated file names to the specified number @code{mm} - of characters. - This is useful if the - resulting set of files is required to be interoperable with systems - which limit the length of file names. - No space is allowed between the @code{-k} and the numeric value. The numeric - value may be omitted in which case a default of @code{-k8}, - suitable for use - with DOS-like file systems, is used. If no @code{-k} switch - is present then - there is no limit on the length of file names. - - @item -p - @cindex @code{-p} (@code{gnatchop}) - Causes the file modification time stamp of the input file to be - preserved and used for the time stamp of the output file(s). This may be - useful for preserving coherency of time stamps in an enviroment where - @code{gnatchop} is used as part of a standard build process. - - @item -q - @cindex @code{-q} (@code{gnatchop}) - Causes output of informational messages indicating the set of generated - files to be suppressed. Warnings and error messages are unaffected. - - @item -r - @cindex @code{-r} (@code{gnatchop}) - @findex Source_Reference - Generate @code{Source_Reference} pragmas. Use this switch if the output - files are regarded as temporary and development is to be done in terms - of the original unchopped file. This switch causes - @code{Source_Reference} pragmas to be inserted into each of the - generated files to refers back to the original file name and line number. - The result is that all error messages refer back to the original - unchopped file. - In addition, the debugging information placed into the object file (when - the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also - refers back to this original file so that tools like profilers and - debuggers will give information in terms of the original unchopped file. - - If the original file to be chopped itself contains - a @code{Source_Reference} - pragma referencing a third file, then gnatchop respects - this pragma, and the generated @code{Source_Reference} pragmas - in the chopped file refer to the original file, with appropriate - line numbers. This is particularly useful when @code{gnatchop} - is used in conjunction with @code{gnatprep} to compile files that - contain preprocessing statements and multiple units. - - @item -v - @cindex @code{-v} (@code{gnatchop}) - Causes @code{gnatchop} to operate in verbose mode. The version - number and copyright notice are output, as well as exact copies of - the gnat1 commands spawned to obtain the chop control information. - - @item -w - @cindex @code{-w} (@code{gnatchop}) - Overwrite existing file names. Normally @code{gnatchop} regards it as a - fatal error if there is already a file with the same name as a - file it would otherwise output, in other words if the files to be - chopped contain duplicated units. This switch bypasses this - check, and causes all but the last instance of such duplicated - units to be skipped. - - @item --GCC=xxxx - @cindex @code{--GCC=} (@code{gnatchop}) - Specify the path of the GNAT parser to be used. When this switch is used, - no attempt is made to add the prefix to the GNAT parser executable. - @end table - - @node Examples of gnatchop Usage - @section Examples of @code{gnatchop} Usage - - @table @code - @item gnatchop -w hello_s.ada ichbiah/files - - Chops the source file @file{hello_s.ada}. The output files will be - placed in the directory @file{ichbiah/files}, - overwriting any - files with matching names in that directory (no files in the current - directory are modified). - - @item gnatchop archive - Chops the source file @file{archive} - into the current directory. One - useful application of @code{gnatchop} is in sending sets of sources - around, for example in email messages. The required sources are simply - concatenated (for example, using a Unix @code{cat} - command), and then - @code{gnatchop} is used at the other end to reconstitute the original - file names. - - @item gnatchop file1 file2 file3 direc - Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing - the resulting files in the directory @file{direc}. Note that if any units - occur more than once anywhere within this set of files, an error message - is generated, and no files are written. To override this check, use the - @code{-w} switch, - in which case the last occurrence in the last file will - be the one that is output, and earlier duplicate occurrences for a given - unit will be skipped. - @end table - - @node Configuration Pragmas - @chapter Configuration Pragmas - @cindex Configuration pragmas - @cindex Pragmas, configuration - - @noindent - In Ada 95, configuration pragmas include those pragmas described as - such in the Ada 95 Reference Manual, as well as - implementation-dependent pragmas that are configuration pragmas. See the - individual descriptions of pragmas in the GNAT Reference Manual for - details on these additional GNAT-specific configuration pragmas. Most - notably, the pragma @code{Source_File_Name}, which allows - specifying non-default names for source files, is a configuration - pragma. The following is a complete list of configuration pragmas - recognized by @code{GNAT}: - - @smallexample - Ada_83 - Ada_95 - C_Pass_By_Copy - Component_Alignment - Discard_Names - Elaboration_Checks - Eliminate - Extend_System - Extensions_Allowed - External_Name_Casing - Float_Representation - Initialize_Scalars - License - Locking_Policy - Long_Float - No_Run_Time - Normalize_Scalars - Polling - Propagate_Exceptions - Queuing_Policy - Ravenscar - Restricted_Run_Time - Restrictions - Reviewable - Source_File_Name - Style_Checks - Suppress - Task_Dispatching_Policy - Unsuppress - Use_VADS_Size - Warnings - Validity_Checks - @end smallexample - - @menu - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - @end menu - - @node Handling of Configuration Pragmas - @section Handling of Configuration Pragmas - - Configuration pragmas may either appear at the start of a compilation - unit, in which case they apply only to that unit, or they may apply to - all compilations performed in a given compilation environment. - - GNAT also provides the @code{gnatchop} utility to provide an automatic - way to handle configuration pragmas following the semantics for - compilations (that is, files with multiple units), described in the RM. - See section @pxref{Operating gnatchop in Compilation Mode} for details. - However, for most purposes, it will be more convenient to edit the - @file{gnat.adc} file that contains configuration pragmas directly, - as described in the following section. - - @node The Configuration Pragmas Files - @section The Configuration Pragmas Files - @cindex @file{gnat.adc} - - @noindent - In GNAT a compilation environment is defined by the current - directory at the time that a compile command is given. This current - directory is searched for a file whose name is @file{gnat.adc}. If - this file is present, it is expected to contain one or more - configuration pragmas that will be applied to the current compilation. - However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not - considered. - - Configuration pragmas may be entered into the @file{gnat.adc} file - either by running @code{gnatchop} on a source file that consists only of - configuration pragmas, or more conveniently by - direct editing of the @file{gnat.adc} file, which is a standard format - source file. - - In addition to @file{gnat.adc}, one additional file containing configuration - pragmas may be applied to the current compilation using the switch - @option{-gnatec}@var{path}. @var{path} must designate an existing file that - contains only configuration pragmas. These configuration pragmas are - in addition to those found in @file{gnat.adc} (provided @file{gnat.adc} - is present and switch @option{-gnatA} is not used). - - It is allowed to specify several switches @option{-gnatec}, however only - the last one on the command line will be taken into account. - - - @node Handling Arbitrary File Naming Conventions Using gnatname - @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} - @cindex Arbitrary File Naming Conventions - - @menu - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - @end menu - - @node Arbitrary File Naming Conventions - @section Arbitrary File Naming Conventions - - @noindent - The GNAT compiler must be able to know the source file name of a compilation unit. - When using the standard GNAT default file naming conventions (@code{.ads} for specs, - @code{.adb} for bodies), the GNAT compiler does not need additional information. - - @noindent - When the source file names do not follow the standard GNAT default file naming - conventions, the GNAT compiler must be given additional information through - a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file. - When the non standard file naming conventions are well-defined, a small number of - pragmas @code{Source_File_Name} specifying a naming pattern - (see @ref{Alternative File Naming Schemes}) may be sufficient. However, - if the file naming conventions are irregular or arbitrary, a number - of pragma @code{Source_File_Name} for individual compilation units must be defined. - To help maintain the correspondence between compilation unit names and - source file names within the compiler, - GNAT provides a tool @code{gnatname} to generate the required pragmas for a - set of files. - - @node Running gnatname - @section Running @code{gnatname} - - @noindent - The usual form of the @code{gnatname} command is - - @smallexample - $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}] - @end smallexample - - @noindent - All of the arguments are optional. If invoked without any argument, - @code{gnatname} will display its usage. - - @noindent - When used with at least one naming pattern, @code{gnatname} will attempt to - find all the compilation units in files that follow at least one of the - naming patterns. To find these compilation units, - @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all - regular files. - - @noindent - One or several Naming Patterns may be given as arguments to @code{gnatname}. - Each Naming Pattern is enclosed between double quotes. - A Naming Pattern is a regular expression similar to the wildcard patterns - used in file names by the Unix shells or the DOS prompt. - - @noindent - Examples of Naming Patterns are - - @smallexample - "*.[12].ada" - "*.ad[sb]*" - "body_*" "spec_*" - @end smallexample - - @noindent - For a more complete description of the syntax of Naming Patterns, see the second kind - of regular expressions described in @file{g-regexp.ads} (the "Glob" regular - expressions). - - @noindent - When invoked with no switches, @code{gnatname} will create a configuration - pragmas file @file{gnat.adc} in the current working directory, with pragmas - @code{Source_File_Name} for each file that contains a valid Ada unit. - - @node Switches for gnatname - @section Switches for @code{gnatname} - - @noindent - Switches for @code{gnatname} must precede any specified Naming Pattern. - - @noindent - You may specify any of the following switches to @code{gnatname}: - - @table @code - - @item -c@file{file} - @cindex @code{-c} (@code{gnatname}) - Create a configuration pragmas file @file{file} (instead of the default - @file{gnat.adc}). There may be zero, one or more space between @code{-c} and - @file{file}. @file{file} may include directory information. @file{file} must be - writeable. There may be only one switch @code{-c}. When a switch @code{-c} is - specified, no switch @code{-P} may be specified (see below). - - @item -d@file{dir} - @cindex @code{-d} (@code{gnatname}) - Look for source files in directory @file{dir}. There may be zero, one or more spaces - between @code{-d} and @file{dir}. When a switch @code{-d} is specified, - the current working directory will not be searched for source files, unless it - is explictly - specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be - specified. If @file{dir} is a relative path, it is relative to the directory of - the configuration pragmas file specified with switch @code{-c}, or to the directory - of the project file specified with switch @code{-P} or, if neither switch @code{-c} - nor switch @code{-P} are specified, it is relative to the current working - directory. The directory - specified with switch @code{-c} must exist and be readable. - - @item -D@file{file} - @cindex @code{-D} (@code{gnatname}) - Look for source files in all directories listed in text file @file{file}. There may be - zero, one or more spaces between @code{-d} and @file{dir}. @file{file} - must be an existing, readable text file. Each non empty line in @file{file} must be - a directory. Specifying switch @code{-D} is equivalent to specifying as many switches - @code{-d} as there are non empty lines in @file{file}. - - @item -h - @cindex @code{-h} (@code{gnatname}) - Output usage (help) information. The output is written to @file{stdout}. - - @item -P@file{proj} - @cindex @code{-P} (@code{gnatname}) - Create or update project file @file{proj}. There may be zero, one or more space - between @code{-P} and @file{proj}. @file{proj} may include directory information. - @file{proj} must be writeable. There may be only one switch @code{-P}. - When a switch @code{-P} is specified, no switch @code{-c} may be specified. - - @item -v - @cindex @code{-v} (@code{gnatname}) - Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes - name of the file written, the name of the directories to search and, for each file - in those directories whose name matches at least one of the Naming Patterns, an - indication of whether the file contains a unit, and if so the name of the unit. - - @item -v -v - Very Verbose mode. In addition to the output produced in verbose mode, for each file - in the searched directories whose name matches none of the Naming Patterns, an - indication is given that there is no match. - - @item -x@file{pattern} - Excluded patterns. Using this switch, it is possible to exclude some files - that would match the name patterns. For example, - @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files - with the @file{.ada} extension, except those whose names end with - @file{_nt.ada}. - - @end table - - @node Examples of gnatname Usage - @section Examples of @code{gnatname} Usage - - @smallexample - $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" - @end smallexample - - In this example, the directory @file{/home/me} must already exist and be - writeable. In addition, the directory @file{/home/me/sources} (specified by - @code{-d sources}) must exist and be readable. Note the optional spaces after - @code{-c} and @code{-d}. - - @smallexample - $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" - @end smallexample - - Note that several switches @code{-d} may be used, even in conjunction with one - or several switches @code{-D}. Several Naming Patterns and one excluded pattern - are used in this example. - - - @c ***************************************** - @c * G N A T P r o j e c t M a n a g e r * - @c ***************************************** - @node GNAT Project Manager - @chapter GNAT Project Manager - - @menu - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - @end menu - - - @c **************** - @c * Introduction * - @c **************** - - @node Introduction - @section Introduction - - @noindent - This chapter describes GNAT's @emph{Project Manager}, a facility that - lets you configure various properties for a collection of source files. In - particular, you can specify: - @itemize @bullet - @item - The directory or set of directories containing the source files, and/or the - names of the specific source files themselves - @item - The directory in which the compiler's output - (@file{ALI} files, object files, tree files) will be placed - @item - The directory in which the executable programs will be placed - @item - Switch settings for any of the project-enabled tools (@command{gnatmake}, - compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind}); - you can apply these settings either globally or to individual units - @item - The source files containing the main subprogram(s) to be built - @item - The source programming language(s) (currently Ada and/or C) - @item - Source file naming conventions; you can specify these either globally or for - individual units - @end itemize - - @menu - * Project Files:: - @end menu - - @node Project Files - @subsection Project Files - - @noindent - A @dfn{project} is a specific set of values for these properties. You can - define a project's settings in a @dfn{project file}, a text file with an - Ada-like syntax; a property value is either a string or a list of strings. - Properties that are not explicitly set receive default values. A project - file may interrogate the values of @dfn{external variables} (user-defined - command-line switches or environment variables), and it may specify property - settings conditionally, based on the value of such variables. - - In simple cases, a project's source files depend only on other source files - in the same project, or on the predefined libraries. ("Dependence" is in - the technical sense; for example, one Ada unit "with"ing another.) However, - the Project Manager also allows much more sophisticated arrangements, - with the source files in one project depending on source files in other - projects: - @itemize @bullet - @item - One project can @emph{import} other projects containing needed source files. - @item - You can organize GNAT projects in a hierarchy: a @emph{child} project - can extend a @emph{parent} project, inheriting the parent's source files and - optionally overriding any of them with alternative versions - @end itemize - - @noindent - More generally, the Project Manager lets you structure large development - efforts into hierarchical subsystems, with build decisions deferred to the - subsystem level and thus different compilation environments (switch settings) - used for different subsystems. - - The Project Manager is invoked through the @option{-P@emph{projectfile}} - switch to @command{gnatmake} or to the @command{gnat} front driver. - If you want to define (on the command line) an external variable that is - queried by the project file, additionally use the - @option{-X@emph{vbl}=@emph{value}} switch. - The Project Manager parses and interprets the project file, and drives the - invoked tool based on the project settings. - - The Project Manager supports a wide range of development strategies, - for systems of all sizes. Some typical practices that are easily handled: - @itemize @bullet - @item - Using a common set of source files, but generating object files in different - directories via different switch settings - @item - Using a mostly-shared set of source files, but with different versions of - some unit or units - @end itemize - - @noindent - The destination of an executable can be controlled inside a project file - using the @option{-o} switch. In the absence of such a switch either inside - the project file or on the command line, any executable files generated by - @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified - in the project file. If no @code{Exec_Dir} is specified, they will be placed - in the object directory of the project. - - You can use project files to achieve some of the effects of a source - versioning system (for example, defining separate projects for - the different sets of sources that comprise different releases) but the - Project Manager is independent of any source configuration management tools - that might be used by the developers. - - The next section introduces the main features of GNAT's project facility - through a sequence of examples; subsequent sections will present the syntax - and semantics in more detail. - - - @c ***************************** - @c * Examples of Project Files * - @c ***************************** - - @node Examples of Project Files - @section Examples of Project Files - @noindent - This section illustrates some of the typical uses of project files and - explains their basic structure and behavior. - - @menu - * Common Sources with Different Switches and Different Output Directories:: - * Using External Variables:: - * Importing Other Projects:: - * Extending a Project:: - @end menu - - @node Common Sources with Different Switches and Different Output Directories - @subsection Common Sources with Different Switches and Different Output Directories - - @menu - * Source Files:: - * Specifying the Object Directory:: - * Specifying the Exec Directory:: - * Project File Packages:: - * Specifying Switch Settings:: - * Main Subprograms:: - * Source File Naming Conventions:: - * Source Language(s):: - @end menu - - @noindent - Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and - @file{proc.adb} are in the @file{/common} directory. The file - @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s - package @code{Pack}. We want to compile these source files under two sets - of switches: - @itemize @bullet - @item - When debugging, we want to pass the @option{-g} switch to @command{gnatmake}, - and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the - compiler; the compiler's output is to appear in @file{/common/debug} - @item - When preparing a release version, we want to pass the @option{-O2} switch to - the compiler; the compiler's output is to appear in @file{/common/release} - @end itemize - - @noindent - The GNAT project files shown below, respectively @file{debug.gpr} and - @file{release.gpr} in the @file{/common} directory, achieve these effects. - - Diagrammatically: - @smallexample - @group - /common - debug.gpr - release.gpr - pack.ads - pack.adb - proc.adb - @end group - @group - /common/debug @{-g, -gnata, -gnato, -gnatE@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @group - /common/release @{-O2@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @end smallexample - Here are the project files: - @smallexample - @group - project Debug is - for Object_Dir use "debug"; - for Main use ("proc"); - - package Builder is - for Default_Switches ("Ada") use ("-g"); - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") - use ("-fstack-check", "-gnata", "-gnato", "-gnatE"); - end Compiler; - end Debug; - @end group - @end smallexample - - @smallexample - @group - project Release is - for Object_Dir use "release"; - for Exec_Dir use "."; - for Main use ("proc"); - - package Compiler is - for Default_Switches ("Ada") use ("-O2"); - end Compiler; - end Release; - @end group - @end smallexample - - @noindent - The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case - insensitive), and analogously the project defined by @file{release.gpr} is - @code{"Release"}. For consistency the file should have the same name as the - project, and the project file's extension should be @code{"gpr"}. These - conventions are not required, but a warning is issued if they are not followed. - - If the current directory is @file{/temp}, then the command - @smallexample - gnatmake -P/common/debug.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/debug}, and the @code{proc} - executable also in @file{/common/debug}, using the switch settings defined in - the project file. - - Likewise, the command - @smallexample - gnatmake -P/common/release.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/release}, and the @code{proc} - executable in @file{/common}, using the switch settings from the project file. - - @node Source Files - @unnumberedsubsubsec Source Files - - @noindent - If a project file does not explicitly specify a set of source directories or - a set of source files, then by default the project's source files are the - Ada source files in the project file directory. Thus @file{pack.ads}, - @file{pack.adb}, and @file{proc.adb} are the source files for both projects. - - @node Specifying the Object Directory - @unnumberedsubsubsec Specifying the Object Directory - - @noindent - Several project properties are modeled by Ada-style @emph{attributes}; - you define the property by supplying the equivalent of an Ada attribute - definition clause in the project file. - A project's object directory is such a property; the corresponding - attribute is @code{Object_Dir}, and its value is a string expression. A - directory may be specified either as absolute or as relative; in the latter - case, it is relative to the project file directory. Thus the compiler's - output is directed to @file{/common/debug} (for the @code{Debug} project) - and to @file{/common/release} (for the @code{Release} project). If - @code{Object_Dir} is not specified, then the default is the project file - directory. - - @node Specifying the Exec Directory - @unnumberedsubsubsec Specifying the Exec Directory - - @noindent - A project's exec directory is another property; the corresponding - attribute is @code{Exec_Dir}, and its value is also a string expression, - either specified as relative or absolute. If @code{Exec_Dir} is not specified, - then the default is the object directory (which may also be the project file - directory if attribute @code{Object_Dir} is not specified). Thus the executable - is placed in @file{/common/debug} for the @code{Debug} project (attribute - @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release} - project. - - @node Project File Packages - @unnumberedsubsubsec Project File Packages - - @noindent - A GNAT tool integrated with the Project Manager is modeled by a - corresponding package in the project file. - The @code{Debug} project defines the packages @code{Builder} - (for @command{gnatmake}) and @code{Compiler}; - the @code{Release} project defines only the @code{Compiler} package. - - The Ada package syntax is not to be taken literally. Although packages in - project files bear a surface resemblance to packages in Ada source code, the - notation is simply a way to convey a grouping of properties for a named - entity. Indeed, the package names permitted in project files are restricted - to a predefined set, corresponding to the project-aware tools, and the contents - of packages are limited to a small set of constructs. - The packages in the example above contain attribute definitions. - - - @node Specifying Switch Settings - @unnumberedsubsubsec Specifying Switch Settings - - @noindent - Switch settings for a project-aware tool can be specified through attributes - in the package corresponding to the tool. - The example above illustrates one of the relevant attributes, - @code{Default_Switches}, defined in the packages in both project files. - Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is - known as an @emph{associative array}. When you define this attribute, you must - supply an "index" (a literal string), and the effect of the attribute - definition is to set the value of the "array" at the specified "index". - For the @code{Default_Switches} attribute, the index is a programming - language (in our case, Ada) , and the value specified (after @code{use}) - must be a list of string expressions. - - The attributes permitted in project files are restricted to a predefined set. - Some may appear at project level, others in packages. - For any attribute that is an associate array, the index must always be a - literal string, but the restrictions on this string (e.g., a file name or a - language name) depend on the individual attribute. - Also depending on the attribute, its specified value will need to be either a - string or a string list. - - In the @code{Debug} project, we set the switches for two tools, - @command{gnatmake} and the compiler, and thus we include corresponding - packages, with each package defining the @code{Default_Switches} attribute - with index @code{"Ada"}. - Note that the package corresponding to - @command{gnatmake} is named @code{Builder}. The @code{Release} project is - similar, but with just the @code{Compiler} package. - - In project @code{Debug} above the switches starting with @option{-gnat} that - are specified in package @code{Compiler} could have been placed in package - @code{Builder}, since @command{gnatmake} transmits all such switches to the - compiler. - - @node Main Subprograms - @unnumberedsubsubsec Main Subprograms - - @noindent - One of the properties of a project is its list of main subprograms (actually - a list of names of source files containing main subprograms, with the file - extension optional. This property is captured in the @code{Main} attribute, - whose value is a list of strings. If a project defines the @code{Main} - attribute, then you do not need to identify the main subprogram(s) when - invoking @command{gnatmake} (see @ref{gnatmake and Project Files}). - - @node Source File Naming Conventions - @unnumberedsubsubsec Source File Naming Conventions - - @noindent - Since the project files do not specify any source file naming conventions, - the GNAT defaults are used. The mechanism for defining source file naming - conventions -- a package named @code{Naming} -- will be described below - (@pxref{Naming Schemes}). - - @node Source Language(s) - @unnumberedsubsubsec Source Language(s) - - @noindent - Since the project files do not specify a @code{Languages} attribute, by - default the GNAT tools assume that the language of the project file is Ada. - More generally, a project can comprise source files - in Ada, C, and/or other languages. - - @node Using External Variables - @subsection Using External Variables - - @noindent - Instead of supplying different project files for debug and release, we can - define a single project file that queries an external variable (set either - on the command line or via an environment variable) in order to - conditionally define the appropriate settings. Again, assume that the - source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are - located in directory @file{/common}. The following project file, - @file{build.gpr}, queries the external variable named @code{STYLE} and - defines an object directory and switch settings based on whether the value - is @code{"deb"} (debug) or @code{"rel"} (release), where the default is - @code{"deb"}. - - @smallexample - @group - project Build is - for Main use ("proc"); - - type Style_Type is ("deb", "rel"); - Style : Style_Type := external ("STYLE", "deb"); - - case Style is - when "deb" => - for Object_Dir use "debug"; - - when "rel" => - for Object_Dir use "release"; - for Exec_Dir use "."; - end case; - @end group - - @group - package Builder is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-g"); - end case; - - end Builder; - @end group - - @group - package Compiler is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE"); - - when "rel" => - for Default_Switches ("Ada") use ("-O2"); - end case; - - end Compiler; - - end Build; - @end group - @end smallexample - - @noindent - @code{Style_Type} is an example of a @emph{string type}, which is the project - file analog of an Ada enumeration type but containing string literals rather - than identifiers. @code{Style} is declared as a variable of this type. - - The form @code{external("STYLE", "deb")} is known as an - @emph{external reference}; its first argument is the name of an - @emph{external variable}, and the second argument is a default value to be - used if the external variable doesn't exist. You can define an external - variable on the command line via the @option{-X} switch, or you can use an - environment variable as an external variable. - - Each @code{case} construct is expanded by the Project Manager based on the - value of @code{Style}. Thus the command - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=deb - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{debug.gpr} in the earlier example. So is the command - @smallexample - gnatmake -P/common/build.gpr - @end smallexample - - @noindent - since @code{"deb"} is the default for @code{STYLE}. - - Analogously, - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=rel - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{release.gpr} in the earlier example. - - - @node Importing Other Projects - @subsection Importing Other Projects - - @noindent - A compilation unit in a source file in one project may depend on compilation - units in source files in other projects. To obtain this behavior, the - dependent project must @emph{import} the projects containing the needed source - files. This effect is embodied in syntax similar to an Ada @code{with} clause, - but the "with"ed entities are strings denoting project files. - - As an example, suppose that the two projects @code{GUI_Proj} and - @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and - @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm}, - respectively. Assume that the source files for @code{GUI_Proj} are - @file{gui.ads} and @file{gui.adb}, and that the source files for - @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of - files located in its respective project file directory. Diagrammatically: - - @smallexample - @group - /gui - gui_proj.gpr - gui.ads - gui.adb - @end group - - @group - /comm - comm_proj.gpr - comm.ads - comm.adb - @end group - @end smallexample - - @noindent - We want to develop an application in directory @file{/app} that "with"s the - packages @code{GUI} and @code{Comm}, using the properties of the - corresponding project files (e.g. the switch settings and object directory). - Skeletal code for a main procedure might be something like the following: - - @smallexample - @group - with GUI, Comm; - procedure App_Main is - ... - begin - ... - end App_Main; - @end group - @end smallexample - - @noindent - Here is a project file, @file{app_proj.gpr}, that achieves the desired - effect: - - @smallexample - @group - with "/gui/gui_proj", "/comm/comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Building an executable is achieved through the command: - @smallexample - gnatmake -P/app/app_proj - @end smallexample - @noindent - which will generate the @code{app_main} executable in the directory where - @file{app_proj.gpr} resides. - - If an imported project file uses the standard extension (@code{gpr}) then - (as illustrated above) the @code{with} clause can omit the extension. - - Our example specified an absolute path for each imported project file. - Alternatively, you can omit the directory if either - @itemize @bullet - @item - The imported project file is in the same directory as the importing project - file, or - @item - You have defined an environment variable @code{ADA_PROJECT_PATH} that - includes the directory containing the needed project file. - @end itemize - - @noindent - Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and - @file{/comm}, then our project file @file{app_proj.gpr} could be written as - follows: - - @smallexample - @group - with "gui_proj", "comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Importing other projects raises the possibility of ambiguities. For - example, the same unit might be present in different imported projects, or - it might be present in both the importing project and an imported project. - Both of these conditions are errors. Note that in the current version of - the Project Manager, it is illegal to have an ambiguous unit even if the - unit is never referenced by the importing project. This restriction may be - relaxed in a future release. - - @node Extending a Project - @subsection Extending a Project - - @noindent - A common situation in large software systems is to have multiple - implementations for a common interface; in Ada terms, multiple versions of a - package body for the same specification. For example, one implementation - might be safe for use in tasking programs, while another might only be used - in sequential applications. This can be modeled in GNAT using the concept - of @emph{project extension}. If one project (the "child") @emph{extends} - another project (the "parent") then by default all source files of the - parent project are inherited by the child, but the child project can - override any of the parent's source files with new versions, and can also - add new files. This facility is the project analog of extension in - Object-Oriented Programming. Project hierarchies are permitted (a child - project may be the parent of yet another project), and a project that - inherits one project can also import other projects. - - As an example, suppose that directory @file{/seq} contains the project file - @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb}, - and @file{proc.adb}: - - @smallexample - @group - /seq - pack.ads - pack.adb - proc.adb - seq_proj.gpr - @end group - @end smallexample - - @noindent - Note that the project file can simply be empty (that is, no attribute or - package is defined): - - @smallexample - @group - project Seq_Proj is - end Seq_Proj; - @end group - @end smallexample - - @noindent - implying that its source files are all the Ada source files in the project - directory. - - Suppose we want to supply an alternate version of @file{pack.adb}, in - directory @file{/tasking}, but use the existing versions of @file{pack.ads} - and @file{proc.adb}. We can define a project @code{Tasking_Proj} that - inherits @code{Seq_Proj}: - - @smallexample - @group - /tasking - pack.adb - tasking_proj.gpr - @end group - - @group - project Tasking_Proj extends "/seq/seq_proj" is - end Tasking_Proj; - @end group - @end smallexample - - @noindent - The version of @file{pack.adb} used in a build depends on which project file - is specified. - - Note that we could have designed this using project import rather than - project inheritance; a @code{base} project would contain the sources for - @file{pack.ads} and @file{proc.adb}, a sequential project would import - @code{base} and add @file{pack.adb}, and likewise a tasking project would - import @code{base} and add a different version of @file{pack.adb}. The - choice depends on whether other sources in the original project need to be - overridden. If they do, then project extension is necessary, otherwise, - importing is sufficient. - - - @c *********************** - @c * Project File Syntax * - @c *********************** - - @node Project File Syntax - @section Project File Syntax - - @menu - * Basic Syntax:: - * Packages:: - * Expressions:: - * String Types:: - * Variables:: - * Attributes:: - * Associative Array Attributes:: - * case Constructions:: - @end menu - - @noindent - This section describes the structure of project files. - - A project may be an @emph{independent project}, entirely defined by a single - project file. Any Ada source file in an independent project depends only - on the predefined library and other Ada source files in the same project. - - @noindent - A project may also @dfn{depend on} other projects, in either or both of the following ways: - @itemize @bullet - @item It may import any number of projects - @item It may extend at most one other project - @end itemize - - @noindent - The dependence relation is a directed acyclic graph (the subgraph reflecting - the "extends" relation is a tree). - - A project's @dfn{immediate sources} are the source files directly defined by - that project, either implicitly by residing in the project file's directory, - or explicitly through any of the source-related attributes described below. - More generally, a project @var{proj}'s @dfn{sources} are the immediate sources - of @var{proj} together with the immediate sources (unless overridden) of any - project on which @var{proj} depends (either directly or indirectly). - - @node Basic Syntax - @subsection Basic Syntax - - @noindent - As seen in the earlier examples, project files have an Ada-like syntax. - The minimal project file is: - @smallexample - @group - project Empty is - - end Empty; - @end group - @end smallexample - - @noindent - The identifier @code{Empty} is the name of the project. - This project name must be present after the reserved - word @code{end} at the end of the project file, followed by a semi-colon. - - Any name in a project file, such as the project name or a variable name, - has the same syntax as an Ada identifier. - - The reserved words of project files are the Ada reserved words plus - @code{extends}, @code{external}, and @code{project}. Note that the only Ada - reserved words currently used in project file syntax are: - - @itemize @bullet - @item - @code{case} - @item - @code{end} - @item - @code{for} - @item - @code{is} - @item - @code{others} - @item - @code{package} - @item - @code{renames} - @item - @code{type} - @item - @code{use} - @item - @code{when} - @item - @code{with} - @end itemize - - @noindent - Comments in project files have the same syntax as in Ada, two consecutives - hyphens through the end of the line. - - @node Packages - @subsection Packages - - @noindent - A project file may contain @emph{packages}. The name of a package must be one - of the identifiers (case insensitive) from a predefined list, and a package - with a given name may only appear once in a project file. The predefined list - includes the following packages: - - @itemize @bullet - @item - @code{Naming} - @item - @code{Builder} - @item - @code{Compiler} - @item - @code{Binder} - @item - @code{Linker} - @item - @code{Finder} - @item - @code{Cross_Reference} - @item - @code{gnatls} - @end itemize - - @noindent - (The complete list of the package names and their attributes can be found - in file @file{prj-attr.adb}). - - @noindent - In its simplest form, a package may be empty: - - @smallexample - @group - project Simple is - package Builder is - end Builder; - end Simple; - @end group - @end smallexample - - @noindent - A package may contain @emph{attribute declarations}, - @emph{variable declarations} and @emph{case constructions}, as will be - described below. - - When there is ambiguity between a project name and a package name, - the name always designates the project. To avoid possible confusion, it is - always a good idea to avoid naming a project with one of the - names allowed for packages or any name that starts with @code{gnat}. - - - @node Expressions - @subsection Expressions - - @noindent - An @emph{expression} is either a @emph{string expression} or a - @emph{string list expression}. - - A @emph{string expression} is either a @emph{simple string expression} or a - @emph{compound string expression}. - - A @emph{simple string expression} is one of the following: - @itemize @bullet - @item A literal string; e.g.@code{"comm/my_proj.gpr"} - @item A string-valued variable reference (see @ref{Variables}) - @item A string-valued attribute reference (see @ref{Attributes}) - @item An external reference (see @ref{External References in Project Files}) - @end itemize - - @noindent - A @emph{compound string expression} is a concatenation of string expressions, - using @code{"&"} - @smallexample - Path & "/" & File_Name & ".ads" - @end smallexample - - @noindent - A @emph{string list expression} is either a - @emph{simple string list expression} or a - @emph{compound string list expression}. - - A @emph{simple string list expression} is one of the following: - @itemize @bullet - @item A parenthesized list of zero or more string expressions, separated by commas - @smallexample - File_Names := (File_Name, "gnat.adc", File_Name & ".orig"); - Empty_List := (); - @end smallexample - @item A string list-valued variable reference - @item A string list-valued attribute reference - @end itemize - - @noindent - A @emph{compound string list expression} is the concatenation (using - @code{"&"}) of a simple string list expression and an expression. Note that - each term in a compound string list expression, except the first, may be - either a string expression or a string list expression. - - @smallexample - @group - File_Name_List := () & File_Name; -- One string in this list - Extended_File_Name_List := File_Name_List & (File_Name & ".orig"); - -- Two strings - Big_List := File_Name_List & Extended_File_Name_List; - -- Concatenation of two string lists: three strings - Illegal_List := "gnat.adc" & Extended_File_Name_List; - -- Illegal: must start with a string list - @end group - @end smallexample - - - @node String Types - @subsection String Types - - @noindent - The value of a variable may be restricted to a list of string literals. - The restricted list of string literals is given in a - @emph{string type declaration}. - - Here is an example of a string type declaration: - - @smallexample - type OS is ("NT, "nt", "Unix", "Linux", "other OS"); - @end smallexample - - @noindent - Variables of a string type are called @emph{typed variables}; all other - variables are called @emph{untyped variables}. Typed variables are - particularly useful in @code{case} constructions - (see @ref{case Constructions}). - - A string type declaration starts with the reserved word @code{type}, followed - by the name of the string type (case-insensitive), followed by the reserved - word @code{is}, followed by a parenthesized list of one or more string literals - separated by commas, followed by a semicolon. - - The string literals in the list are case sensitive and must all be different. - They may include any graphic characters allowed in Ada, including spaces. - - A string type may only be declared at the project level, not inside a package. - - A string type may be referenced by its name if it has been declared in the same - project file, or by its project name, followed by a dot, - followed by the string type name. - - - @node Variables - @subsection Variables - - @noindent - A variable may be declared at the project file level, or in a package. - Here are some examples of variable declarations: - - @smallexample - @group - This_OS : OS := external ("OS"); -- a typed variable declaration - That_OS := "Linux"; -- an untyped variable declaration - @end group - @end smallexample - - @noindent - A @emph{typed variable declaration} includes the variable name, followed by a colon, - followed by the name of a string type, followed by @code{:=}, followed by - a simple string expression. - - An @emph{untyped variable declaration} includes the variable name, - followed by @code{:=}, followed by an expression. Note that, despite the - terminology, this form of "declaration" resembles more an assignment - than a declaration in Ada. It is a declaration in several senses: - @itemize @bullet - @item - The variable name does not need to be defined previously - @item - The declaration establishes the @emph{kind} (string versus string list) of the - variable, and later declarations of the same variable need to be consistent - with this - @end itemize - - @noindent - A string variable declaration (typed or untyped) declares a variable - whose value is a string. This variable may be used as a string expression. - @smallexample - File_Name := "readme.txt"; - Saved_File_Name := File_Name & ".saved"; - @end smallexample - - @noindent - A string list variable declaration declares a variable whose value is a list - of strings. The list may contain any number (zero or more) of strings. - - @smallexample - Empty_List := (); - List_With_One_Element := ("-gnaty"); - List_With_Two_Elements := List_With_One_Element & "-gnatg"; - Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada" - "pack2.ada", "util_.ada", "util.ada"); - @end smallexample - - @noindent - The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable. - - The same untyped variable may be declared several times. - In this case, the new value replaces the old one, - and any subsequent reference to the variable uses the new value. - However, as noted above, if a variable has been declared as a string, all subsequent - declarations must give it a string value. Similarly, if a variable has - been declared as a string list, all subsequent declarations - must give it a string list value. - - A @emph{variable reference} may take several forms: - - @itemize @bullet - @item The simple variable name, for a variable in the current package (if any) or in the current project - @item A context name, followed by a dot, followed by the variable name. - @end itemize - - @noindent - A @emph{context} may be one of the following: - - @itemize @bullet - @item The name of an existing package in the current project - @item The name of an imported project of the current project - @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly) - @item An imported/parent project name, followed by a dot, followed by a package name - @end itemize - - @noindent - A variable reference may be used in an expression. - - - @node Attributes - @subsection Attributes - - @noindent - A project (and its packages) may have @emph{attributes} that define the project's properties. - Some attributes have values that are strings; - others have values that are string lists. - - There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays} - (see @ref{Associative Array Attributes}). - - The names of the attributes are restricted; there is a list of project - attributes, and a list of package attributes for each package. - The names are not case sensitive. - - The project attributes are as follows (all are simple attributes): - - @multitable @columnfractions .4 .3 - @item @emph{Attribute Name} - @tab @emph{Value} - @item @code{Source_Files} - @tab string list - @item @code{Source_Dirs} - @tab string list - @item @code{Source_List_File} - @tab string - @item @code{Object_Dir} - @tab string - @item @code{Exec_Dir} - @tab string - @item @code{Main} - @tab string list - @item @code{Languages} - @tab string list - @item @code{Library_Dir} - @tab string - @item @code{Library_Name} - @tab string - @item @code{Library_Kind} - @tab string - @item @code{Library_Elaboration} - @tab string - @item @code{Library_Version} - @tab string - @end multitable - - @noindent - The attributes for package @code{Naming} are as follows - (see @ref{Naming Schemes}): - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Specification_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Implementation_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Separate_Suffix} - @tab simple attribute - @tab n/a - @tab string - @item @code{Casing} - @tab simple attribute - @tab n/a - @tab string - @item @code{Dot_Replacement} - @tab simple attribute - @tab n/a - @tab string - @item @code{Specification} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Implementation} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Specification_Exceptions} - @tab associative array - @tab language name - @tab string list - @item @code{Implementation_Exceptions} - @tab associative array - @tab language name - @tab string list - @end multitable - - @noindent - The attributes for package @code{Builder}, @code{Compiler}, @code{Binder}, - @code{Linker}, @code{Cross_Reference}, and @code{Finder} - are as follows (see @ref{Switches and Project Files}). - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Default_Switches} - @tab associative array - @tab language name - @tab string list - @item @code{Switches} - @tab associative array - @tab file name - @tab string list - @end multitable - - @noindent - In addition, package @code{Builder} has a single string attribute - @code{Local_Configuration_Pragmas} and package @code{Builder} has a single - string attribute @code{Global_Configuration_Pragmas}. - - @noindent - The attribute for package @code{Glide} are not documented: they are for - internal use only. - - @noindent - Each simple attribute has a default value: the empty string (for string-valued - attributes) and the empty list (for string list-valued attributes). - - Similar to variable declarations, an attribute declaration defines a new value - for an attribute. - - Examples of simple attribute declarations: - - @smallexample - for Object_Dir use "objects"; - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - @noindent - A @dfn{simple attribute declaration} starts with the reserved word @code{for}, - followed by the name of the attribute, followed by the reserved word - @code{use}, followed by an expression (whose kind depends on the attribute), - followed by a semicolon. - - Attributes may be referenced in expressions. - The general form for such a reference is @code{'}: - the entity for which the attribute is defined, - followed by an apostrophe, followed by the name of the attribute. - For associative array attributes, a litteral string between parentheses - need to be supplied as index. - - Examples are: - - @smallexample - project'Object_Dir - Naming'Dot_Replacement - Imported_Project'Source_Dirs - Imported_Project.Naming'Casing - Builder'Default_Switches("Ada") - @end smallexample - - @noindent - The entity may be: - @itemize @bullet - @item @code{project} for an attribute of the current project - @item The name of an existing package of the current project - @item The name of an imported project - @item The name of a parent project (extended by the current project) - @item An imported/parent project name, followed by a dot, - followed by a package name - @end itemize - - @noindent - Example: - @smallexample - @group - project Prj is - for Source_Dirs use project'Source_Dirs & "units"; - for Source_Dirs use project'Source_Dirs & "test/drivers" - end Prj; - @end group - @end smallexample - - @noindent - In the first attribute declaration, initially the attribute @code{Source_Dirs} - has the default value: an empty string list. After this declaration, - @code{Source_Dirs} is a string list of one element: "units". - After the second attribute declaration @code{Source_Dirs} is a string list of - two elements: "units" and "test/drivers". - - Note: this example is for illustration only. In practice, - the project file would contain only one attribute declaration: - - @smallexample - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - - @node Associative Array Attributes - @subsection Associative Array Attributes - - @noindent - Some attributes are defined as @emph{associative arrays}. An associative - array may be regarded as a function that takes a string as a parameter - and delivers a string or string list value as its result. - - Here are some examples of associative array attribute declarations: - - @smallexample - for Implementation ("main") use "Main.ada"; - for Switches ("main.ada") use ("-v", "-gnatv"); - for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g"; - @end smallexample - - @noindent - Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the - attribute, replacing the previous setting. - - - @node case Constructions - @subsection @code{case} Constructions - - @noindent - A @code{case} construction is used in a project file to effect conditional - behavior. - Here is a typical example: - - @smallexample - @group - project MyProj is - type OS_Type is ("Linux", "Unix", "NT", "VMS"); - - OS : OS_Type := external ("OS", "Linux"); - @end group - - @group - package Compiler is - case OS is - when "Linux" | "Unix" => - for Default_Switches ("Ada") use ("-gnath"); - when "NT" => - for Default_Switches ("Ada") use ("-gnatP"); - when others => - end case; - end Compiler; - end MyProj; - @end group - @end smallexample - - @noindent - The syntax of a @code{case} construction is based on the Ada case statement - (although there is no @code{null} construction for empty alternatives). - - Following the reserved word @code{case} there is the case variable (a typed - string variable), the reserved word @code{is}, and then a sequence of one or - more alternatives. - Each alternative comprises the reserved word @code{when}, either a list of - literal strings separated by the @code{"|"} character or the reserved word - @code{others}, and the @code{"=>"} token. - Each literal string must belong to the string type that is the type of the - case variable. - An @code{others} alternative, if present, must occur last. - The @code{end case;} sequence terminates the case construction. - - After each @code{=>}, there are zero or more constructions. The only - constructions allowed in a case construction are other case constructions and - attribute declarations. String type declarations, variable declarations and - package declarations are not allowed. - - The value of the case variable is often given by an external reference - (see @ref{External References in Project Files}). - - - @c **************************************** - @c * Objects and Sources in Project Files * - @c **************************************** - - @node Objects and Sources in Project Files - @section Objects and Sources in Project Files - - @menu - * Object Directory:: - * Exec Directory:: - * Source Directories:: - * Source File Names:: - @end menu - - @noindent - Each project has exactly one object directory and one or more source - directories. The source directories must contain at least one source file, - unless the project file explicitly specifies that no source files are present - (see @ref{Source File Names}). - - - @node Object Directory - @subsection Object Directory - - @noindent - The object directory for a project is the directory containing the compiler's - output (such as @file{ALI} files and object files) for the project's immediate - sources. Note that for inherited sources (when extending a parent project) the - parent project's object directory is used. - - The object directory is given by the value of the attribute @code{Object_Dir} - in the project file. - - @smallexample - for Object_Dir use "objects"; - @end smallexample - - @noindent - The attribute @var{Object_Dir} has a string value, the path name of the object - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be readable and writable. - - By default, when the attribute @code{Object_Dir} is not given an explicit value - or when its value is the empty string, the object directory is the same as the - directory containing the project file. - - - @node Exec Directory - @subsection Exec Directory - - @noindent - The exec directory for a project is the directory containing the executables - for the project's main subprograms. - - The exec directory is given by the value of the attribute @code{Exec_Dir} - in the project file. - - @smallexample - for Exec_Dir use "executables"; - @end smallexample - - @noindent - The attribute @var{Exec_Dir} has a string value, the path name of the exec - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be writable. - - By default, when the attribute @code{Exec_Dir} is not given an explicit value - or when its value is the empty string, the exec directory is the same as the - object directory of the project file. - - - @node Source Directories - @subsection Source Directories - - @noindent - The source directories of a project are specified by the project file - attribute @code{Source_Dirs}. - - This attribute's value is a string list. If the attribute is not given an - explicit value, then there is only one source directory, the one where the - project file resides. - - A @code{Source_Dirs} attribute that is explicitly defined to be the empty list, - as in - - @smallexample - for Source_Dirs use (); - @end smallexample - - @noindent - indicates that the project contains no source files. - - Otherwise, each string in the string list designates one or more - source directories. - - @smallexample - for Source_Dirs use ("sources", "test/drivers"); - @end smallexample - - @noindent - If a string in the list ends with @code{"/**"}, then the directory whose path - name precedes the two asterisks, as well as all its subdirectories - (recursively), are source directories. - - @smallexample - for Source_Dirs use ("/system/sources/**"); - @end smallexample - - @noindent - Here the directory @code{/system/sources} and all of its subdirectories - (recursively) are source directories. - - To specify that the source directories are the directory of the project file - and all of its subdirectories, you can declare @code{Source_Dirs} as follows: - @smallexample - for Source_Dirs use ("./**"); - @end smallexample - - @noindent - Each of the source directories must exist and be readable. - - - @node Source File Names - @subsection Source File Names - - @noindent - In a project that contains source files, their names may be specified by the - attributes @code{Source_Files} (a string list) or @code{Source_List_File} - (a string). Source file names never include any directory information. - - If the attribute @code{Source_Files} is given an explicit value, then each - element of the list is a source file name. - - @smallexample - for Source_Files use ("main.adb"); - for Source_Files use ("main.adb", "pack1.ads", "pack2.adb"); - @end smallexample - - @noindent - If the attribute @code{Source_Files} is not given an explicit value, - but the attribute @code{Source_List_File} is given a string value, - then the source file names are contained in the text file whose path name - (absolute or relative to the directory of the project file) is the - value of the attribute @code{Source_List_File}. - - Each line in the file that is not empty or is not a comment - contains a source file name. A comment line starts with two hyphens. - - @smallexample - for Source_List_File use "source_list.txt"; - @end smallexample - - @noindent - By default, if neither the attribute @code{Source_Files} nor the attribute - @code{Source_List_File} is given an explicit value, then each file in the - source directories that conforms to the project's naming scheme - (see @ref{Naming Schemes}) is an immediate source of the project. - - A warning is issued if both attributes @code{Source_Files} and - @code{Source_List_File} are given explicit values. In this case, the attribute - @code{Source_Files} prevails. - - Each source file name must be the name of one and only one existing source file - in one of the source directories. - - A @code{Source_Files} attribute defined with an empty list as its value - indicates that there are no source files in the project. - - Except for projects that are clearly specified as containing no Ada source - files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list, - or @code{Languages} specified without @code{"Ada"} in the list) - @smallexample - for Source_Dirs use (); - for Source_Files use (); - for Languages use ("C", "C++"); - @end smallexample - - @noindent - a project must contain at least one immediate source. - - Projects with no source files are useful as template packages - (see @ref{Packages in Project Files}) for other projects; in particular to - define a package @code{Naming} (see @ref{Naming Schemes}). - - - @c **************************** - @c * Importing Projects * - @c **************************** - - @node Importing Projects - @section Importing Projects - - @noindent - An immediate source of a project P may depend on source files that - are neither immediate sources of P nor in the predefined library. - To get this effect, P must @emph{import} the projects that contain the needed - source files. - - @smallexample - @group - with "project1", "utilities.gpr"; - with "/namings/apex.gpr"; - project Main is - ... - @end group - @end smallexample - - @noindent - As can be seen in this example, the syntax for importing projects is similar - to the syntax for importing compilation units in Ada. However, project files - use literal strings instead of names, and the @code{with} clause identifies - project files rather than packages. - - Each literal string is the file name or path name (absolute or relative) of a - project file. If a string is simply a file name, with no path, then its - location is determined by the @emph{project path}: - - @itemize @bullet - @item - If the environment variable @env{ADA_PROJECT_PATH} exists, then the project - path includes all the directories in this environment variable, plus the - directory of the project file. - - @item - If the environment variable @env{ADA_PROJECT_PATH} does not exist, - then the project path contains only one directory, namely the one where - the project file is located. - @end itemize - - @noindent - If a relative pathname is used as in - - @smallexample - with "tests/proj"; - @end smallexample - - @noindent - then the path is relative to the directory where the importing project file is - located. Any symbolic link will be fully resolved in the directory - of the importing project file before the imported project file is looked up. - - When the @code{with}'ed project file name does not have an extension, - the default is @file{.gpr}. If a file with this extension is not found, then - the file name as specified in the @code{with} clause (no extension) will be - used. In the above example, if a file @code{project1.gpr} is found, then it - will be used; otherwise, if a file @code{project1} exists then it will be used; - if neither file exists, this is an error. - - A warning is issued if the name of the project file does not match the - name of the project; this check is case insensitive. - - Any source file that is an immediate source of the imported project can be - used by the immediate sources of the importing project, and recursively. Thus - if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate - sources of @code{A} may depend on the immediate sources of @code{C}, even if - @code{A} does not import @code{C} explicitly. However, this is not recommended, - because if and when @code{B} ceases to import @code{C}, some sources in - @code{A} will no longer compile. - - A side effect of this capability is that cyclic dependences are not permitted: - if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not - allowed to import @code{A}. - - - @c ********************* - @c * Project Extension * - @c ********************* - - @node Project Extension - @section Project Extension - - @noindent - During development of a large system, it is sometimes necessary to use - modified versions of some of the source files without changing the original - sources. This can be achieved through a facility known as - @emph{project extension}. - - @smallexample - project Modified_Utilities extends "/baseline/utilities.gpr" is ... - @end smallexample - - @noindent - The project file for the project being extended (the @emph{parent}) is - identified by the literal string that follows the reserved word @code{extends}, - which itself follows the name of the extending project (the @emph{child}). - - By default, a child project inherits all the sources of its parent. - However, inherited sources can be overridden: a unit with the same name as one - in the parent will hide the original unit. - Inherited sources are considered to be sources (but not immediate sources) - of the child project; see @ref{Project File Syntax}. - - An inherited source file retains any switches specified in the parent project. - - For example if the project @code{Utilities} contains the specification and the - body of an Ada package @code{Util_IO}, then the project - @code{Modified_Utilities} can contain a new body for package @code{Util_IO}. - The original body of @code{Util_IO} will not be considered in program builds. - However, the package specification will still be found in the project - @code{Utilities}. - - A child project can have only one parent but it may import any number of other - projects. - - A project is not allowed to import directly or indirectly at the same time a - child project and any of its ancestors. - - - @c **************************************** - @c * External References in Project Files * - @c **************************************** - - @node External References in Project Files - @section External References in Project Files - - @noindent - A project file may contain references to external variables; such references - are called @emph{external references}. - - An external variable is either defined as part of the environment (an - environment variable in Unix, for example) or else specified on the command - line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the - command line value is used. - - An external reference is denoted by the built-in function - @code{external}, which returns a string value. This function has two forms: - @itemize @bullet - @item @code{external (external_variable_name)} - @item @code{external (external_variable_name, default_value)} - @end itemize - - @noindent - Each parameter must be a string literal. For example: - - @smallexample - external ("USER") - external ("OS", "Linux") - @end smallexample - - @noindent - In the form with one parameter, the function returns the value of - the external variable given as parameter. If this name is not present in the - environment, then the returned value is an empty string. - - In the form with two string parameters, the second parameter is - the value returned when the variable given as the first parameter is not - present in the environment. In the example above, if @code{"OS"} is not - the name of an environment variable and is not passed on the command line, - then the returned value will be @code{"Linux"}. - - An external reference may be part of a string expression or of a string - list expression, to define variables or attributes. - - @smallexample - @group - type Mode_Type is ("Debug", "Release"); - Mode : Mode_Type := external ("MODE"); - case Mode is - when "Debug" => - ... - @end group - @end smallexample - - - @c ***************************** - @c * Packages in Project Files * - @c ***************************** - - @node Packages in Project Files - @section Packages in Project Files - - @noindent - The @emph{package} is the project file feature that defines the settings for - project-aware tools. - For each such tool you can declare a corresponding package; the names for these - packages are preset (see @ref{Packages}) but are not case sensitive. - A package may contain variable declarations, attribute declarations, and case - constructions. - - @smallexample - @group - project Proj is - package Builder is -- used by gnatmake - for Default_Switches ("Ada") use ("-v", "-g"); - end Builder; - end Proj; - @end group - @end smallexample - - @noindent - A package declaration starts with the reserved word @code{package}, - followed by the package name (case insensitive), followed by the reserved word - @code{is}. It ends with the reserved word @code{end}, followed by the package - name, finally followed by a semi-colon. - - Most of the packages have an attribute @code{Default_Switches}. - This attribute is an associative array, and its value is a string list. - The index of the associative array is the name of a programming language (case - insensitive). This attribute indicates the switch or switches to be used - with the corresponding tool. - - Some packages also have another attribute, @code{Switches}, an associative - array whose value is a string list. The index is the name of a source file. - This attribute indicates the switch or switches to be used by the corresponding - tool when dealing with this specific file. - - Further information on these switch-related attributes is found in - @ref{Switches and Project Files}. - - A package may be declared as a @emph{renaming} of another package; e.g., from - the project file for an imported project. - - @smallexample - @group - with "/global/apex.gpr"; - project Example is - package Naming renames Apex.Naming; - ... - end Example; - @end group - @end smallexample - - @noindent - Packages that are renamed in other project files often come from project files - that have no sources: they are just used as templates. Any modification in the - template will be reflected automatically in all the project files that rename - a package from the template. - - In addition to the tool-oriented packages, you can also declare a package - named @code{Naming} to establish specialized source file naming conventions - (see @ref{Naming Schemes}). - - - @c ************************************ - @c * Variables from Imported Projects * - @c ************************************ - - @node Variables from Imported Projects - @section Variables from Imported Projects - - @noindent - An attribute or variable defined in an imported or parent project can - be used in expressions in the importing / extending project. - Such an attribute or variable is prefixed with the name of the project - and (if relevant) the name of package where it is defined. - - @smallexample - @group - with "imported"; - project Main extends "base" is - Var1 := Imported.Var; - Var2 := Base.Var & ".new"; - @end group - - @group - package Builder is - for Default_Switches ("Ada") use Imported.Builder.Ada_Switches & - "-gnatg" & "-v"; - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") use Base.Compiler.Ada_Switches; - end Compiler; - end Main; - @end group - @end smallexample - - @noindent - In this example: - - @itemize @bullet - @item - @code{Var1} is a copy of the variable @code{Var} defined in the project file - @file{"imported.gpr"} - @item - the value of @code{Var2} is a copy of the value of variable @code{Var} - defined in the project file @file{base.gpr}, concatenated with @code{".new"} - @item - attribute @code{Default_Switches ("Ada")} in package @code{Builder} - is a string list that includes in its value a copy of variable - @code{Ada_Switches} defined in the @code{Builder} package in project file - @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"}; - @item - attribute @code{Default_Switches ("Ada")} in package @code{Compiler} - is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler} - package in project file @file{base.gpr}, the project being extended. - @end itemize - - - @c ****************** - @c * Naming Schemes * - @c ****************** - - @node Naming Schemes - @section Naming Schemes - - @noindent - Sometimes an Ada software system is ported from a foreign compilation - environment to GNAT, with file names that do not use the default GNAT - conventions. Instead of changing all the file names (which for a variety of - reasons might not be possible), you can define the relevant file naming scheme - in the @code{Naming} package in your project file. For example, the following - package models the Apex file naming rules: - - @smallexample - @group - package Naming is - for Casing use "lowercase"; - for Dot_Replacement use "."; - for Specification_Suffix ("Ada") use ".1.ada"; - for Implementation_Suffix ("Ada") use ".2.ada"; - end Naming; - @end group - @end smallexample - - @noindent - You can define the following attributes in package @code{Naming}: - - @table @code - - @item @var{Casing} - This must be a string with one of the three values @code{"lowercase"}, - @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive. - - @noindent - If @var{Casing} is not specified, then the default is @code{"lowercase"}. - - @item @var{Dot_Replacement} - This must be a string whose value satisfies the following conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start or end with an alphanumeric character - @item It cannot be a single underscore - @item It cannot start with an underscore followed by an alphanumeric - @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."} - @end itemize - - @noindent - If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. - - @item @var{Specification_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @end itemize - @noindent - If @code{Specification_Suffix ("Ada")} is not specified, then the default is - @code{".ads"}. - - @item @var{Implementation_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @item It cannot be a suffix of @code{Specification_Suffix} - @end itemize - @noindent - If @code{Implementation_Suffix ("Ada")} is not specified, then the default is - @code{".adb"}. - - @item @var{Separate_Suffix} - This must be a string whose value satisfies the same conditions as - @code{Implementation_Suffix}. - - @noindent - If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same - value as @code{Implementation_Suffix ("Ada")}. - - @item @var{Specification} - @noindent - You can use the @code{Specification} attribute, an associative array, to define - the source file name for an individual Ada compilation unit's spec. The array - index must be a string literal that identifies the Ada unit (case insensitive). - The value of this attribute must be a string that identifies the file that - contains this unit's spec (case sensitive or insensitive depending on the - operating system). - - @smallexample - for Specification ("MyPack.MyChild") use "mypack.mychild.spec"; - @end smallexample - - @item @var{Implementation} - - You can use the @code{Implementation} attribute, an associative array, to - define the source file name for an individual Ada compilation unit's body - (possibly a subunit). The array index must be a string literal that identifies - the Ada unit (case insensitive). The value of this attribute must be a string - that identifies the file that contains this unit's body or subunit (case - sensitive or insensitive depending on the operating system). - - @smallexample - for Implementation ("MyPack.MyChild") use "mypack.mychild.body"; - @end smallexample - @end table - - - @c ******************** - @c * Library Projects * - @c ******************** - - @node Library Projects - @section Library Projects - - @noindent - @emph{Library projects} are projects whose object code is placed in a library. - (Note that this facility is not yet supported on all platforms) - - To create a library project, you need to define in its project file - two project-level attributes: @code{Library_Name} and @code{Library_Dir}. - Additionally, you may define the library-related attributes - @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}. - - The @code{Library_Name} attribute has a string value that must start with a - letter and include only letters and digits. - - The @code{Library_Dir} attribute has a string value that designates the path - (absolute or relative) of the directory where the library will reside. - It must designate an existing directory, and this directory needs to be - different from the project's object directory. It also needs to be writable. - - If both @code{Library_Name} and @code{Library_Dir} are specified and - are legal, then the project file defines a library project. The optional - library-related attributes are checked only for such project files. - - The @code{Library_Kind} attribute has a string value that must be one of the - following (case insensitive): @code{"static"}, @code{"dynamic"} or - @code{"relocatable"}. If this attribute is not specified, the library is a - static library. Otherwise, the library may be dynamic or relocatable. - Depending on the operating system, there may or may not be a distinction - between dynamic and relocatable libraries. For example, on Unix there is no - such distinction. - - The @code{Library_Version} attribute has a string value whose interpretation - is platform dependent. On Unix, it is used only for dynamic/relocatable - libraries as the internal name of the library (the @code{"soname"}). If the - library file name (built from the @code{Library_Name}) is different from the - @code{Library_Version}, then the library file will be a symbolic link to the - actual file whose name will be @code{Library_Version}. - - Example (on Unix): - - @smallexample - @group - project Plib is - - Version := "1"; - - for Library_Dir use "lib_dir"; - for Library_Name use "dummy"; - for Library_Kind use "relocatable"; - for Library_Version use "libdummy.so." & Version; - - end Plib; - @end group - @end smallexample - - @noindent - Directory @file{lib_dir} will contain the internal library file whose name - will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to - @file{libdummy.so.1}. - - When @command{gnatmake} detects that a project file (not the main project file) - is a library project file, it will check all immediate sources of the project - and rebuild the library if any of the sources have been recompiled. - All @file{ALI} files will also be copied from the object directory to the - library directory. To build executables, @command{gnatmake} will use the - library rather than the individual object files. - - - @c ************************************* - @c * Switches Related to Project Files * - @c ************************************* - @node Switches Related to Project Files - @section Switches Related to Project Files - - @noindent - The following switches are used by GNAT tools that support project files: - - @table @code - - @item @option{-P@var{project}} - Indicates the name of a project file. This project file will be parsed with - the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external - references indicated by @option{-X} switches, if any. - - @noindent - There must be only one @option{-P} switch on the command line. - - @noindent - Since the Project Manager parses the project file only after all the switches - on the command line are checked, the order of the switches @option{-P}, - @option{-Vp@emph{x}} or @option{-X} is not significant. - - @item @option{-X@var{name=value}} - Indicates that external variable @var{name} has the value @var{value}. - The Project Manager will use this value for occurrences of - @code{external(name)} when parsing the project file. - - @noindent - If @var{name} or @var{value} includes a space, then @var{name=value} should be - put between quotes. - @smallexample - -XOS=NT - -X"user=John Doe" - @end smallexample - - @noindent - Several @option{-X} switches can be used simultaneously. - If several @option{-X} switches specify the same @var{name}, only the last one - is used. - - @noindent - An external variable specified with a @option{-X} switch takes precedence - over the value of the same name in the environment. - - @item @option{-vP@emph{x}} - Indicates the verbosity of the parsing of GNAT project files. - @option{-vP0} means Default (no output for syntactically correct project - files); - @option{-vP1} means Medium; - @option{-vP2} means High. - @noindent - The default is Default. - @noindent - If several @option{-vP@emph{x}} switches are present, only the last one is - used. - - @end table - - - @c ********************************** - @c * Tools Supporting Project Files * - @c ********************************** - - @node Tools Supporting Project Files - @section Tools Supporting Project Files - - @menu - * gnatmake and Project Files:: - * The GNAT Driver and Project Files:: - * Glide and Project Files:: - @end menu - - @node gnatmake and Project Files - @subsection gnatmake and Project Files - - @noindent - This section covers two topics related to @command{gnatmake} and project files: - defining switches for @command{gnatmake} and for the tools that it invokes; - and the use of the @code{Main} attribute. - - @menu - * Switches and Project Files:: - * Project Files and Main Subprograms:: - @end menu - - @node Switches and Project Files - @subsubsection Switches and Project Files - - @noindent - For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and - @code{Linker}, you can specify a @code{Default_Switches} attribute, a - @code{Switches} attribute, or both; as their names imply, these switch-related - attributes affect which switches are used for which files when - @command{gnatmake} is invoked. As will be explained below, these - package-contributed switches precede the switches passed on the - @command{gnatmake} command line. - - The @code{Default_Switches} attribute is an associative array indexed by - language name (case insensitive) and returning a string list. For example: - - @smallexample - @group - package Compiler is - for Default_Switches ("Ada") use ("-gnaty", "-v"); - end Compiler; - @end group - @end smallexample - - @noindent - The @code{Switches} attribute is also an associative array, indexed by a file - name (which may or may not be case sensitive, depending on the operating - system) and returning a string list. For example: - - @smallexample - @group - package Builder is - for Switches ("main1.adb") use ("-O2"); - for Switches ("main2.adb") use ("-g"); - end Builder; - @end group - @end smallexample - - @noindent - For the @code{Builder} package, the file names should designate source files - for main subprograms. For the @code{Binder} and @code{Linker} packages, the - file names should designate @file{ALI} or source files for main subprograms. - In each case just the file name (without explicit extension) is acceptable. - - For each tool used in a program build (@command{gnatmake}, the compiler, the - binder, and the linker), its corresponding package @dfn{contributes} a set of - switches for each file on which the tool is invoked, based on the - switch-related attributes defined in the package. In particular, the switches - that each of these packages contributes for a given file @var{f} comprise: - - @itemize @bullet - @item - the value of attribute @code{Switches (@var{f})}, if it is specified in the - package for the given file, - @item - otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in - the package. - @end itemize - - @noindent - If neither of these attributes is defined in the package, then the package does - not contribute any switches for the given file. - - When @command{gnatmake} is invoked on a file, the switches comprise two sets, - in the following order: those contributed for the file by the @code{Builder} - package; and the switches passed on the command line. - - When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file, - the switches passed to the tool comprise three sets, in the following order: - - @enumerate - @item - the applicable switches contributed for the file by the @code{Builder} package - in the project file supplied on the command line; - - @item - those contributed for the file by the package (in the relevant project file -- - see below) corresponding to the tool; and - - @item - the applicable switches passed on the command line. - @end enumerate - - @noindent - The term @emph{applicable switches} reflects the fact that @command{gnatmake} - switches may or may not be passed to individual tools, depending on the - individual switch. - - @command{gnatmake} may invoke the compiler on source files from different - projects. The Project Manager will use the appropriate project file to - determine the @code{Compiler} package for each source file being compiled. - Likewise for the @code{Binder} and @code{Linker} packages. - - As an example, consider the following package in a project file: - - @smallexample - @group - project Proj1 is - package Compiler is - for Default_Switches ("Ada") use ("-g"); - for Switches ("a.adb") use ("-O1"); - for Switches ("b.adb") use ("-O2", "-gnaty"); - end Compiler; - end Proj1; - @end group - @end smallexample - - @noindent - If @command{gnatmake} is invoked with this project file, and it needs to - compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then - @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb} - with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with - @option{-g}. - - Another example illustrates the ordering of the switches contributed by - different packages: - - @smallexample - @group - project Proj2 is - package Builder is - for Switches ("main.adb") use ("-g", "-O1", "-f"); - end Builder; - @end group - - @group - package Compiler is - for Switches ("main.adb") use ("-O2"); - end Compiler; - end Proj2; - @end group - @end smallexample - - @noindent - If you issue the command: - - @smallexample - gnatmake -PProj2 -O0 main - @end smallexample - - @noindent - then the compiler will be invoked on @file{main.adb} with the following sequence of switches - - @smallexample - -g -O1 -O2 -O0 - @end smallexample - - with the last @option{-O} switch having precedence over the earlier ones; - several other switches (such as @option{-c}) are added implicitly. - - The switches @option{-g} and @option{-O1} are contributed by package - @code{Builder}, @option{-O2} is contributed by the package @code{Compiler} - and @option{-O0} comes from the command line. - - The @option{-g} switch will also be passed in the invocation of - @command{gnatlink.} - - A final example illustrates switch contributions from packages in different - project files: - - @smallexample - @group - project Proj3 is - for Source_Files use ("pack.ads", "pack.adb"); - package Compiler is - for Default_Switches ("Ada") use ("-gnata"); - end Compiler; - end Proj3; - @end group - - @group - with "Proj3"; - project Proj4 is - for Source_Files use ("foo_main.adb", "bar_main.adb"); - package Builder is - for Switches ("foo_main.adb") use ("-s", "-g"); - end Builder; - end Proj4; - @end group - - @group - -- Ada source file: - with Pack; - procedure Foo_Main is - ... - end Foo_Main; - @end group - @end smallexample - - If the command is - @smallexample - gnatmake -PProj4 foo_main.adb -cargs -gnato - @end smallexample - - @noindent - then the switches passed to the compiler for @file{foo_main.adb} are - @option{-g} (contributed by the package @code{Proj4.Builder}) and - @option{-gnato} (passed on the command line). - When the imported package @code{Pack} is compiled, the switches used are - @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from - package @code{Proj3.Compiler}, and @option{-gnato} from the command line. - - - @node Project Files and Main Subprograms - @subsubsection Project Files and Main Subprograms - - @noindent - When using a project file, you can invoke @command{gnatmake} - with several main subprograms, by specifying their source files on the command - line. Each of these needs to be an immediate source file of the project. - - @smallexample - gnatmake -Pprj main1 main2 main3 - @end smallexample - - @noindent - When using a project file, you can also invoke @command{gnatmake} without - explicitly specifying any main, and the effect depends on whether you have - defined the @code{Main} attribute. This attribute has a string list value, - where each element in the list is the name of a source file (the file - extension is optional) containing a main subprogram. - - If the @code{Main} attribute is defined in a project file as a non-empty - string list and the switch @option{-u} is not used on the command line, then - invoking @command{gnatmake} with this project file but without any main on the - command line is equivalent to invoking @command{gnatmake} with all the file - names in the @code{Main} attribute on the command line. - - Example: - @smallexample - @group - project Prj is - for Main use ("main1", "main2", "main3"); - end Prj; - @end group - @end smallexample - - @noindent - With this project file, @code{"gnatmake -Pprj"} is equivalent to - @code{"gnatmake -Pprj main1 main2 main3"}. - - When the project attribute @code{Main} is not specified, or is specified - as an empty string list, or when the switch @option{-u} is used on the command - line, then invoking @command{gnatmake} with no main on the command line will - result in all immediate sources of the project file being checked, and - potentially recompiled. Depending on the presence of the switch @option{-u}, - sources from other project files on which the immediate sources of the main - project file depend are also checked and potentially recompiled. In other - words, the @option{-u} switch is applied to all of the immediate sources of themain project file. - - - @node The GNAT Driver and Project Files - @subsection The GNAT Driver and Project Files - - @noindent - A number of GNAT tools, other than @command{gnatmake} are project-aware: - @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls} - and @command{gnatxref}. However, none of these tools can be invoked directly - with a project file switch (@code{-P}). They need to be invoke through the - @command{gnat} driver. - - The @command{gnat} driver is a front-end that accepts a number of commands and - call the corresponding tool. It has been designed initially for VMS to convert - VMS style qualifiers to Unix style switches, but it is now available to all - the GNAT supported platforms. - - On non VMS platforms, the @command{gnat} driver accepts the following commands - (case insensitive): - - @itemize @bullet - @item - BIND to invoke @command{gnatbind} - @item - CHOP to invoke @command{gnatchop} - @item - COMP or COMPILE to invoke the compiler - @item - ELIM to invoke @command{gnatelim} - @item - FIND to invoke @command{gnatfind} - @item - KR or KRUNCH to invoke @command{gnatkr} - @item - LINK to invoke @command{gnatlink} - @item - LS or LIST to invoke @command{gnatls} - @item - MAKE to invoke @command{gnatmake} - @item - NAME to invoke @command{gnatname} - @item - PREP or PREPROCESS to invoke @command{gnatprep} - @item - PSTA or STANDARD to invoke @command{gnatpsta} - @item - STUB to invoke @command{gnatstub} - @item - XREF to invoke @command{gnatxref} - @end itemize - - @noindent - Note that the compiler is invoked using the command @command{gnatmake -f -u}. - - @noindent - Following the command, you may put switches and arguments for the invoked - tool. - - @smallexample - gnat bind -C main.ali - gnat ls -a main - gnat chop foo.txt - @end smallexample - - @noindent - In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project - file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in - addition to the switches of the invoking tool. - - @noindent - For each of these command, there is possibly a package in the main project that - corresponds to the invoked tool. - - @itemize @bullet - @item - package @code{Binder} for command BIND (invoking @code{gnatbind}) - - @item - package @code{Finder} for command FIND (invoking @code{gnatfind}) - - @item - package @code{Gnatls} for command LS or LIST (invoking @code{gnatls}) - - @item - package @code{Linker} for command LINK (invoking @code{gnatlink}) - - @item - package @code{Cross_Reference} for command XREF (invoking @code{gnatlink}) - - @end itemize - - @noindent - Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable - with a string list value. It contains switches for the invocation of - @code{gnatls}. - - @smallexample - @group - project Proj1 is - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - end Proj1; - @end group - @end smallexample - - @noindent - All other packages contains a switch @code{Default_Switches}, an associative - array, indexed by the programming language (case insensitive) and having a - string list value. @code{Default_Switches ("Ada")} contains the switches for - the invocation of the tool corresponding to the package. - - @smallexample - @group - project Proj is - - for Source_Dirs use ("./**"); - - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - @end group - @group - - package Binder is - for Default_Switches ("Ada") use ("-C", "-e"); - end Binder; - @end group - @group - - package Linker is - for Default_Switches ("Ada") use ("-C"); - end Linker; - @end group - @group - - package Finder is - for Default_Switches ("Ada") use ("-a", "-f"); - end Finder; - @end group - @group - - package Cross_Reference is - for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u"); - end Cross_Reference; - end Proj; - @end group - @end smallexample - - @noindent - With the above project file, commands such as - - @smallexample - gnat ls -Pproj main - gnat xref -Pproj main - gnat bind -Pproj main.ali - @end smallexample - - @noindent - will set up the environment properly and invoke the tool with the switches - found in the package corresponding to the tool. - - - @node Glide and Project Files - @subsection Glide and Project Files - - @noindent - Glide will automatically recognize the @file{.gpr} extension for - project files, and will - convert them to its own internal format automatically. However, it - doesn't provide a syntax-oriented editor for modifying these - files. - The project file will be loaded as text when you select the menu item - @code{Ada} @result{} @code{Project} @result{} @code{Edit}. - You can edit this text and save the @file{gpr} file; - when you next select this project file in Glide it - will be automatically reloaded. - - Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value - is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the - cross-prefix. From this information the correct location for the - GNAT runtime, and thus also the correct cross-references, can be - determined. - - - @node An Extended Example - @section An Extended Example - - @noindent - Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources - in the respective directories. We would like to build them with a single - @command{gnatmake} command, and we would like to place their object files into - @file{.build} subdirectories of the source directories. Furthermore, we would - like to have to have two separate subdirectories in @file{.build} -- - @file{release} and @file{debug} -- which will contain the object files compiled with - different set of compilation flags. - - In other words, we have the following structure: - - @smallexample - @group - main - |- prog1 - | |- .build - | | debug - | | release - |- prog2 - |- .build - | debug - | release - @end group - @end smallexample - - @noindent - Here are the project files that we need to create in a directory @file{main} - to maintain this structure: - - @enumerate - - @item We create a @code{Common} project with a package @code{Compiler} that - specifies the compilation switches: - - @smallexample - File "common.gpr": - @group - @b{project} Common @b{is} - - @b{for} Source_Dirs @b{use} (); -- No source files - @end group - - @group - @b{type} Build_Type @b{is} ("release", "debug"); - Build : Build_Type := External ("BUILD", "debug"); - @end group - @group - @b{package} Compiler @b{is} - @b{case} Build @b{is} - @b{when} "release" => - @b{for} Default_Switches ("Ada") @b{use} ("-O2"); - @b{when} "debug" => - @b{for} Default_Switches ("Ada") @b{use} ("-g"); - @b{end case}; - @b{end} Compiler; - - @b{end} Common; - @end group - @end smallexample - - @item We create separate projects for the two programs: - - @smallexample - @group - File "prog1.gpr": - - @b{with} "common"; - @b{project} Prog1 @b{is} - - @b{for} Source_Dirs @b{use} ("prog1"); - @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Prog1; - @end group - @end smallexample - - @smallexample - @group - File "prog2.gpr": - - @b{with} "common"; - @b{project} Prog2 @b{is} - - @b{for} Source_Dirs @b{use} ("prog2"); - @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @end group - @b{end} Prog2; - @end smallexample - - @item We create a wrapping project @var{Main}: - - @smallexample - @group - File "main.gpr": - - @b{with} "common"; - @b{with} "prog1"; - @b{with} "prog2"; - @b{project} Main @b{is} - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Main; - @end group - @end smallexample - - @item Finally we need to create a dummy procedure that @code{with}s (either - explicitly or implicitly) all the sources of our two programs. - - @end enumerate - - @noindent - Now we can build the programs using the command - - @smallexample - gnatmake -Pmain dummy - @end smallexample - - @noindent - for the Debug mode, or - - @smallexample - gnatmake -Pmain -XBUILD=release - @end smallexample - - @noindent - for the Release mode. - - - @c ******************************** - @c * Project File Complete Syntax * - @c ******************************** - - @node Project File Complete Syntax - @section Project File Complete Syntax - - @smallexample - project ::= - context_clause project_declaration - - context_clause ::= - @{with_clause@} - - with_clause ::= - @b{with} literal_string @{ , literal_string @} ; - - project_declaration ::= - @b{project} simple_name [ @b{extends} literal_string ] @b{is} - @{declarative_item@} - @b{end} simple_name; - - declarative_item ::= - package_declaration | - typed_string_declaration | - other_declarative_item - - package_declaration ::= - @b{package} simple_name package_completion - - package_completion ::= - package_body | package_renaming - - package body ::= - @b{is} - @{other_declarative_item@} - @b{end} simple_name ; - - package_renaming ::== - @b{renames} simple_name.simple_name ; - - typed_string_declaration ::= - @b{type} _simple_name @b{is} - ( literal_string @{, literal_string@} ); - - other_declarative_item ::= - attribute_declaration | - typed_variable_declaration | - variable_declaration | - case_construction - - attribute_declaration ::= - @b{for} attribute @b{use} expression ; - - attribute ::= - simple_name | - simple_name ( literal_string ) - - typed_variable_declaration ::= - simple_name : name := string_expression ; - - variable_declaration ::= - simple_name := expression; - - expression ::= - term @{& term@} - - term ::= - literal_string | - string_list | - name | - external_value | - attribute_reference - - literal_string ::= - (same as Ada) - - string_list ::= - ( expression @{ , expression @} ) - - external_value ::= - @b{external} ( literal_string [, literal_string] ) - - attribute_reference ::= - attribute_parent ' simple_name [ ( literal_string ) ] - - attribute_parent ::= - @b{project} | - simple_name | - simple_name . simple_name - - case_construction ::= - @b{case} name @b{is} - @{case_item@} - @b{end case} ; - - case_item ::= - @b{when} discrete_choice_list => @{case_construction | attribute_declaration@} - - discrete_choice_list ::= - literal_string @{| literal_string@} - - name ::= - simple_name @{. simple_name@} - - simple_name ::= - identifier (same as Ada) - - @end smallexample - - - @node Elaboration Order Handling in GNAT - @chapter Elaboration Order Handling in GNAT - @cindex Order of elaboration - @cindex Elaboration control - - @menu - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - @end menu - - @noindent - This chapter describes the handling of elaboration code in Ada 95 and - in GNAT, and discusses how the order of elaboration of program units can - be controlled in GNAT, either automatically or with explicit programming - features. - - @node Elaboration Code in Ada 95 - @section Elaboration Code in Ada 95 - - @noindent - Ada 95 provides rather general mechanisms for executing code at elaboration - time, that is to say before the main program starts executing. Such code arises - in three contexts: - - @table @asis - @item Initializers for variables. - Variables declared at the library level, in package specs or bodies, can - require initialization that is performed at elaboration time, as in: - @smallexample - @cartouche - Sqrt_Half : Float := Sqrt (0.5); - @end cartouche - @end smallexample - - @item Package initialization code - Code in a @code{BEGIN-END} section at the outer level of a package body is - executed as part of the package body elaboration code. - - @item Library level task allocators - Tasks that are declared using task allocators at the library level - start executing immediately and hence can execute at elaboration time. - @end table - - @noindent - Subprogram calls are possible in any of these contexts, which means that - any arbitrary part of the program may be executed as part of the elaboration - code. It is even possible to write a program which does all its work at - elaboration time, with a null main program, although stylistically this - would usually be considered an inappropriate way to structure - a program. - - An important concern arises in the context of elaboration code: - we have to be sure that it is executed in an appropriate order. What we - have is a series of elaboration code sections, potentially one section - for each unit in the program. It is important that these execute - in the correct order. Correctness here means that, taking the above - example of the declaration of @code{Sqrt_Half}, - if some other piece of - elaboration code references @code{Sqrt_Half}, - then it must run after the - section of elaboration code that contains the declaration of - @code{Sqrt_Half}. - - There would never be any order of elaboration problem if we made a rule - that whenever you @code{with} a unit, you must elaborate both the spec and body - of that unit before elaborating the unit doing the @code{with}'ing: - - @smallexample - @group - @cartouche - @b{with} Unit_1; - @b{package} Unit_2 @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - would require that both the body and spec of @code{Unit_1} be elaborated - before the spec of @code{Unit_2}. However, a rule like that would be far too - restrictive. In particular, it would make it impossible to have routines - in separate packages that were mutually recursive. - - You might think that a clever enough compiler could look at the actual - elaboration code and determine an appropriate correct order of elaboration, - but in the general case, this is not possible. Consider the following - example. - - In the body of @code{Unit_1}, we have a procedure @code{Func_1} - that references - the variable @code{Sqrt_1}, which is declared in the elaboration code - of the body of @code{Unit_1}: - - @smallexample - @cartouche - Sqrt_1 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_1} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_1 = 1 @b{then} - Q := Unit_2.Func_2; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - @code{Unit_2} is exactly parallel, - it has a procedure @code{Func_2} that references - the variable @code{Sqrt_2}, which is declared in the elaboration code of - the body @code{Unit_2}: - - @smallexample - @cartouche - Sqrt_2 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_2} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_2 = 2 @b{then} - Q := Unit_1.Func_1; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the question is, which of the following orders of elaboration is - acceptable: - - @smallexample - @group - Spec of Unit_1 - Spec of Unit_2 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - or - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_2 - Body of Unit_1 - @end group - @end smallexample - - @noindent - If you carefully analyze the flow here, you will see that you cannot tell - at compile time the answer to this question. - If @code{expression_1} is not equal to 1, - and @code{expression_2} is not equal to 2, - then either order is acceptable, because neither of the function calls is - executed. If both tests evaluate to true, then neither order is acceptable - and in fact there is no correct order. - - If one of the two expressions is true, and the other is false, then one - of the above orders is correct, and the other is incorrect. For example, - if @code{expression_1} = 1 and @code{expression_2} /= 2, - then the call to @code{Func_2} - will occur, but not the call to @code{Func_1.} - This means that it is essential - to elaborate the body of @code{Unit_1} before - the body of @code{Unit_2}, so the first - order of elaboration is correct and the second is wrong. - - By making @code{expression_1} and @code{expression_2} - depend on input data, or perhaps - the time of day, we can make it impossible for the compiler or binder - to figure out which of these expressions will be true, and hence it - is impossible to guarantee a safe order of elaboration at run time. - - @node Checking the Elaboration Order in Ada 95 - @section Checking the Elaboration Order in Ada 95 - - @noindent - In some languages that involve the same kind of elaboration problems, - e.g. Java and C++, the programmer is expected to worry about these - ordering problems himself, and it is common to - write a program in which an incorrect elaboration order gives - surprising results, because it references variables before they - are initialized. - Ada 95 is designed to be a safe language, and a programmer-beware approach is - clearly not sufficient. Consequently, the language provides three lines - of defense: - - @table @asis - @item Standard rules - Some standard rules restrict the possible choice of elaboration - order. In particular, if you @code{with} a unit, then its spec is always - elaborated before the unit doing the @code{with}. Similarly, a parent - spec is always elaborated before the child spec, and finally - a spec is always elaborated before its corresponding body. - - @item Dynamic elaboration checks - @cindex Elaboration checks - @cindex Checks, elaboration - Dynamic checks are made at run time, so that if some entity is accessed - before it is elaborated (typically by means of a subprogram call) - then the exception (@code{Program_Error}) is raised. - - @item Elaboration control - Facilities are provided for the programmer to specify the desired order - of elaboration. - @end table - - Let's look at these facilities in more detail. First, the rules for - dynamic checking. One possible rule would be simply to say that the - exception is raised if you access a variable which has not yet been - elaborated. The trouble with this approach is that it could require - expensive checks on every variable reference. Instead Ada 95 has two - rules which are a little more restrictive, but easier to check, and - easier to state: - - @table @asis - @item Restrictions on calls - A subprogram can only be called at elaboration time if its body - has been elaborated. The rules for elaboration given above guarantee - that the spec of the subprogram has been elaborated before the - call, but not the body. If this rule is violated, then the - exception @code{Program_Error} is raised. - - @item Restrictions on instantiations - A generic unit can only be instantiated if the body of the generic - unit has been elaborated. Again, the rules for elaboration given above - guarantee that the spec of the generic unit has been elaborated - before the instantiation, but not the body. If this rule is - violated, then the exception @code{Program_Error} is raised. - @end table - - @noindent - The idea is that if the body has been elaborated, then any variables - it references must have been elaborated; by checking for the body being - elaborated we guarantee that none of its references causes any - trouble. As we noted above, this is a little too restrictive, because a - subprogram that has no non-local references in its body may in fact be safe - to call. However, it really would be unsafe to rely on this, because - it would mean that the caller was aware of details of the implementation - in the body. This goes against the basic tenets of Ada. - - A plausible implementation can be described as follows. - A Boolean variable is associated with each subprogram - and each generic unit. This variable is initialized to False, and is set to - True at the point body is elaborated. Every call or instantiation checks the - variable, and raises @code{Program_Error} if the variable is False. - - Note that one might think that it would be good enough to have one Boolean - variable for each package, but that would not deal with cases of trying - to call a body in the same package as the call - that has not been elaborated yet. - Of course a compiler may be able to do enough analysis to optimize away - some of the Boolean variables as unnecessary, and @code{GNAT} indeed - does such optimizations, but still the easiest conceptual model is to - think of there being one variable per subprogram. - - @node Controlling the Elaboration Order in Ada 95 - @section Controlling the Elaboration Order in Ada 95 - - @noindent - In the previous section we discussed the rules in Ada 95 which ensure - that @code{Program_Error} is raised if an incorrect elaboration order is - chosen. This prevents erroneous executions, but we need mechanisms to - specify a correct execution and avoid the exception altogether. - To achieve this, Ada 95 provides a number of features for controlling - the order of elaboration. We discuss these features in this section. - - First, there are several ways of indicating to the compiler that a given - unit has no elaboration problems: - - @table @asis - @item packages that do not require a body - In Ada 95, a library package that does not require a body does not permit - a body. This means that if we have a such a package, as in: - - @smallexample - @group - @cartouche - @b{package} Definitions @b{is} - @b{generic} - @b{type} m @b{is new} integer; - @b{package} Subp @b{is} - @b{type} a @b{is array} (1 .. 10) @b{of} m; - @b{type} b @b{is array} (1 .. 20) @b{of} m; - @b{end} Subp; - @b{end} Definitions; - @end cartouche - @end group - @end smallexample - - @noindent - A package that @code{with}'s @code{Definitions} may safely instantiate - @code{Definitions.Subp} because the compiler can determine that there - definitely is no package body to worry about in this case - - @item pragma Pure - @cindex pragma Pure - @findex Pure - Places sufficient restrictions on a unit to guarantee that - no call to any subprogram in the unit can result in an - elaboration problem. This means that the compiler does not need - to worry about the point of elaboration of such units, and in - particular, does not need to check any calls to any subprograms - in this unit. - - @item pragma Preelaborate - @findex Preelaborate - @cindex pragma Preelaborate - This pragma places slightly less stringent restrictions on a unit than - does pragma Pure, - but these restrictions are still sufficient to ensure that there - are no elaboration problems with any calls to the unit. - - @item pragma Elaborate_Body - @findex Elaborate_Body - @cindex pragma Elaborate_Body - This pragma requires that the body of a unit be elaborated immediately - after its spec. Suppose a unit @code{A} has such a pragma, - and unit @code{B} does - a @code{with} of unit @code{A}. Recall that the standard rules require - the spec of unit @code{A} - to be elaborated before the @code{with}'ing unit; given the pragma in - @code{A}, we also know that the body of @code{A} - will be elaborated before @code{B}, so - that calls to @code{A} are safe and do not need a check. - @end table - - @noindent - Note that, - unlike pragma @code{Pure} and pragma @code{Preelaborate}, - the use of - @code{Elaborate_Body} does not guarantee that the program is - free of elaboration problems, because it may not be possible - to satisfy the requested elaboration order. - Let's go back to the example with @code{Unit_1} and @code{Unit_2}. - If a programmer - marks @code{Unit_1} as @code{Elaborate_Body}, - and not @code{Unit_2,} then the order of - elaboration will be: - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - Now that means that the call to @code{Func_1} in @code{Unit_2} - need not be checked, - it must be safe. But the call to @code{Func_2} in - @code{Unit_1} may still fail if - @code{Expression_1} is equal to 1, - and the programmer must still take - responsibility for this not being the case. - - If all units carry a pragma @code{Elaborate_Body}, then all problems are - eliminated, except for calls entirely within a body, which are - in any case fully under programmer control. However, using the pragma - everywhere is not always possible. - In particular, for our @code{Unit_1}/@code{Unit_2} example, if - we marked both of them as having pragma @code{Elaborate_Body}, then - clearly there would be no possible elaboration order. - - The above pragmas allow a server to guarantee safe use by clients, and - clearly this is the preferable approach. Consequently a good rule in - Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible, - and if this is not possible, - mark them as @code{Elaborate_Body} if possible. - As we have seen, there are situations where neither of these - three pragmas can be used. - So we also provide methods for clients to control the - order of elaboration of the servers on which they depend: - - @table @asis - @item pragma Elaborate (unit) - @findex Elaborate - @cindex pragma Elaborate - This pragma is placed in the context clause, after a @code{with} clause, - and it requires that the body of the named unit be elaborated before - the unit in which the pragma occurs. The idea is to use this pragma - if the current unit calls at elaboration time, directly or indirectly, - some subprogram in the named unit. - - @item pragma Elaborate_All (unit) - @findex Elaborate_All - @cindex pragma Elaborate_All - This is a stronger version of the Elaborate pragma. Consider the - following example: - - @smallexample - Unit A @code{with}'s unit B and calls B.Func in elab code - Unit B @code{with}'s unit C, and B.Func calls C.Func - @end smallexample - - @noindent - Now if we put a pragma @code{Elaborate (B)} - in unit @code{A}, this ensures that the - body of @code{B} is elaborated before the call, but not the - body of @code{C}, so - the call to @code{C.Func} could still cause @code{Program_Error} to - be raised. - - The effect of a pragma @code{Elaborate_All} is stronger, it requires - not only that the body of the named unit be elaborated before the - unit doing the @code{with}, but also the bodies of all units that the - named unit uses, following @code{with} links transitively. For example, - if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, - then it requires - not only that the body of @code{B} be elaborated before @code{A}, - but also the - body of @code{C}, because @code{B} @code{with}'s @code{C}. - @end table - - @noindent - We are now in a position to give a usage rule in Ada 95 for avoiding - elaboration problems, at least if dynamic dispatching and access to - subprogram values are not used. We will handle these cases separately - later. - - The rule is simple. If a unit has elaboration code that can directly or - indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate - a generic unit in a @code{with}'ed unit, - then if the @code{with}'ed unit does not have - pragma @code{Pure} or @code{Preelaborate}, then the client should have - a pragma @code{Elaborate_All} - for the @code{with}'ed unit. By following this rule a client is - assured that calls can be made without risk of an exception. - If this rule is not followed, then a program may be in one of four - states: - - @table @asis - @item No order exists - No order of elaboration exists which follows the rules, taking into - account any @code{Elaborate}, @code{Elaborate_All}, - or @code{Elaborate_Body} pragmas. In - this case, an Ada 95 compiler must diagnose the situation at bind - time, and refuse to build an executable program. - - @item One or more orders exist, all incorrect - One or more acceptable elaboration orders exists, and all of them - generate an elaboration order problem. In this case, the binder - can build an executable program, but @code{Program_Error} will be raised - when the program is run. - - @item Several orders exist, some right, some incorrect - One or more acceptable elaboration orders exists, and some of them - work, and some do not. The programmer has not controlled - the order of elaboration, so the binder may or may not pick one of - the correct orders, and the program may or may not raise an - exception when it is run. This is the worst case, because it means - that the program may fail when moved to another compiler, or even - another version of the same compiler. - - @item One or more orders exists, all correct - One ore more acceptable elaboration orders exist, and all of them - work. In this case the program runs successfully. This state of - affairs can be guaranteed by following the rule we gave above, but - may be true even if the rule is not followed. - @end table - - @noindent - Note that one additional advantage of following our Elaborate_All rule - is that the program continues to stay in the ideal (all orders OK) state - even if maintenance - changes some bodies of some subprograms. Conversely, if a program that does - not follow this rule happens to be safe at some point, this state of affairs - may deteriorate silently as a result of maintenance changes. - - You may have noticed that the above discussion did not mention - the use of @code{Elaborate_Body}. This was a deliberate omission. If you - @code{with} an @code{Elaborate_Body} unit, it still may be the case that - code in the body makes calls to some other unit, so it is still necessary - to use @code{Elaborate_All} on such units. - - @node Controlling Elaboration in GNAT - Internal Calls - @section Controlling Elaboration in GNAT - Internal Calls - - @noindent - In the case of internal calls, i.e. calls within a single package, the - programmer has full control over the order of elaboration, and it is up - to the programmer to elaborate declarations in an appropriate order. For - example writing: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - Q : Float := One; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - @end cartouche - @end group - @end smallexample - - @noindent - will obviously raise @code{Program_Error} at run time, because function - One will be called before its body is elaborated. In this case GNAT will - generate a warning that the call will raise @code{Program_Error}: - - @smallexample - @group - @cartouche - 1. procedure y is - 2. function One return Float; - 3. - 4. Q : Float := One; - | - >>> warning: cannot call "One" before body is elaborated - >>> warning: Program_Error will be raised at run time - - 5. - 6. function One return Float is - 7. begin - 8. return 1.0; - 9. end One; - 10. - 11. begin - 12. null; - 13. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that in this particular case, it is likely that the call is safe, because - the function @code{One} does not access any global variables. - Nevertheless in Ada 95, we do not want the validity of the check to depend on - the contents of the body (think about the separate compilation case), so this - is still wrong, as we discussed in the previous sections. - - The error is easily corrected by rearranging the declarations so that the - body of One appears before the declaration containing the call - (note that in Ada 95, - declarations can appear in any order, so there is no restriction that - would prevent this reordering, and if we write: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - - Q : Float := One; - @end cartouche - @end group - @end smallexample - - @noindent - then all is well, no warning is generated, and no - @code{Program_Error} exception - will be raised. - Things are more complicated when a chain of subprograms is executed: - - @smallexample - @group - @cartouche - @b{function} A @b{return} Integer; - @b{function} B @b{return} Integer; - @b{function} C @b{return} Integer; - - @b{function} B @b{return} Integer @b{is begin return} A; @b{end}; - @b{function} C @b{return} Integer @b{is begin return} B; @b{end}; - - X : Integer := C; - - @b{function} A @b{return} Integer @b{is begin return} 1; @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the call to @code{C} - at elaboration time in the declaration of @code{X} is correct, because - the body of @code{C} is already elaborated, - and the call to @code{B} within the body of - @code{C} is correct, but the call - to @code{A} within the body of @code{B} is incorrect, because the body - of @code{A} has not been elaborated, so @code{Program_Error} - will be raised on the call to @code{A}. - In this case GNAT will generate a - warning that @code{Program_Error} may be - raised at the point of the call. Let's look at the warning: - - @smallexample - @group - @cartouche - 1. procedure x is - 2. function A return Integer; - 3. function B return Integer; - 4. function C return Integer; - 5. - 6. function B return Integer is begin return A; end; - | - >>> warning: call to "A" before body is elaborated may - raise Program_Error - >>> warning: "B" called at line 7 - >>> warning: "C" called at line 9 - - 7. function C return Integer is begin return B; end; - 8. - 9. X : Integer := C; - 10. - 11. function A return Integer is begin return 1; end; - 12. - 13. begin - 14. null; - 15. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that the message here says "may raise", instead of the direct case, - where the message says "will be raised". That's because whether - @code{A} is - actually called depends in general on run-time flow of control. - For example, if the body of @code{B} said - - @smallexample - @group - @cartouche - @b{function} B @b{return} Integer @b{is} - @b{begin} - @b{if} some-condition-depending-on-input-data @b{then} - @b{return} A; - @b{else} - @b{return} 1; - @b{end if}; - @b{end} B; - @end cartouche - @end group - @end smallexample - - @noindent - then we could not know until run time whether the incorrect call to A would - actually occur, so @code{Program_Error} might - or might not be raised. It is possible for a compiler to - do a better job of analyzing bodies, to - determine whether or not @code{Program_Error} - might be raised, but it certainly - couldn't do a perfect job (that would require solving the halting problem - and is provably impossible), and because this is a warning anyway, it does - not seem worth the effort to do the analysis. Cases in which it - would be relevant are rare. - - In practice, warnings of either of the forms given - above will usually correspond to - real errors, and should be examined carefully and eliminated. - In the rare case where a warning is bogus, it can be suppressed by any of - the following methods: - - @itemize @bullet - @item - Compile with the @option{-gnatws} switch set - - @item - Suppress @code{Elaboration_Checks} for the called subprogram - - @item - Use pragma @code{Warnings_Off} to turn warnings off for the call - @end itemize - - @noindent - For the internal elaboration check case, - GNAT by default generates the - necessary run-time checks to ensure - that @code{Program_Error} is raised if any - call fails an elaboration check. Of course this can only happen if a - warning has been issued as described above. The use of pragma - @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress - some of these checks, meaning that it may be possible (but is not - guaranteed) for a program to be able to call a subprogram whose body - is not yet elaborated, without raising a @code{Program_Error} exception. - - @node Controlling Elaboration in GNAT - External Calls - @section Controlling Elaboration in GNAT - External Calls - - @noindent - The previous section discussed the case in which the execution of a - particular thread of elaboration code occurred entirely within a - single unit. This is the easy case to handle, because a programmer - has direct and total control over the order of elaboration, and - furthermore, checks need only be generated in cases which are rare - and which the compiler can easily detect. - The situation is more complex when separate compilation is taken into account. - Consider the following: - - @smallexample - @cartouche - @group - @b{package} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float; - @b{end} Math; - - @b{package body} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float @b{is} - @b{begin} - ... - @b{end} Sqrt; - @b{end} Math; - @end group - @group - @b{with} Math; - @b{package} Stuff @b{is} - X : Float := Math.Sqrt (0.5); - @b{end} Stuff; - - @b{with} Stuff; - @b{procedure} Main @b{is} - @b{begin} - ... - @b{end} Main; - @end group - @end cartouche - @end smallexample - - @noindent - where @code{Main} is the main program. When this program is executed, the - elaboration code must first be executed, and one of the jobs of the - binder is to determine the order in which the units of a program are - to be elaborated. In this case we have four units: the spec and body - of @code{Math}, - the spec of @code{Stuff} and the body of @code{Main}). - In what order should the four separate sections of elaboration code - be executed? - - There are some restrictions in the order of elaboration that the binder - can choose. In particular, if unit U has a @code{with} - for a package @code{X}, then you - are assured that the spec of @code{X} - is elaborated before U , but you are - not assured that the body of @code{X} - is elaborated before U. - This means that in the above case, the binder is allowed to choose the - order: - - @smallexample - spec of Math - spec of Stuff - body of Math - body of Main - @end smallexample - - @noindent - but that's not good, because now the call to @code{Math.Sqrt} - that happens during - the elaboration of the @code{Stuff} - spec happens before the body of @code{Math.Sqrt} is - elaborated, and hence causes @code{Program_Error} exception to be raised. - At first glance, one might say that the binder is misbehaving, because - obviously you want to elaborate the body of something you @code{with} - first, but - that is not a general rule that can be followed in all cases. Consider - - @smallexample - @group - @cartouche - @b{package} X @b{is} ... - - @b{package} Y @b{is} ... - - @b{with} X; - @b{package body} Y @b{is} ... - - @b{with} Y; - @b{package body} X @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - This is a common arrangement, and, apart from the order of elaboration - problems that might arise in connection with elaboration code, this works fine. - A rule that says that you must first elaborate the body of anything you - @code{with} cannot work in this case: - the body of @code{X} @code{with}'s @code{Y}, - which means you would have to - elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, - which means - you have to elaborate the body of @code{X} first, but ... and we have a - loop that cannot be broken. - - It is true that the binder can in many cases guess an order of elaboration - that is unlikely to cause a @code{Program_Error} - exception to be raised, and it tries to do so (in the - above example of @code{Math/Stuff/Spec}, the GNAT binder will - by default - elaborate the body of @code{Math} right after its spec, so all will be well). - - However, a program that blindly relies on the binder to be helpful can - get into trouble, as we discussed in the previous sections, so - GNAT - provides a number of facilities for assisting the programmer in - developing programs that are robust with respect to elaboration order. - - @node Default Behavior in GNAT - Ensuring Safety - @section Default Behavior in GNAT - Ensuring Safety - - @noindent - The default behavior in GNAT ensures elaboration safety. In its - default mode GNAT implements the - rule we previously described as the right approach. Let's restate it: - - @itemize - @item - @emph{If a unit has elaboration code that can directly or indirectly make a - call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit - in a @code{with}'ed unit, then if the @code{with}'ed unit - does not have pragma @code{Pure} or - @code{Preelaborate}, then the client should have an - @code{Elaborate_All} for the @code{with}'ed unit.} - @end itemize - - @noindent - By following this rule a client - is assured that calls and instantiations can be made without risk of an exception. - - In this mode GNAT traces all calls that are potentially made from - elaboration code, and puts in any missing implicit @code{Elaborate_All} - pragmas. - The advantage of this approach is that no elaboration problems - are possible if the binder can find an elaboration order that is - consistent with these implicit @code{Elaborate_All} pragmas. The - disadvantage of this approach is that no such order may exist. - - If the binder does not generate any diagnostics, then it means that it - has found an elaboration order that is guaranteed to be safe. However, - the binder may still be relying on implicitly generated - @code{Elaborate_All} pragmas so portability to other compilers than - GNAT is not guaranteed. - - If it is important to guarantee portability, then the compilations should - use the - @option{-gnatwl} - (warn on elaboration problems) switch. This will cause warning messages - to be generated indicating the missing @code{Elaborate_All} pragmas. - Consider the following source program: - - @smallexample - @group - @cartouche - @b{with} k; - @b{package} j @b{is} - m : integer := k.r; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - where it is clear that there - should be a pragma @code{Elaborate_All} - for unit @code{k}. An implicit pragma will be generated, and it is - likely that the binder will be able to honor it. However, - it is safer to include the pragma explicitly in the source. If this - unit is compiled with the - @option{-gnatwl} - switch, then the compiler outputs a warning: - - @smallexample - @group - @cartouche - 1. with k; - 2. package j is - 3. m : integer := k.r; - | - >>> warning: call to "r" may raise Program_Error - >>> warning: missing pragma Elaborate_All for "k" - - 4. end; - @end cartouche - @end group - @end smallexample - - @noindent - and these warnings can be used as a guide for supplying manually - the missing pragmas. - - This default mode is more restrictive than the Ada Reference - Manual, and it is possible to construct programs which will compile - using the dynamic model described there, but will run into a - circularity using the safer static model we have described. - - Of course any Ada compiler must be able to operate in a mode - consistent with the requirements of the Ada Reference Manual, - and in particular must have the capability of implementing the - standard dynamic model of elaboration with run-time checks. - - In GNAT, this standard mode can be achieved either by the use of - the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake}) - command, or by the use of the configuration pragma: - - @smallexample - pragma Elaboration_Checks (RM); - @end smallexample - - @noindent - Either approach will cause the unit affected to be compiled using the - standard dynamic run-time elaboration checks described in the Ada - Reference Manual. The static model is generally preferable, since it - is clearly safer to rely on compile and link time checks rather than - run-time checks. However, in the case of legacy code, it may be - difficult to meet the requirements of the static model. This - issue is further discussed in - @ref{What to Do If the Default Elaboration Behavior Fails}. - - Note that the static model provides a strict subset of the allowed - behavior and programs of the Ada Reference Manual, so if you do - adhere to the static model and no circularities exist, - then you are assured that your program will - work using the dynamic model. - - @node Elaboration Issues for Library Tasks - @section Elaboration Issues for Library Tasks - @cindex Library tasks, elaboration issues - @cindex Elaboration of library tasks - - @noindent - In this section we examine special elaboration issues that arise for - programs that declare library level tasks. - - Generally the model of execution of an Ada program is that all units are - elaborated, and then execution of the program starts. However, the - declaration of library tasks definitely does not fit this model. The - reason for this is that library tasks start as soon as they are declared - (more precisely, as soon as the statement part of the enclosing package - body is reached), that is to say before elaboration - of the program is complete. This means that if such a task calls a - subprogram, or an entry in another task, the callee may or may not be - elaborated yet, and in the standard - Reference Manual model of dynamic elaboration checks, you can even - get timing dependent Program_Error exceptions, since there can be - a race between the elaboration code and the task code. - - The static model of elaboration in GNAT seeks to avoid all such - dynamic behavior, by being conservative, and the conservative - approach in this particular case is to assume that all the code - in a task body is potentially executed at elaboration time if - a task is declared at the library level. - - This can definitely result in unexpected circularities. Consider - the following example - - @smallexample - package Decls is - task Lib_Task is - entry Start; - end Lib_Task; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - procedure Main is - begin - Decls.Lib_Task.Start; - end; - @end smallexample - - @noindent - If the above example is compiled in the default static elaboration - mode, then a circularity occurs. The circularity comes from the call - @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since - this call occurs in elaboration code, we need an implicit pragma - @code{Elaborate_All} for @code{Utils}. This means that not only must - the spec and body of @code{Utils} be elaborated before the body - of @code{Decls}, but also the spec and body of any unit that is - @code{with'ed} by the body of @code{Utils} must also be elaborated before - the body of @code{Decls}. This is the transitive implication of - pragma @code{Elaborate_All} and it makes sense, because in general - the body of @code{Put_Val} might have a call to something in a - @code{with'ed} unit. - - In this case, the body of Utils (actually its spec) @code{with's} - @code{Decls}. Unfortunately this means that the body of @code{Decls} - must be elaborated before itself, in case there is a call from the - body of @code{Utils}. - - Here is the exact chain of events we are worrying about: - - @enumerate - @item - In the body of @code{Decls} a call is made from within the body of a library - task to a subprogram in the package @code{Utils}. Since this call may - occur at elaboration time (given that the task is activated at elaboration - time), we have to assume the worst, i.e. that the - call does happen at elaboration time. - - @item - This means that the body and spec of @code{Util} must be elaborated before - the body of @code{Decls} so that this call does not cause an access before - elaboration. - - @item - Within the body of @code{Util}, specifically within the body of - @code{Util.Put_Val} there may be calls to any unit @code{with}'ed - by this package. - - @item - One such @code{with}'ed package is package @code{Decls}, so there - might be a call to a subprogram in @code{Decls} in @code{Put_Val}. - In fact there is such a call in this example, but we would have to - assume that there was such a call even if it were not there, since - we are not supposed to write the body of @code{Decls} knowing what - is in the body of @code{Utils}; certainly in the case of the - static elaboration model, the compiler does not know what is in - other bodies and must assume the worst. - - @item - This means that the spec and body of @code{Decls} must also be - elaborated before we elaborate the unit containing the call, but - that unit is @code{Decls}! This means that the body of @code{Decls} - must be elaborated before itself, and that's a circularity. - @end enumerate - - @noindent - Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in - the body of @code{Decls} you will get a true Ada Reference Manual - circularity that makes the program illegal. - - In practice, we have found that problems with the static model of - elaboration in existing code often arise from library tasks, so - we must address this particular situation. - - Note that if we compile and run the program above, using the dynamic model of - elaboration (that is to say use the @option{-gnatE} switch), - then it compiles, binds, - links, and runs, printing the expected result of 2. Therefore in some sense - the circularity here is only apparent, and we need to capture - the properties of this program that distinguish it from other library-level - tasks that have real elaboration problems. - - We have four possible answers to this question: - - @itemize @bullet - - @item - Use the dynamic model of elaboration. - - If we use the @option{-gnatE} switch, then as noted above, the program works. - Why is this? If we examine the task body, it is apparent that the task cannot - proceed past the - @code{accept} statement until after elaboration has been completed, because - the corresponding entry call comes from the main program, not earlier. - This is why the dynamic model works here. But that's really giving - up on a precise analysis, and we prefer to take this approach only if we cannot - solve the - problem in any other manner. So let us examine two ways to reorganize - the program to avoid the potential elaboration problem. - - @item - Split library tasks into separate packages. - - Write separate packages, so that library tasks are isolated from - other declarations as much as possible. Let us look at a variation on - the above program. - - @smallexample - package Decls1 is - task Lib_Task is - entry Start; - end Lib_Task; - end Decls1; - - with Utils; - package body Decls1 is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - end Decls1; - - package Decls2 is - type My_Int is new Integer; - function Ident (M : My_Int) return My_Int; - end Decls2; - - with Utils; - package body Decls2 is - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls2; - - with Decls2; - package Utils is - procedure Put_Val (Arg : Decls2.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls2.My_Int) is - begin - Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls1; - procedure Main is - begin - Decls1.Lib_Task.Start; - end; - @end smallexample - - @noindent - All we have done is to split @code{Decls} into two packages, one - containing the library task, and one containing everything else. Now - there is no cycle, and the program compiles, binds, links and executes - using the default static model of elaboration. - - @item - Declare separate task types. - - A significant part of the problem arises because of the use of the - single task declaration form. This means that the elaboration of - the task type, and the elaboration of the task itself (i.e. the - creation of the task) happen at the same time. A good rule - of style in Ada 95 is to always create explicit task types. By - following the additional step of placing task objects in separate - packages from the task type declaration, many elaboration problems - are avoided. Here is another modified example of the example program: - - @smallexample - package Decls is - task type Lib_Task_Type is - entry Start; - end Lib_Task_Type; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task_Type is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task_Type; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - package Declst is - Lib_Task : Decls.Lib_Task_Type; - end Declst; - - with Declst; - procedure Main is - begin - Declst.Lib_Task.Start; - end; - @end smallexample - - @noindent - What we have done here is to replace the @code{task} declaration in - package @code{Decls} with a @code{task type} declaration. Then we - introduce a separate package @code{Declst} to contain the actual - task object. This separates the elaboration issues for - the @code{task type} - declaration, which causes no trouble, from the elaboration issues - of the task object, which is also unproblematic, since it is now independent - of the elaboration of @code{Utils}. - This separation of concerns also corresponds to - a generally sound engineering principle of separating declarations - from instances. This version of the program also compiles, binds, links, - and executes, generating the expected output. - - @item - Use No_Entry_Calls_In_Elaboration_Code restriction. - @cindex No_Entry_Calls_In_Elaboration_Code - - The previous two approaches described how a program can be restructured - to avoid the special problems caused by library task bodies. in practice, - however, such restructuring may be difficult to apply to existing legacy code, - so we must consider solutions that do not require massive rewriting. - - Let us consider more carefully why our original sample program works - under the dynamic model of elaboration. The reason is that the code - in the task body blocks immediately on the @code{accept} - statement. Now of course there is nothing to prohibit elaboration - code from making entry calls (for example from another library level task), - so we cannot tell in isolation that - the task will not execute the accept statement during elaboration. - - However, in practice it is very unusual to see elaboration code - make any entry calls, and the pattern of tasks starting - at elaboration time and then immediately blocking on @code{accept} or - @code{select} statements is very common. What this means is that - the compiler is being too pessimistic when it analyzes the - whole package body as though it might be executed at elaboration - time. - - If we know that the elaboration code contains no entry calls, (a very safe - assumption most of the time, that could almost be made the default - behavior), then we can compile all units of the program under control - of the following configuration pragma: - - @smallexample - pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); - @end smallexample - - @noindent - This pragma can be placed in the @file{gnat.adc} file in the usual - manner. If we take our original unmodified program and compile it - in the presence of a @file{gnat.adc} containing the above pragma, - then once again, we can compile, bind, link, and execute, obtaining - the expected result. In the presence of this pragma, the compiler does - not trace calls in a task body, that appear after the first @code{accept} - or @code{select} statement, and therefore does not report a potential - circularity in the original program. - - The compiler will check to the extent it can that the above - restriction is not violated, but it is not always possible to do a - complete check at compile time, so it is important to use this - pragma only if the stated restriction is in fact met, that is to say - no task receives an entry call before elaboration of all units is completed. - - @end itemize - - @node Mixing Elaboration Models - @section Mixing Elaboration Models - @noindent - So far, we have assumed that the entire program is either compiled - using the dynamic model or static model, ensuring consistency. It - is possible to mix the two models, but rules have to be followed - if this mixing is done to ensure that elaboration checks are not - omitted. - - The basic rule is that @emph{a unit compiled with the static model cannot - be @code{with'ed} by a unit compiled with the dynamic model}. The - reason for this is that in the static model, a unit assumes that - its clients guarantee to use (the equivalent of) pragma - @code{Elaborate_All} so that no elaboration checks are required - in inner subprograms, and this assumption is violated if the - client is compiled with dynamic checks. - - The precise rule is as follows. A unit that is compiled with dynamic - checks can only @code{with} a unit that meets at least one of the - following criteria: - - @itemize @bullet - - @item - The @code{with'ed} unit is itself compiled with dynamic elaboration - checks (that is with the @option{-gnatE} switch. - - @item - The @code{with'ed} unit is an internal GNAT implementation unit from - the System, Interfaces, Ada, or GNAT hierarchies. - - @item - The @code{with'ed} unit has pragma Preelaborate or pragma Pure. - - @item - The @code{with'ing} unit (that is the client) has an explicit pragma - @code{Elaborate_All} for the @code{with'ed} unit. - - @end itemize - - @noindent - If this rule is violated, that is if a unit with dynamic elaboration - checks @code{with's} a unit that does not meet one of the above four - criteria, then the binder (@code{gnatbind}) will issue a warning - similar to that in the following example: - - @smallexample - warning: "x.ads" has dynamic elaboration checks and with's - warning: "y.ads" which has static elaboration checks - @end smallexample - - @noindent - These warnings indicate that the rule has been violated, and that as a result - elaboration checks may be missed in the resulting executable file. - This warning may be suppressed using the @code{-ws} binder switch - in the usual manner. - - One useful application of this mixing rule is in the case of a subsystem - which does not itself @code{with} units from the remainder of the - application. In this case, the entire subsystem can be compiled with - dynamic checks to resolve a circularity in the subsystem, while - allowing the main application that uses this subsystem to be compiled - using the more reliable default static model. - - @node What to Do If the Default Elaboration Behavior Fails - @section What to Do If the Default Elaboration Behavior Fails - - @noindent - If the binder cannot find an acceptable order, it outputs detailed - diagnostics. For example: - @smallexample - @group - @iftex - @leftskip=0cm - @end iftex - error: elaboration circularity detected - info: "proc (body)" must be elaborated before "pack (body)" - info: reason: Elaborate_All probably needed in unit "pack (body)" - info: recompile "pack (body)" with -gnatwl - info: for full details - info: "proc (body)" - info: is needed by its spec: - info: "proc (spec)" - info: which is withed by: - info: "pack (body)" - info: "pack (body)" must be elaborated before "proc (body)" - info: reason: pragma Elaborate in unit "proc (body)" - @end group - - @end smallexample - - @noindent - In this case we have a cycle that the binder cannot break. On the one - hand, there is an explicit pragma Elaborate in @code{proc} for - @code{pack}. This means that the body of @code{pack} must be elaborated - before the body of @code{proc}. On the other hand, there is elaboration - code in @code{pack} that calls a subprogram in @code{proc}. This means - that for maximum safety, there should really be a pragma - Elaborate_All in @code{pack} for @code{proc} which would require that - the body of @code{proc} be elaborated before the body of - @code{pack}. Clearly both requirements cannot be satisfied. - Faced with a circularity of this kind, you have three different options. - - @table @asis - @item Fix the program - The most desirable option from the point of view of long-term maintenance - is to rearrange the program so that the elaboration problems are avoided. - One useful technique is to place the elaboration code into separate - child packages. Another is to move some of the initialization code to - explicitly called subprograms, where the program controls the order - of initialization explicitly. Although this is the most desirable option, - it may be impractical and involve too much modification, especially in - the case of complex legacy code. - - @item Perform dynamic checks - If the compilations are done using the - @option{-gnatE} - (dynamic elaboration check) switch, then GNAT behaves in - a quite different manner. Dynamic checks are generated for all calls - that could possibly result in raising an exception. With this switch, - the compiler does not generate implicit @code{Elaborate_All} pragmas. - The behavior then is exactly as specified in the Ada 95 Reference Manual. - The binder will generate an executable program that may or may not - raise @code{Program_Error}, and then it is the programmer's job to ensure - that it does not raise an exception. Note that it is important to - compile all units with the switch, it cannot be used selectively. - - @item Suppress checks - The drawback of dynamic checks is that they generate a - significant overhead at run time, both in space and time. If you - are absolutely sure that your program cannot raise any elaboration - exceptions, and you still want to use the dynamic elaboration model, - then you can use the configuration pragma - @code{Suppress (Elaboration_Checks)} to suppress all such checks. For - example this pragma could be placed in the @file{gnat.adc} file. - - @item Suppress checks selectively - When you know that certain calls in elaboration code cannot possibly - lead to an elaboration error, and the binder nevertheless generates warnings - on those calls and inserts Elaborate_All pragmas that lead to elaboration - circularities, it is possible to remove those warnings locally and obtain - a program that will bind. Clearly this can be unsafe, and it is the - responsibility of the programmer to make sure that the resulting program has - no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can - be used with different granularity to suppress warnings and break - elaboration circularities: - - @itemize @bullet - @item - Place the pragma that names the called subprogram in the declarative part - that contains the call. - - @item - Place the pragma in the declarative part, without naming an entity. This - disables warnings on all calls in the corresponding declarative region. - - @item - Place the pragma in the package spec that declares the called subprogram, - and name the subprogram. This disables warnings on all elaboration calls to - that subprogram. - - @item - Place the pragma in the package spec that declares the called subprogram, - without naming any entity. This disables warnings on all elaboration calls to - all subprograms declared in this spec. - @end itemize - - @noindent - These four cases are listed in order of decreasing safety, and therefore - require increasing programmer care in their application. Consider the - following program: - @smallexample - - package Pack1 is - function F1 return Integer; - X1 : Integer; - end Pack1; - - package Pack2 is - function F2 return Integer; - function Pure (x : integer) return integer; - -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) - -- pragma Suppress (Elaboration_Check); -- (4) - end Pack2; - - with Pack2; - package body Pack1 is - function F1 return Integer is - begin - return 100; - end F1; - Val : integer := Pack2.Pure (11); -- Elab. call (1) - begin - declare - -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) - -- pragma Suppress(Elaboration_Check); -- (2) - begin - X1 := Pack2.F2 + 1; -- Elab. call (2) - end; - end Pack1; - - with Pack1; - package body Pack2 is - function F2 return Integer is - begin - return Pack1.F1; - end F2; - function Pure (x : integer) return integer is - begin - return x ** 3 - 3 * x; - end; - end Pack2; - - with Pack1, Ada.Text_IO; - procedure Proc3 is - begin - Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 - end Proc3; - @end smallexample - In the absence of any pragmas, an attempt to bind this program produces - the following diagnostics: - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - error: elaboration circularity detected - info: "pack1 (body)" must be elaborated before "pack1 (body)" - info: reason: Elaborate_All probably needed in unit "pack1 (body)" - info: recompile "pack1 (body)" with -gnatwl for full details - info: "pack1 (body)" - info: must be elaborated along with its spec: - info: "pack1 (spec)" - info: which is withed by: - info: "pack2 (body)" - info: which must be elaborated along with its spec: - info: "pack2 (spec)" - info: which is withed by: - info: "pack1 (body)" - @end group - @end smallexample - The sources of the circularity are the two calls to @code{Pack2.Pure} and - @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to - F2 is safe, even though F2 calls F1, because the call appears after the - elaboration of the body of F1. Therefore the pragma (1) is safe, and will - remove the warning on the call. It is also possible to use pragma (2) - because there are no other potentially unsafe calls in the block. - - @noindent - The call to @code{Pure} is safe because this function does not depend on the - state of @code{Pack2}. Therefore any call to this function is safe, and it - is correct to place pragma (3) in the corresponding package spec. - - @noindent - Finally, we could place pragma (4) in the spec of @code{Pack2} to disable - warnings on all calls to functions declared therein. Note that this is not - necessarily safe, and requires more detailed examination of the subprogram - bodies involved. In particular, a call to @code{F2} requires that @code{F1} - be already elaborated. - @end table - - @noindent - It is hard to generalize on which of these four approaches should be - taken. Obviously if it is possible to fix the program so that the default - treatment works, this is preferable, but this may not always be practical. - It is certainly simple enough to use - @option{-gnatE} - but the danger in this case is that, even if the GNAT binder - finds a correct elaboration order, it may not always do so, - and certainly a binder from another Ada compiler might not. A - combination of testing and analysis (for which the warnings generated - with the - @option{-gnatwl} - switch can be useful) must be used to ensure that the program is free - of errors. One switch that is useful in this testing is the - @code{-p (pessimistic elaboration order)} - switch for - @code{gnatbind}. - Normally the binder tries to find an order that has the best chance of - of avoiding elaboration problems. With this switch, the binder - plays a devil's advocate role, and tries to choose the order that - has the best chance of failing. If your program works even with this - switch, then it has a better chance of being error free, but this is still - not a guarantee. - - For an example of this approach in action, consider the C-tests (executable - tests) from the ACVC suite. If these are compiled and run with the default - treatment, then all but one of them succeed without generating any error - diagnostics from the binder. However, there is one test that fails, and - this is not surprising, because the whole point of this test is to ensure - that the compiler can handle cases where it is impossible to determine - a correct order statically, and it checks that an exception is indeed - raised at run time. - - This one test must be compiled and run using the - @option{-gnatE} - switch, and then it passes. Alternatively, the entire suite can - be run using this switch. It is never wrong to run with the dynamic - elaboration switch if your code is correct, and we assume that the - C-tests are indeed correct (it is less efficient, but efficiency is - not a factor in running the ACVC tests.) - - @node Elaboration for Access-to-Subprogram Values - @section Elaboration for Access-to-Subprogram Values - @cindex Access-to-subprogram - - @noindent - The introduction of access-to-subprogram types in Ada 95 complicates - the handling of elaboration. The trouble is that it becomes - impossible to tell at compile time which procedure - is being called. This means that it is not possible for the binder - to analyze the elaboration requirements in this case. - - If at the point at which the access value is created - (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}), - the body of the subprogram is - known to have been elaborated, then the access value is safe, and its use - does not require a check. This may be achieved by appropriate arrangement - of the order of declarations if the subprogram is in the current unit, - or, if the subprogram is in another unit, by using pragma - @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body} - on the referenced unit. - - If the referenced body is not known to have been elaborated at the point - the access value is created, then any use of the access value must do a - dynamic check, and this dynamic check will fail and raise a - @code{Program_Error} exception if the body has not been elaborated yet. - GNAT will generate the necessary checks, and in addition, if the - @option{-gnatwl} - switch is set, will generate warnings that such checks are required. - - The use of dynamic dispatching for tagged types similarly generates - a requirement for dynamic checks, and premature calls to any primitive - operation of a tagged type before the body of the operation has been elaborated, - will result in the raising of @code{Program_Error}. - - @node Summary of Procedures for Elaboration Control - @section Summary of Procedures for Elaboration Control - @cindex Elaboration control - - @noindent - First, compile your program with the default options, using none of - the special elaboration control switches. If the binder successfully - binds your program, then you can be confident that, apart from issues - raised by the use of access-to-subprogram types and dynamic dispatching, - the program is free of elaboration errors. If it is important that the - program be portable, then use the - @option{-gnatwl} - switch to generate warnings about missing @code{Elaborate_All} - pragmas, and supply the missing pragmas. - - If the program fails to bind using the default static elaboration - handling, then you can fix the program to eliminate the binder - message, or recompile the entire program with the - @option{-gnatE} switch to generate dynamic elaboration checks, - and, if you are sure there really are no elaboration problems, - use a global pragma @code{Suppress (Elaboration_Checks)}. - - @node Other Elaboration Order Considerations - @section Other Elaboration Order Considerations - @noindent - This section has been entirely concerned with the issue of finding a valid - elaboration order, as defined by the Ada Reference Manual. In a case - where several elaboration orders are valid, the task is to find one - of the possible valid elaboration orders (and the static model in GNAT - will ensure that this is achieved). - - The purpose of the elaboration rules in the Ada Reference Manual is to - make sure that no entity is accessed before it has been elaborated. For - a subprogram, this means that the spec and body must have been elaborated - before the subprogram is called. For an object, this means that the object - must have been elaborated before its value is read or written. A violation - of either of these two requirements is an access before elaboration order, - and this section has been all about avoiding such errors. - - In the case where more than one order of elaboration is possible, in the - sense that access before elaboration errors are avoided, then any one of - the orders is "correct" in the sense that it meets the requirements of - the Ada Reference Manual, and no such error occurs. - - However, it may be the case for a given program, that there are - constraints on the order of elaboration that come not from consideration - of avoiding elaboration errors, but rather from extra-lingual logic - requirements. Consider this example: - - @smallexample - with Init_Constants; - package Constants is - X : Integer := 0; - Y : Integer := 0; - end Constants; - - package Init_Constants is - procedure Calc; - end Init_Constants; - - with Constants; - package body Init_Constants is - procedure Calc is begin null; end; - begin - Constants.X := 3; - Constants.Y := 4; - end Init_Constants; - - with Constants; - package Calc is - Z : Integer := Constants.X + Constants.Y; - end Calc; - - with Calc; - with Text_IO; use Text_IO; - procedure Main is - begin - Put_Line (Calc.Z'Img); - end Main; - @end smallexample - - @noindent - In this example, there is more than one valid order of elaboration. For - example both the following are correct orders: - - @smallexample - Init_Constants spec - Constants spec - Calc spec - Main body - Init_Constants body - - and - - Init_Constants spec - Init_Constants body - Constants spec - Calc spec - Main body - @end smallexample - - @noindent - There is no language rule to prefer one or the other, both are correct - from an order of elaboration point of view. But the programmatic effects - of the two orders are very different. In the first, the elaboration routine - of @code{Calc} initializes @code{Z} to zero, and then the main program - runs with this value of zero. But in the second order, the elaboration - routine of @code{Calc} runs after the body of Init_Constants has set - @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} - runs. - - One could perhaps by applying pretty clever non-artificial intelligence - to the situation guess that it is more likely that the second order of - elaboration is the one desired, but there is no formal linguistic reason - to prefer one over the other. In fact in this particular case, GNAT will - prefer the second order, because of the rule that bodies are elaborated - as soon as possible, but it's just luck that this is what was wanted - (if indeed the second order was preferred). - - If the program cares about the order of elaboration routines in a case like - this, it is important to specify the order required. In this particular - case, that could have been achieved by adding to the spec of Calc: - - @smallexample - pragma Elaborate_All (Constants); - @end smallexample - - @noindent - which requires that the body (if any) and spec of @code{Constants}, - as well as the body and spec of any unit @code{with}'ed by - @code{Constants} be elaborated before @code{Calc} is elaborated. - - Clearly no automatic method can always guess which alternative you require, - and if you are working with legacy code that had constraints of this kind - which were not properly specified by adding @code{Elaborate} or - @code{Elaborate_All} pragmas, then indeed it is possible that two different - compilers can choose different orders. - - The @code{gnatbind} - @code{-p} switch may be useful in smoking - out problems. This switch causes bodies to be elaborated as late as possible - instead of as early as possible. In the example above, it would have forced - the choice of the first elaboration order. If you get different results - when using this switch, and particularly if one set of results is right, - and one is wrong as far as you are concerned, it shows that you have some - missing @code{Elaborate} pragmas. For the example above, we have the - following output: - - @smallexample - gnatmake -f -q main - main - 7 - gnatmake -f -q main -bargs -p - main - 0 - @end smallexample - - @noindent - It is of course quite unlikely that both these results are correct, so - it is up to you in a case like this to investigate the source of the - difference, by looking at the two elaboration orders that are chosen, - and figuring out which is correct, and then adding the necessary - @code{Elaborate_All} pragmas to ensure the desired order. - - @node The Cross-Referencing Tools gnatxref and gnatfind - @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind} - @findex gnatxref - @findex gnatfind - - @noindent - The compiler generates cross-referencing information (unless - you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files. - This information indicates where in the source each entity is declared and - referenced. Note that entities in package Standard are not included, but - entities in all other predefined units are included in the output. - - Before using any of these two tools, you need to compile successfully your - application, so that GNAT gets a chance to generate the cross-referencing - information. - - The two tools @code{gnatxref} and @code{gnatfind} take advantage of this - information to provide the user with the capability to easily locate the - declaration and references to an entity. These tools are quite similar, - the difference being that @code{gnatfind} is intended for locating - definitions and/or references to a specified entity or entities, whereas - @code{gnatxref} is oriented to generating a full report of all - cross-references. - - To use these tools, you must not compile your application using the - @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The - GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing - information will not be generated. - - @menu - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - @end menu - - @node gnatxref Switches - @section @code{gnatxref} Switches - - @noindent - The command lines for @code{gnatxref} is: - @smallexample - $ gnatxref [switches] sourcefile1 [sourcefile2 ...] - @end smallexample - - @noindent - where - - @table @code - @item sourcefile1, sourcefile2 - identifies the source files for which a report is to be generated. The - 'with'ed units will be processed too. You must provide at least one file. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - @end table - - @noindent - The switches can be : - @table @code - @item -a - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatxref}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set @code{gnatxref} will output the parent type - reference for each matching derived types. - - @item -f - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item -g - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file to use @xref{Project Files}. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{-aI} - and @samp{-aO}. - @item -u - Output only unused symbols. This may be really useful if you give your - main compilation unit on the command line, as @code{gnatxref} will then - display every unused entity and 'with'ed package. - - @item -v - Instead of producing the default output, @code{gnatxref} will generate a - @file{tags} file that can be used by vi. For examples how to use this - feature, see @xref{Examples of gnatxref Usage}. The tags file is output - to the standard output, thus you will have to redirect it to a file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref -ag} instead of - @samp{gnatxref -a -g}. - - @node gnatfind Switches - @section @code{gnatfind} Switches - - @noindent - The command line for @code{gnatfind} is: - - @smallexample - $ gnatfind [switches] pattern[:sourcefile[:line[:column]]] - [file1 file2 ...] - @end smallexample - - @noindent - where - - @table @code - @item pattern - An entity will be output only if it matches the regular expression found - in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}. - - Omitting the pattern is equivalent to specifying @samp{*}, which - will match any entity. Note that if you do not provide a pattern, you - have to provide both a sourcefile and a line. - - Entity names are given in Latin-1, with uppercase/lowercase equivalence - for matching purposes. At the current time there is no support for - 8-bit codes other than Latin-1, or for wide characters in identifiers. - - @item sourcefile - @code{gnatfind} will look for references, bodies or declarations - of symbols referenced in @file{sourcefile}, at line @samp{line} - and column @samp{column}. See @pxref{Examples of gnatfind Usage} - for syntax examples. - - @item line - is a decimal integer identifying the line number containing - the reference to the entity (or entities) to be located. - - @item column - is a decimal integer identifying the exact location on the - line of the first character of the identifier for the - entity reference. Columns are numbered from 1. - - @item file1 file2 ... - The search will be restricted to these files. If none are given, then - the search will be done for every library file in the search path. - These file must appear only after the pattern or sourcefile. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - Not that if you specify at least one file in this part, @code{gnatfind} may - sometimes not be able to find the body of the subprograms... - - @end table - - At least one of 'sourcefile' or 'pattern' has to be present on - the command line. - - The following switches are available: - @table @code - - @item -a - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatfind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set, then @code{gnatfind} will output the parent type - reference for each matching derived types. - - @item -e - By default, @code{gnatfind} accept the simple regular expression set for - @samp{pattern}. If this switch is set, then the pattern will be - considered as full Unix-style regular expression. - - @item -f - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item -g - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file (@pxref{Project Files}) to use. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{-aI} and - @samp{-aO}. - - @item -r - By default, @code{gnatfind} will output only the information about the - declaration, body or type completion of the entities. If this switch is - set, the @code{gnatfind} will locate every reference to the entities in - the files specified on the command line (or in every file in the search - path if no file is given on the command line). - - @item -s - If this switch is set, then @code{gnatfind} will output the content - of the Ada source file lines were the entity was found. - - @item -t - If this switch is set, then @code{gnatfind} will output the type hierarchy for - the specified type. It act like -d option but recursively from parent - type to parent type. When this switch is set it is not possible to - specify more than one file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref -ag} instead of - @samp{gnatxref -a -g}. - - As stated previously, gnatfind will search in every directory in the - search path. You can force it to look only in the current directory if - you specify @code{*} at the end of the command line. - - - @node Project Files for gnatxref and gnatfind - @section Project Files for @command{gnatxref} and @command{gnatfind} - - @noindent - Project files allow a programmer to specify how to compile its - application, where to find sources,... These files are used primarily by - the Glide Ada mode, but they can also be used by the two tools - @code{gnatxref} and @code{gnatfind}. - - A project file name must end with @file{.adp}. If a single one is - present in the current directory, then @code{gnatxref} and @code{gnatfind} will - extract the information from it. If multiple project files are found, none of - them is read, and you have to use the @samp{-p} switch to specify the one - you want to use. - - The following lines can be included, even though most of them have default - values which can be used in most cases. - The lines can be entered in any order in the file. - Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of - each line. If you have multiple instances, only the last one is taken into - account. - - @table @code - @item src_dir=DIR [default: "./"] - specifies a directory where to look for source files. Multiple src_dir lines - can be specified and they will be searched in the order they - are specified. - - @item obj_dir=DIR [default: "./"] - specifies a directory where to look for object and library files. Multiple - obj_dir lines can be specified and they will be searched in the order they - are specified - - @item comp_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{comp_opt@}} notation. This is intended to store the default - switches given to @file{gnatmake} and @file{gcc}. - - @item bind_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{bind_opt@}} notation. This is intended to store the default - switches given to @file{gnatbind}. - - @item link_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{link_opt@}} notation. This is intended to store the default - switches given to @file{gnatlink}. - - @item main=EXECUTABLE [default: ""] - specifies the name of the executable for the application. This variable can - be referred to in the following lines by using the @samp{$@{main@}} notation. - - @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"] - specifies the command used to compile a single file in the application. - - @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"] - specifies the command used to recompile the whole application. - - @item run_cmd=COMMAND [default: "$@{main@}"] - specifies the command used to run the application. - - @item debug_cmd=COMMAND [default: "gdb $@{main@}"] - specifies the command used to debug the application - - @end table - - @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir} - and @samp{obj_dir} lines, and ignore the others. - - @node Regular Expressions in gnatfind and gnatxref - @section Regular Expressions in @code{gnatfind} and @code{gnatxref} - - @noindent - As specified in the section about @code{gnatfind}, the pattern can be a - regular expression. Actually, there are to set of regular expressions - which are recognized by the program : - - @table @code - @item globbing patterns - These are the most usual regular expression. They are the same that you - generally used in a Unix shell command line, or in a DOS session. - - Here is a more formal grammar : - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - regexp ::= term - term ::= elmt -- matches elmt - term ::= elmt elmt -- concatenation (elmt then elmt) - term ::= * -- any string of 0 or more characters - term ::= ? -- matches any character - term ::= [char @{char@}] -- matches any character listed - term ::= [char - char] -- matches any character in range - @end group - @end smallexample - - @item full regular expression - The second set of regular expressions is much more powerful. This is the - type of regular expressions recognized by utilities such a @file{grep}. - - The following is the form of a regular expression, expressed in Ada - reference manual style BNF is as follows - - @smallexample - @iftex - @leftskip=.5cm - @end iftex - @group - regexp ::= term @{| term@} -- alternation (term or term ...) - - term ::= item @{item@} -- concatenation (item then item) - - item ::= elmt -- match elmt - item ::= elmt * -- zero or more elmt's - item ::= elmt + -- one or more elmt's - item ::= elmt ? -- matches elmt or nothing - @end group - @group - elmt ::= nschar -- matches given character - elmt ::= [nschar @{nschar@}] -- matches any character listed - elmt ::= [^ nschar @{nschar@}] -- matches any character not listed - elmt ::= [char - char] -- matches chars in given range - elmt ::= \ char -- matches given character - elmt ::= . -- matches any single character - elmt ::= ( regexp ) -- parens used for grouping - - char ::= any character, including special characters - nschar ::= any character except ()[].*+?^ - @end group - @end smallexample - - Following are a few examples : - - @table @samp - @item abcde|fghi - will match any of the two strings 'abcde' and 'fghi'. - - @item abc*d - will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on - - @item [a-z]+ - will match any string which has only lowercase characters in it (and at - least one character - - @end table - @end table - - @node Examples of gnatxref Usage - @section Examples of @code{gnatxref} Usage - - @subsection General Usage - - @noindent - For the following examples, we will consider the following units : - - @smallexample - @group - @cartouche - main.ads: - 1: @b{with} Bar; - 2: @b{package} Main @b{is} - 3: @b{procedure} Foo (B : @b{in} Integer); - 4: C : Integer; - 5: @b{private} - 6: D : Integer; - 7: @b{end} Main; - - main.adb: - 1: @b{package body} Main @b{is} - 2: @b{procedure} Foo (B : @b{in} Integer) @b{is} - 3: @b{begin} - 4: C := B; - 5: D := B; - 6: Bar.Print (B); - 7: Bar.Print (C); - 8: @b{end} Foo; - 9: @b{end} Main; - - bar.ads: - 1: @b{package} Bar @b{is} - 2: @b{procedure} Print (B : Integer); - 3: @b{end} bar; - @end cartouche - @end group - @end smallexample - - @table @code - - @noindent - The first thing to do is to recompile your application (for instance, in - that case just by doing a @samp{gnatmake main}, so that GNAT generates - the cross-referencing information. - You can then issue any of the following commands: - - @item gnatxref main.adb - @code{gnatxref} generates cross-reference information for main.adb - and every unit 'with'ed by main.adb. - - The output would be: - @smallexample - @iftex - @leftskip=0cm - @end iftex - B Type: Integer - Decl: bar.ads 2:22 - B Type: Integer - Decl: main.ads 3:20 - Body: main.adb 2:20 - Ref: main.adb 4:13 5:13 6:19 - Bar Type: Unit - Decl: bar.ads 1:9 - Ref: main.adb 6:8 7:8 - main.ads 1:6 - C Type: Integer - Decl: main.ads 4:5 - Modi: main.adb 4:8 - Ref: main.adb 7:19 - D Type: Integer - Decl: main.ads 6:5 - Modi: main.adb 5:8 - Foo Type: Unit - Decl: main.ads 3:15 - Body: main.adb 2:15 - Main Type: Unit - Decl: main.ads 2:9 - Body: main.adb 1:14 - Print Type: Unit - Decl: bar.ads 2:15 - Ref: main.adb 6:12 7:12 - @end smallexample - - @noindent - that is the entity @code{Main} is declared in main.ads, line 2, column 9, - its body is in main.adb, line 1, column 14 and is not referenced any where. - - The entity @code{Print} is declared in bar.ads, line 2, column 15 and it - it referenced in main.adb, line 6 column 12 and line 7 column 12. - - @item gnatxref package1.adb package2.ads - @code{gnatxref} will generates cross-reference information for - package1.adb, package2.ads and any other package 'with'ed by any - of these. - - @end table - - @subsection Using gnatxref with vi - - @code{gnatxref} can generate a tags file output, which can be used - directly from @file{vi}. Note that the standard version of @file{vi} - will not work properly with overloaded symbols. Consider using another - free implementation of @file{vi}, such as @file{vim}. - - @smallexample - $ gnatxref -v gnatfind.adb > tags - @end smallexample - - @noindent - will generate the tags file for @code{gnatfind} itself (if the sources - are in the search path!). - - From @file{vi}, you can then use the command @samp{:tag @i{entity}} - (replacing @i{entity} by whatever you are looking for), and vi will - display a new file with the corresponding declaration of entity. - - @node Examples of gnatfind Usage - @section Examples of @code{gnatfind} Usage - - @table @code - - @item gnatfind -f xyz:main.adb - Find declarations for all entities xyz referenced at least once in - main.adb. The references are search in every library file in the search - path. - - The directories will be printed as well (as the @samp{-f} - switch is set) - - The output will look like: - @smallexample - directory/main.ads:106:14: xyz <= declaration - directory/main.adb:24:10: xyz <= body - directory/foo.ads:45:23: xyz <= declaration - @end smallexample - - @noindent - that is to say, one of the entities xyz found in main.adb is declared at - line 12 of main.ads (and its body is in main.adb), and another one is - declared at line 45 of foo.ads - - @item gnatfind -fs xyz:main.adb - This is the same command as the previous one, instead @code{gnatfind} will - display the content of the Ada source file lines. - - The output will look like: - - @smallexample - directory/main.ads:106:14: xyz <= declaration - procedure xyz; - directory/main.adb:24:10: xyz <= body - procedure xyz is - directory/foo.ads:45:23: xyz <= declaration - xyz : Integer; - @end smallexample - - @noindent - This can make it easier to find exactly the location your are looking - for. - - @item gnatfind -r "*x*":main.ads:123 foo.adb - Find references to all entities containing an x that are - referenced on line 123 of main.ads. - The references will be searched only in main.adb and foo.adb. - - @item gnatfind main.ads:123 - Find declarations and bodies for all entities that are referenced on - line 123 of main.ads. - - This is the same as @code{gnatfind "*":main.adb:123}. - - @item gnatfind mydir/main.adb:123:45 - Find the declaration for the entity referenced at column 45 in - line 123 of file main.adb in directory mydir. Note that it - is usual to omit the identifier name when the column is given, - since the column position identifies a unique reference. - - The column has to be the beginning of the identifier, and should not - point to any character in the middle of the identifier. - - @end table - - @node File Name Krunching Using gnatkr - @chapter File Name Krunching Using @code{gnatkr} - @findex gnatkr - - @noindent - This chapter discusses the method used by the compiler to shorten - the default file names chosen for Ada units so that they do not - exceed the maximum length permitted. It also describes the - @code{gnatkr} utility that can be used to determine the result of - applying this shortening. - @menu - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - @end menu - - @node About gnatkr - @section About @code{gnatkr} - - @noindent - The default file naming rule in GNAT - is that the file name must be derived from - the unit name. The exact default rule is as follows: - @itemize @bullet - @item - Take the unit name and replace all dots by hyphens. - @item - If such a replacement occurs in the - second character position of a name, and the first character is - a, g, s, or i then replace the dot by the character - ~ (tilde) - instead of a minus. - @end itemize - The reason for this exception is to avoid clashes - with the standard names for children of System, Ada, Interfaces, - and GNAT, which use the prefixes s- a- i- and g- - respectively. - - The @code{-gnatk@var{nn}} - switch of the compiler activates a "krunching" - circuit that limits file names to nn characters (where nn is a decimal - integer). For example, using OpenVMS, - where the maximum file name length is - 39, the value of nn is usually set to 39, but if you want to generate - a set of files that would be usable if ported to a system with some - different maximum file length, then a different value can be specified. - The default value of 39 for OpenVMS need not be specified. - - The @code{gnatkr} utility can be used to determine the krunched name for - a given file, when krunched to a specified maximum length. - - @node Using gnatkr - @section Using @code{gnatkr} - - @noindent - The @code{gnatkr} command has the form - - @smallexample - $ gnatkr @var{name} [@var{length}] - @end smallexample - - - @noindent - @var{name} can be an Ada name with dots or the GNAT name of the unit, - where the dots representing child units or subunit are replaced by - hyphens. The only confusion arises if a name ends in @code{.ads} or - @code{.adb}. @code{gnatkr} takes this to be an extension if there are - no other dots in the name and the whole name is in lowercase. - - @var{length} represents the length of the krunched name. The default - when no argument is given is 8 characters. A length of zero stands for - unlimited, in other words do not chop except for system files which are - always 8. - - @noindent - The output is the krunched name. The output has an extension only if the - original argument was a file name with an extension. - - @node Krunching Method - @section Krunching Method - - @noindent - The initial file name is determined by the name of the unit that the file - contains. The name is formed by taking the full expanded name of the - unit and replacing the separating dots with hyphens and - using lowercase - for all letters, except that a hyphen in the second character position is - replaced by a tilde if the first character is - a, i, g, or s. - The extension is @code{.ads} for a - specification and @code{.adb} for a body. - Krunching does not affect the extension, but the file name is shortened to - the specified length by following these rules: - - @itemize @bullet - @item - The name is divided into segments separated by hyphens, tildes or - underscores and all hyphens, tildes, and underscores are - eliminated. If this leaves the name short enough, we are done. - - @item - If the name is too long, the longest segment is located (left-most if there are two - of equal length), and shortened by dropping its last character. This is - repeated until the name is short enough. - - As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb} - to fit the name into 8 characters as required by some operating systems. - - @smallexample - our-strings-wide_fixed 22 - our strings wide fixed 19 - our string wide fixed 18 - our strin wide fixed 17 - our stri wide fixed 16 - our stri wide fixe 15 - our str wide fixe 14 - our str wid fixe 13 - our str wid fix 12 - ou str wid fix 11 - ou st wid fix 10 - ou st wi fix 9 - ou st wi fi 8 - Final file name: oustwifi.adb - @end smallexample - - @item - The file names for all predefined units are always krunched to eight - characters. The krunching of these predefined units uses the following - special prefix replacements: - - @table @file - @item ada- - replaced by @file{a-} - - @item gnat- - replaced by @file{g-} - - @item interfaces- - replaced by @file{i-} - - @item system- - replaced by @file{s-} - @end table - - These system files have a hyphen in the second character position. That - is why normal user files replace such a character with a - tilde, to - avoid confusion with system file names. - - As an example of this special rule, consider - @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows: - - @smallexample - ada-strings-wide_fixed 22 - a- strings wide fixed 18 - a- string wide fixed 17 - a- strin wide fixed 16 - a- stri wide fixed 15 - a- stri wide fixe 14 - a- str wide fixe 13 - a- str wid fixe 12 - a- str wid fix 11 - a- st wid fix 10 - a- st wi fix 9 - a- st wi fi 8 - Final file name: a-stwifi.adb - @end smallexample - @end itemize - - Of course no file shortening algorithm can guarantee uniqueness over all - possible unit names, and if file name krunching is used then it is your - responsibility to ensure that no name clashes occur. The utility - program @code{gnatkr} is supplied for conveniently determining the - krunched name of a file. - - @node Examples of gnatkr Usage - @section Examples of @code{gnatkr} Usage - - @smallexample - @iftex - @leftskip=0cm - @end iftex - $ gnatkr very_long_unit_name.ads --> velounna.ads - $ gnatkr grandparent-parent-child.ads --> grparchi.ads - $ gnatkr Grandparent.Parent.Child --> grparchi - $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads - $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads - @end smallexample - - @node Preprocessing Using gnatprep - @chapter Preprocessing Using @code{gnatprep} - @findex gnatprep - - @noindent - The @code{gnatprep} utility provides - a simple preprocessing capability for Ada programs. - It is designed for use with GNAT, but is not dependent on any special - features of GNAT. - - @menu - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - @end menu - - @node Using gnatprep - @section Using @code{gnatprep} - - @noindent - To call @code{gnatprep} use - - @smallexample - $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile] - @end smallexample - - @noindent - where - @table @code - @item infile - is the full name of the input file, which is an Ada source - file containing preprocessor directives. - - @item outfile - is the full name of the output file, which is an Ada source - in standard Ada form. When used with GNAT, this file name will - normally have an ads or adb suffix. - - @item deffile - is the full name of a text file containing definitions of - symbols to be referenced by the preprocessor. This argument is - optional, and can be replaced by the use of the @code{-D} switch. - - @item switches - is an optional sequence of switches as described in the next section. - @end table - - @node Switches for gnatprep - @section Switches for @code{gnatprep} - - @table @code - - @item -b - Causes both preprocessor lines and the lines deleted by - preprocessing to be replaced by blank lines in the output source file, - preserving line numbers in the output file. - - @item -c - Causes both preprocessor lines and the lines deleted - by preprocessing to be retained in the output source as comments marked - with the special string "--! ". This option will result in line numbers - being preserved in the output file. - - @item -Dsymbol=value - Defines a new symbol, associated with value. If no value is given on the - command line, then symbol is considered to be @code{True}. This switch - can be used in place of a definition file. - - - @item -r - Causes a @code{Source_Reference} pragma to be generated that - references the original input file, so that error messages will use - the file name of this original file. The use of this switch implies - that preprocessor lines are not to be removed from the file, so its - use will force @code{-b} mode if - @code{-c} - has not been specified explicitly. - - Note that if the file to be preprocessed contains multiple units, then - it will be necessary to @code{gnatchop} the output file from - @code{gnatprep}. If a @code{Source_Reference} pragma is present - in the preprocessed file, it will be respected by - @code{gnatchop -r} - so that the final chopped files will correctly refer to the original - input source file for @code{gnatprep}. - - @item -s - Causes a sorted list of symbol names and values to be - listed on the standard output file. - - @item -u - Causes undefined symbols to be treated as having the value FALSE in the context - of a preprocessor test. In the absence of this option, an undefined symbol in - a @code{#if} or @code{#elsif} test will be treated as an error. - - @end table - - @noindent - Note: if neither @code{-b} nor @code{-c} is present, - then preprocessor lines and - deleted lines are completely removed from the output, unless -r is - specified, in which case -b is assumed. - - @node Form of Definitions File - @section Form of Definitions File - - @noindent - The definitions file contains lines of the form - - @smallexample - symbol := value - @end smallexample - - @noindent - where symbol is an identifier, following normal Ada (case-insensitive) - rules for its syntax, and value is one of the following: - - @itemize @bullet - @item - Empty, corresponding to a null substitution - @item - A string literal using normal Ada syntax - @item - Any sequence of characters from the set - (letters, digits, period, underline). - @end itemize - - @noindent - Comment lines may also appear in the definitions file, starting with - the usual @code{--}, - and comments may be added to the definitions lines. - - @node Form of Input Text for gnatprep - @section Form of Input Text for @code{gnatprep} - - @noindent - The input text may contain preprocessor conditional inclusion lines, - as well as general symbol substitution sequences. - - The preprocessor conditional inclusion commands have the form - - @smallexample - @group - @cartouche - #if @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - ... - #else - lines - #end if; - @end cartouche - @end group - @end smallexample - - @noindent - In this example, @i{expression} is defined by the following grammar: - @smallexample - @i{expression} ::= - @i{expression} ::= = "" - @i{expression} ::= = - @i{expression} ::= 'Defined - @i{expression} ::= not @i{expression} - @i{expression} ::= @i{expression} and @i{expression} - @i{expression} ::= @i{expression} or @i{expression} - @i{expression} ::= @i{expression} and then @i{expression} - @i{expression} ::= @i{expression} or else @i{expression} - @i{expression} ::= ( @i{expression} ) - @end smallexample - - @noindent - For the first test (@i{expression} ::= ) the symbol must have - either the value true or false, that is to say the right-hand of the - symbol definition must be one of the (case-insensitive) literals - @code{True} or @code{False}. If the value is true, then the - corresponding lines are included, and if the value is false, they are - excluded. - - The test (@i{expression} ::= @code{'Defined}) is true only if - the symbol has been defined in the definition file or by a @code{-D} - switch on the command line. Otherwise, the test is false. - - The equality tests are case insensitive, as are all the preprocessor lines. - - If the symbol referenced is not defined in the symbol definitions file, - then the effect depends on whether or not switch @code{-u} - is specified. If so, then the symbol is treated as if it had the value - false and the test fails. If this switch is not specified, then - it is an error to reference an undefined symbol. It is also an error to - reference a symbol that is defined with a value other than @code{True} - or @code{False}. - - The use of the @code{not} operator inverts the sense of this logical test, so - that the lines are included only if the symbol is not defined. - The @code{then} keyword is optional as shown - - The @code{#} must be the first non-blank character on a line, but - otherwise the format is free form. Spaces or tabs may appear between - the @code{#} and the keyword. The keywords and the symbols are case - insensitive as in normal Ada code. Comments may be used on a - preprocessor line, but other than that, no other tokens may appear on a - preprocessor line. Any number of @code{elsif} clauses can be present, - including none at all. The @code{else} is optional, as in Ada. - - The @code{#} marking the start of a preprocessor line must be the first - non-blank character on the line, i.e. it must be preceded only by - spaces or horizontal tabs. - - Symbol substitution outside of preprocessor lines is obtained by using - the sequence - - @smallexample - $symbol - @end smallexample - - @noindent - anywhere within a source line, except in a comment or within a - string literal. The identifier - following the @code{$} must match one of the symbols defined in the symbol - definition file, and the result is to substitute the value of the - symbol in place of @code{$symbol} in the output file. - - Note that although the substitution of strings within a string literal - is not possible, it is possible to have a symbol whose defined value is - a string literal. So instead of setting XYZ to @code{hello} and writing: - - @smallexample - Header : String := "$XYZ"; - @end smallexample - - @noindent - you should set XYZ to @code{"hello"} and write: - - @smallexample - Header : String := $XYZ; - @end smallexample - - @noindent - and then the substitution will occur as desired. - - - @node The GNAT Library Browser gnatls - @chapter The GNAT Library Browser @code{gnatls} - @findex gnatls - @cindex Library browser - - @noindent - @code{gnatls} is a tool that outputs information about compiled - units. It gives the relationship between objects, unit names and source - files. It can also be used to check the source dependencies of a unit - as well as various characteristics. - - @menu - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - @end menu - - @node Running gnatls - @section Running @code{gnatls} - - @noindent - The @code{gnatls} command has the form - - @smallexample - $ gnatls switches @var{object_or_ali_file} - @end smallexample - - @noindent - The main argument is the list of object or @file{ali} files - (@pxref{The Ada Library Information Files}) - for which information is requested. - - In normal mode, without additional option, @code{gnatls} produces a - four-column listing. Each line represents information for a specific - object. The first column gives the full path of the object, the second - column gives the name of the principal unit in this object, the third - column gives the status of the source and the fourth column gives the - full path of the source representing this unit. - Here is a simple example of use: - - @smallexample - $ gnatls *.o - ./demo1.o demo1 DIF demo1.adb - ./demo2.o demo2 OK demo2.adb - ./hello.o h1 OK hello.adb - ./instr-child.o instr.child MOK instr-child.adb - ./instr.o instr OK instr.adb - ./tef.o tef DIF tef.adb - ./text_io_example.o text_io_example OK text_io_example.adb - ./tgef.o tgef DIF tgef.adb - @end smallexample - - @noindent - The first line can be interpreted as follows: the main unit which is - contained in - object file @file{demo1.o} is demo1, whose main source is in - @file{demo1.adb}. Furthermore, the version of the source used for the - compilation of demo1 has been modified (DIF). Each source file has a status - qualifier which can be: - - @table @code - @item OK (unchanged) - The version of the source file used for the compilation of the - specified unit corresponds exactly to the actual source file. - - @item MOK (slightly modified) - The version of the source file used for the compilation of the - specified unit differs from the actual source file but not enough to - require recompilation. If you use gnatmake with the qualifier - @code{-m (minimal recompilation)}, a file marked - MOK will not be recompiled. - - @item DIF (modified) - No version of the source found on the path corresponds to the source - used to build this object. - - @item ??? (file not found) - No source file was found for this unit. - - @item HID (hidden, unchanged version not first on PATH) - The version of the source that corresponds exactly to the source used - for compilation has been found on the path but it is hidden by another - version of the same source that has been modified. - - @end table - - @node Switches for gnatls - @section Switches for @code{gnatls} - - @noindent - @code{gnatls} recognizes the following switches: - - @table @code - @item -a - @cindex @code{-a} (@code{gnatls}) - Consider all units, including those of the predefined Ada library. - Especially useful with @code{-d}. - - @item -d - @cindex @code{-d} (@code{gnatls}) - List sources from which specified units depend on. - - @item -h - @cindex @code{-h} (@code{gnatls}) - Output the list of options. - - @item -o - @cindex @code{-o} (@code{gnatls}) - Only output information about object files. - - @item -s - @cindex @code{-s} (@code{gnatls}) - Only output information about source files. - - @item -u - @cindex @code{-u} (@code{gnatls}) - Only output information about compilation units. - - @item -aO@var{dir} - @itemx -aI@var{dir} - @itemx -I@var{dir} - @itemx -I- - @itemx -nostdinc - Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags - (see @ref{Switches for gnatmake}). - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatls}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -v - @cindex @code{-s} (@code{gnatls}) - Verbose mode. Output the complete source and object paths. Do not use - the default column layout but instead use long format giving as much as - information possible on each requested units, including special - characteristics such as: - - @table @code - @item Preelaborable - The unit is preelaborable in the Ada 95 sense. - - @item No_Elab_Code - No elaboration code has been produced by the compiler for this unit. - - @item Pure - The unit is pure in the Ada 95 sense. - - @item Elaborate_Body - The unit contains a pragma Elaborate_Body. - - @item Remote_Types - The unit contains a pragma Remote_Types. - - @item Shared_Passive - The unit contains a pragma Shared_Passive. - - @item Predefined - This unit is part of the predefined environment and cannot be modified - by the user. - - @item Remote_Call_Interface - The unit contains a pragma Remote_Call_Interface. - - @end table - - @end table - - @node Examples of gnatls Usage - @section Example of @code{gnatls} Usage - - @noindent - Example of using the verbose switch. Note how the source and - object paths are affected by the -I switch. - - @smallexample - $ gnatls -v -I.. demo1.o - - GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc. - - Source Search Path: - - ../ - /home/comar/local/adainclude/ - - Object Search Path: - - ../ - /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/ - - ./demo1.o - Unit => - Name => demo1 - Kind => subprogram body - Flags => No_Elab_Code - Source => demo1.adb modified - @end smallexample - - @noindent - The following is an example of use of the dependency list. - Note the use of the -s switch - which gives a straight list of source files. This can be useful for - building specialized scripts. - - @smallexample - $ gnatls -d demo2.o - ./demo2.o demo2 OK demo2.adb - OK gen_list.ads - OK gen_list.adb - OK instr.ads - OK instr-child.ads - - $ gnatls -d -s -a demo1.o - demo1.adb - /home/comar/local/adainclude/ada.ads - /home/comar/local/adainclude/a-finali.ads - /home/comar/local/adainclude/a-filico.ads - /home/comar/local/adainclude/a-stream.ads - /home/comar/local/adainclude/a-tags.ads - gen_list.ads - gen_list.adb - /home/comar/local/adainclude/gnat.ads - /home/comar/local/adainclude/g-io.ads - instr.ads - /home/comar/local/adainclude/system.ads - /home/comar/local/adainclude/s-exctab.ads - /home/comar/local/adainclude/s-finimp.ads - /home/comar/local/adainclude/s-finroo.ads - /home/comar/local/adainclude/s-secsta.ads - /home/comar/local/adainclude/s-stalib.ads - /home/comar/local/adainclude/s-stoele.ads - /home/comar/local/adainclude/s-stratt.ads - /home/comar/local/adainclude/s-tasoli.ads - /home/comar/local/adainclude/s-unstyp.ads - /home/comar/local/adainclude/unchconv.ads - @end smallexample - - - @node GNAT and Libraries - @chapter GNAT and Libraries - @cindex Library, building, installing - - @noindent - This chapter addresses some of the issues related to building and using - a library with GNAT. It also shows how the GNAT run-time library can be - recompiled. - - @menu - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - @end menu - - @node Creating an Ada Library - @section Creating an Ada Library - - @noindent - In the GNAT environment, a library has two components: - @itemize @bullet - @item - Source files. - @item - Compiled code and Ali files. See @ref{The Ada Library Information Files}. - @end itemize - - @noindent - In order to use other packages @ref{The GNAT Compilation Model} - requires a certain number of sources to be available to the compiler. - The minimal set of - sources required includes the specs of all the packages that make up the - visible part of the library as well as all the sources upon which they - depend. The bodies of all visible generic units must also be provided. - @noindent - Although it is not strictly mandatory, it is recommended that all sources - needed to recompile the library be provided, so that the user can make - full use of inter-unit inlining and source-level debugging. This can also - make the situation easier for users that need to upgrade their compilation - toolchain and thus need to recompile the library from sources. - - @noindent - The compiled code can be provided in different ways. The simplest way is - to provide directly the set of objects produced by the compiler during - the compilation of the library. It is also possible to group the objects - into an archive using whatever commands are provided by the operating - system. Finally, it is also possible to create a shared library (see - option -shared in the GCC manual). - - @noindent - There are various possibilities for compiling the units that make up the - library: for example with a Makefile @ref{Using the GNU make Utility}, - or with a conventional script. - For simple libraries, it is also possible to create a - dummy main program which depends upon all the packages that comprise the - interface of the library. This dummy main program can then be given to - gnatmake, in order to build all the necessary objects. Here is an example - of such a dummy program and the generic commands used to build an - archive or a shared library. - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - @b{with} My_Lib.Service1; - @b{with} My_Lib.Service2; - @b{with} My_Lib.Service3; - @b{procedure} My_Lib_Dummy @b{is} - @b{begin} - @b{null}; - @b{end}; - - # compiling the library - $ gnatmake -c my_lib_dummy.adb - - # we don't need the dummy object itself - $ rm my_lib_dummy.o my_lib_dummy.ali - - # create an archive with the remaining objects - $ ar rc libmy_lib.a *.o - # some systems may require "ranlib" to be run as well - - # or create a shared library - $ gcc -shared -o libmy_lib.so *.o - # some systems may require the code to have been compiled with -fPIC - @end smallexample - - @noindent - When the objects are grouped in an archive or a shared library, the user - needs to specify the desired library at link time, unless a pragma - linker_options has been used in one of the sources: - @smallexample - @b{pragma} Linker_Options ("-lmy_lib"); - @end smallexample - - @node Installing an Ada Library - @section Installing an Ada Library - - @noindent - In the GNAT model, installing a library consists in copying into a specific - location the files that make up this library. It is possible to install - the sources in a different directory from the other files (ALI, objects, - archives) since the source path and the object path can easily be - specified separately. - - @noindent - For general purpose libraries, it is possible for the system - administrator to put those libraries in the default compiler paths. To - achieve this, he must specify their location in the configuration files - "ada_source_path" and "ada_object_path" that must be located in the GNAT - installation tree at the same place as the gcc spec file. The location of - the gcc spec file can be determined as follows: - @smallexample - $ gcc -v - @end smallexample - - @noindent - The configuration files mentioned above have simple format: each line in them - must contain one unique - directory name. Those names are added to the corresponding path - in their order of appearance in the file. The names can be either absolute - or relative, in the latter case, they are relative to where theses files - are located. - - @noindent - "ada_source_path" and "ada_object_path" might actually not be present in a - GNAT installation, in which case, GNAT will look for its run-time library in - the directories "adainclude" for the sources and "adalib" for the - objects and ALI files. When the files exist, the compiler does not - look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file - must contain the location for the GNAT run-time sources (which can simply - be "adainclude"). In the same way, the "ada_object_path" file must contain - the location for the GNAT run-time objects (which can simply - be "adalib"). - - @noindent - You can also specify a new default path to the runtime library at compilation - time with the switch "--RTS=@var{rts-path}". You can easily choose and change - the runtime you want your program to be compiled with. This switch is - recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref. - - @noindent - It is possible to install a library before or after the standard GNAT - library, by reordering the lines in the configuration files. In general, a - library must be installed before the GNAT library if it redefines any part of it. - - @node Using an Ada Library - @section Using an Ada Library - - @noindent - In order to use a Ada library, you need to make sure that this - library is on both your source and object path - @ref{Search Paths and the Run-Time Library (RTL)} - and @ref{Search Paths for gnatbind}. For - instance, you can use the library "mylib" installed in "/dir/my_lib_src" - and "/dir/my_lib_obj" with the following commands: - - @smallexample - $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \ - -largs -lmy_lib - @end smallexample - - @noindent - This can be simplified down to the following: - @smallexample - $ gnatmake my_appl - @end smallexample - when the following conditions are met: - @itemize @bullet - @item - "/dir/my_lib_src" has been added by the user to the environment - variable "ADA_INCLUDE_PATH", or by the administrator to the file - "ada_source_path" - @item - "/dir/my_lib_obj" has been added by the user to the environment - variable "ADA_OBJECTS_PATH", or by the administrator to the file - "ada_object_path" - @item - a pragma linker_options, as mentioned in @ref{Creating an Ada Library} - as been added to the sources. - @end itemize - @noindent - - @node Creating an Ada Library to be Used in a Non-Ada Context - @section Creating an Ada Library to be Used in a Non-Ada Context - - @noindent - The previous sections detailed how to create and install a library that - was usable from an Ada main program. Using this library in a non-Ada - context is not possible, because the elaboration of the library is - automatically done as part of the main program elaboration. - - GNAT also provides the ability to build libraries that can be used both - in an Ada and non-Ada context. This section describes how to build such - a library, and then how to use it from a C program. The method for - interfacing with the library from other languages such as Fortran for - instance remains the same. - - @subsection Creating the Library - - @itemize @bullet - @item Identify the units representing the interface of the library. - - Here is an example of simple library interface: - - @smallexample - package Interface is - - procedure Do_Something; - - procedure Do_Something_Else; - - end Interface; - @end smallexample - - @item Use @code{pragma Export} or @code{pragma Convention} for the - exported entities. - - Our package @code{Interface} is then updated as follow: - @smallexample - package Interface is - - procedure Do_Something; - pragma Export (C, Do_Something, "do_something"); - - procedure Do_Something_Else; - pragma Export (C, Do_Something_Else, "do_something_else"); - - end Interface; - @end smallexample - - @item Compile all the units composing the library. - - @item Bind the library objects. - - This step is performed by invoking gnatbind with the @code{-L} - switch. @code{gnatbind} will then generate the library elaboration - procedure (named @code{init}) and the run-time finalization - procedure (named @code{final}). - - @smallexample - # generate the binder file in Ada - $ gnatbind -Lmylib interface - - # generate the binder file in C - $ gnatbind -C -Lmylib interface - @end smallexample - - @item Compile the files generated by the binder - - @smallexample - $ gcc -c b~interface.adb - @end smallexample - - @item Create the library; - - The procedure is identical to the procedure explained in - @ref{Creating an Ada Library}, - except that @file{b~interface.o} needs to be added to - the list of objects. - - @smallexample - # create an archive file - $ ar cr libmylib.a b~interface.o - - # create a shared library - $ gcc -shared -o libmylib.so b~interface.o - @end smallexample - - @item Provide a "foreign" view of the library interface; - - The example below shows the content of @code{mylib_interface.h} (note - that there is no rule for the naming of this file, any name can be used) - @smallexample - /* the library elaboration procedure */ - extern void mylibinit (void); - - /* the library finalization procedure */ - extern void mylibfinal (void); - - /* the interface exported by the library */ - extern void do_something (void); - extern void do_something_else (void); - @end smallexample - @end itemize - - @subsection Using the Library - - @noindent - Libraries built as explained above can be used from any program, provided - that the elaboration procedures (named @code{mylibinit} in the previous - example) are called before the library services are used. Any number of - libraries can be used simultaneously, as long as the elaboration - procedure of each library is called. - - Below is an example of C program that uses our @code{mylib} library. - - @smallexample - #include "mylib_interface.h" - - int - main (void) - @{ - /* First, elaborate the library before using it */ - mylibinit (); - - /* Main program, using the library exported entities */ - do_something (); - do_something_else (); - - /* Library finalization at the end of the program */ - mylibfinal (); - return 0; - @} - @end smallexample - - @noindent - Note that this same library can be used from an equivalent Ada main - program. In addition, if the libraries are installed as detailed in - @ref{Installing an Ada Library}, it is not necessary to invoke the - library elaboration and finalization routines. The binder will ensure - that this is done as part of the main program elaboration and - finalization phases. - - @subsection The Finalization Phase - - @noindent - Invoking any library finalization procedure generated by @code{gnatbind} - shuts down the Ada run time permanently. Consequently, the finalization - of all Ada libraries must be performed at the end of the program. No - call to these libraries nor the Ada run time should be made past the - finalization phase. - - @subsection Restrictions in Libraries - - @noindent - The pragmas listed below should be used with caution inside libraries, - as they can create incompatibilities with other Ada libraries: - @itemize @bullet - @item pragma @code{Locking_Policy} - @item pragma @code{Queuing_Policy} - @item pragma @code{Task_Dispatching_Policy} - @item pragma @code{Unreserve_All_Interrupts} - @end itemize - When using a library that contains such pragmas, the user must make sure - that all libraries use the same pragmas with the same values. Otherwise, - a @code{Program_Error} will - be raised during the elaboration of the conflicting - libraries. The usage of these pragmas and its consequences for the user - should therefore be well documented. - - Similarly, the traceback in exception occurrences mechanism should be - enabled or disabled in a consistent manner across all libraries. - Otherwise, a Program_Error will be raised during the elaboration of the - conflicting libraries. - - If the @code{'Version} and @code{'Body_Version} - attributes are used inside a library, then it is necessary to - perform a @code{gnatbind} step that mentions all ali files in all - libraries, so that version identifiers can be properly computed. - In practice these attributes are rarely used, so this is unlikely - to be a consideration. - - @node Rebuilding the GNAT Run-Time Library - @section Rebuilding the GNAT Run-Time Library - - @noindent - It may be useful to recompile the GNAT library in various contexts, the - most important one being the use of partition-wide configuration pragmas - such as Normalize_Scalar. A special Makefile called - @code{Makefile.adalib} is provided to that effect and can be found in - the directory containing the GNAT library. The location of this - directory depends on the way the GNAT environment has been installed and can - be determined by means of the command: - - @smallexample - $ gnatls -v - @end smallexample - - @noindent - The last entry in the object search path usually contains the - gnat library. This Makefile contains its own documentation and in - particular the set of instructions needed to rebuild a new library and - to use it. - - @node Using the GNU make Utility - @chapter Using the GNU @code{make} Utility - @findex make - - @noindent - This chapter offers some examples of makefiles that solve specific - problems. It does not explain how to write a makefile (see the GNU make - documentation), nor does it try to replace the @code{gnatmake} utility - (@pxref{The GNAT Make Program gnatmake}). - - All the examples in this section are specific to the GNU version of - make. Although @code{make} is a standard utility, and the basic language - is the same, these examples use some advanced features found only in - @code{GNU make}. - - @menu - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - @end menu - - @node Using gnatmake in a Makefile - @section Using gnatmake in a Makefile - @findex makefile - @cindex GNU make - - @noindent - Complex project organizations can be handled in a very powerful way by - using GNU make combined with gnatmake. For instance, here is a Makefile - which allows you to build each subsystem of a big project into a separate - shared library. Such a makefile allows you to significantly reduce the link - time of very big applications while maintaining full coherence at - each step of the build process. - - The list of dependencies are handled automatically by - @code{gnatmake}. The Makefile is simply used to call gnatmake in each of - the appropriate directories. - - Note that you should also read the example on how to automatically - create the list of directories (@pxref{Automatically Creating a List of Directories}) - which might help you in case your project has a lot of - subdirectories. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - ## This Makefile is intended to be used with the following directory - ## configuration: - ## - The sources are split into a series of csc (computer software components) - ## Each of these csc is put in its own directory. - ## Their name are referenced by the directory names. - ## They will be compiled into shared library (although this would also work - ## with static libraries - ## - The main program (and possibly other packages that do not belong to any - ## csc is put in the top level directory (where the Makefile is). - ## toplevel_dir __ first_csc (sources) __ lib (will contain the library) - ## \_ second_csc (sources) __ lib (will contain the library) - ## \_ ... - ## Although this Makefile is build for shared library, it is easy to modify - ## to build partial link objects instead (modify the lines with -shared and - ## gnatlink below) - ## - ## With this makefile, you can change any file in the system or add any new - ## file, and everything will be recompiled correctly (only the relevant shared - ## objects will be recompiled, and the main program will be re-linked). - - # The list of computer software component for your project. This might be - # generated automatically. - CSC_LIST=aa bb cc - - # Name of the main program (no extension) - MAIN=main - - # If we need to build objects with -fPIC, uncomment the following line - #NEED_FPIC=-fPIC - - # The following variable should give the directory containing libgnat.so - # You can get this directory through 'gnatls -v'. This is usually the last - # directory in the Object_Path. - GLIB=... - - # The directories for the libraries - # (This macro expands the list of CSC to the list of shared libraries, you - # could simply use the expanded form : - # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so - LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@} - - $@{MAIN@}: objects $@{LIB_DIR@} - gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared - gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@} - - objects:: - # recompile the sources - gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@} - - # Note: In a future version of GNAT, the following commands will be simplified - # by a new tool, gnatmlib - $@{LIB_DIR@}: - mkdir -p $@{dir $@@ @} - cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat - cd $@{dir $@@ @}; cp -f ../*.ali . - - # The dependencies for the modules - # Note that we have to force the expansion of *.o, since in some cases make won't - # be able to do it itself. - aa/lib/libaa.so: $@{wildcard aa/*.o@} - bb/lib/libbb.so: $@{wildcard bb/*.o@} - cc/lib/libcc.so: $@{wildcard cc/*.o@} - - # Make sure all of the shared libraries are in the path before starting the - # program - run:: - LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@} - - clean:: - $@{RM@} -rf $@{CSC_LIST:%=%/lib@} - $@{RM@} $@{CSC_LIST:%=%/*.ali@} - $@{RM@} $@{CSC_LIST:%=%/*.o@} - $@{RM@} *.o *.ali $@{MAIN@} - @end smallexample - - @node Automatically Creating a List of Directories - @section Automatically Creating a List of Directories - - @noindent - In most makefiles, you will have to specify a list of directories, and - store it in a variable. For small projects, it is often easier to - specify each of them by hand, since you then have full control over what - is the proper order for these directories, which ones should be - included... - - However, in larger projects, which might involve hundreds of - subdirectories, it might be more convenient to generate this list - automatically. - - The example below presents two methods. The first one, although less - general, gives you more control over the list. It involves wildcard - characters, that are automatically expanded by @code{make}. Its - shortcoming is that you need to explicitly specify some of the - organization of your project, such as for instance the directory tree - depth, whether some directories are found in a separate tree,... - - The second method is the most general one. It requires an external - program, called @code{find}, which is standard on all Unix systems. All - the directories found under a given root directory will be added to the - list. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # The examples below are based on the following directory hierarchy: - # All the directories can contain any number of files - # ROOT_DIRECTORY -> a -> aa -> aaa - # -> ab - # -> ac - # -> b -> ba -> baa - # -> bb - # -> bc - # This Makefile creates a variable called DIRS, that can be reused any time - # you need this list (see the other examples in this section) - - # The root of your project's directory hierarchy - ROOT_DIRECTORY=. - - #### - # First method: specify explicitly the list of directories - # This allows you to specify any subset of all the directories you need. - #### - - DIRS := a/aa/ a/ab/ b/ba/ - - #### - # Second method: use wildcards - # Note that the argument(s) to wildcard below should end with a '/'. - # Since wildcards also return file names, we have to filter them out - # to avoid duplicate directory names. - # We thus use make's @code{dir} and @code{sort} functions. - # It sets DIRs to the following value (note that the directories aaa and baa - # are not given, unless you change the arguments to wildcard). - # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/ - #### - - DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@} - - #### - # Third method: use an external program - # This command is much faster if run on local disks, avoiding NFS slowdowns. - # This is the most complete command: it sets DIRs to the following value: - # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc - #### - - DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@} - - @end smallexample - - @node Generating the Command Line Switches - @section Generating the Command Line Switches - - @noindent - Once you have created the list of directories as explained in the - previous section (@pxref{Automatically Creating a List of Directories}), - you can easily generate the command line arguments to pass to gnatmake. - - For the sake of completeness, this example assumes that the source path - is not the same as the object path, and that you have two separate lists - of directories. - - @smallexample - # see "Automatically creating a list of directories" to create - # these variables - SOURCE_DIRS= - OBJECT_DIRS= - - GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@} - GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@} - - all: - gnatmake $@{GNATMAKE_SWITCHES@} main_unit - @end smallexample - - @node Overcoming Command Line Length Limits - @section Overcoming Command Line Length Limits - - @noindent - One problem that might be encountered on big projects is that many - operating systems limit the length of the command line. It is thus hard to give - gnatmake the list of source and object directories. - - This example shows how you can set up environment variables, which will - make @code{gnatmake} behave exactly as if the directories had been - specified on the command line, but have a much higher length limit (or - even none on most systems). - - It assumes that you have created a list of directories in your Makefile, - using one of the methods presented in - @ref{Automatically Creating a List of Directories}. - For the sake of completeness, we assume that the object - path (where the ALI files are found) is different from the sources patch. - - Note a small trick in the Makefile below: for efficiency reasons, we - create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are - expanded immediately by @code{make}. This way we overcome the standard - make behavior which is to expand the variables only when they are - actually used. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH. - # This is the same thing as putting the -I arguments on the command line. - # (the equivalent of using -aI on the command line would be to define - # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH). - # You can of course have different values for these variables. - # - # Note also that we need to keep the previous values of these variables, since - # they might have been set before running 'make' to specify where the GNAT - # library is installed. - - # see "Automatically creating a list of directories" to create these - # variables - SOURCE_DIRS= - OBJECT_DIRS= - - empty:= - space:=$@{empty@} $@{empty@} - SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@} - OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@} - ADA_INCLUDE_PATH += $@{SOURCE_LIST@} - ADA_OBJECT_PATH += $@{OBJECT_LIST@} - export ADA_INCLUDE_PATH - export ADA_OBJECT_PATH - - all: - gnatmake main_unit - @end smallexample - - - @node Finding Memory Problems with GNAT Debug Pool - @chapter Finding Memory Problems with GNAT Debug Pool - @findex Debug Pool - @cindex storage, pool, memory corruption - - @noindent - The use of unchecked deallocation and unchecked conversion can easily - lead to incorrect memory references. The problems generated by such - references are usually difficult to tackle because the symptoms can be - very remote from the origin of the problem. In such cases, it is - very helpful to detect the problem as early as possible. This is the - purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. - - @noindent - In order to use the GNAT specific debugging pool, the user must - associate a debug pool object with each of the access types that may be - related to suspected memory problems. See Ada Reference Manual - 13.11. - @smallexample - @b{type} Ptr @b{is} @b{access} Some_Type; - Pool : GNAT.Debug_Pools.Debug_Pool; - @b{for} Ptr'Storage_Pool @b{use} Pool; - @end smallexample - - @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of - pool: the Checked_Pool. Such pools, like standard Ada storage pools, - allow the user to redefine allocation and deallocation strategies. They - also provide a checkpoint for each dereference, through the use of - the primitive operation @code{Dereference} which is implicitly called at - each dereference of an access value. - - Once an access type has been associated with a debug pool, operations on - values of the type may raise four distinct exceptions, - which correspond to four potential kinds of memory corruption: - @itemize @bullet - @item - @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } - @end itemize - - @noindent - For types associated with a Debug_Pool, dynamic allocation is performed using - the standard - GNAT allocation routine. References to all allocated chunks of memory - are kept in an internal dictionary. The deallocation strategy consists - in not releasing the memory to the underlying system but rather to fill - it with a memory pattern easily recognizable during debugging sessions: - The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#. - Upon each dereference, a check is made that the access value denotes a properly - allocated memory location. Here is a complete example of use of - @code{Debug_Pools}, that includes typical instances of memory corruption: - @smallexample - @iftex - @leftskip=0cm - @end iftex - @b{with} Gnat.Io; @b{use} Gnat.Io; - @b{with} Unchecked_Deallocation; - @b{with} Unchecked_Conversion; - @b{with} GNAT.Debug_Pools; - @b{with} System.Storage_Elements; - @b{with} Ada.Exceptions; @b{use} Ada.Exceptions; - @b{procedure} Debug_Pool_Test @b{is} - - @b{type} T @b{is} @b{access} Integer; - @b{type} U @b{is} @b{access} @b{all} T; - - P : GNAT.Debug_Pools.Debug_Pool; - @b{for} T'Storage_Pool @b{use} P; - - @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T); - @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T); - A, B : @b{aliased} T; - - @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line); - - @b{begin} - Info (P); - A := @b{new} Integer; - B := @b{new} Integer; - B := A; - Info (P); - Free (A); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - B := UC(A'Access); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - Info (P); - @b{end} Debug_Pool_Test; - @end smallexample - @noindent - The debug pool mechanism provides the following precise diagnostics on the - execution of this erroneous program: - @smallexample - Debug Pool info: - Total allocated bytes : 0 - Total deallocated bytes : 0 - Current Water Mark: 0 - High Water Mark: 0 - - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 0 - Current Water Mark: 8 - High Water Mark: 8 - - raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 4 - Current Water Mark: 4 - High Water Mark: 8 - - @end smallexample - - @node Creating Sample Bodies Using gnatstub - @chapter Creating Sample Bodies Using @code{gnatstub} - @findex gnatstub - - @noindent - @code{gnatstub} creates body stubs, that is, empty but compilable bodies - for library unit declarations. - - To create a body stub, @code{gnatstub} has to compile the library - unit declaration. Therefore, bodies can be created only for legal - library units. Moreover, if a library unit depends semantically upon - units located outside the current directory, you have to provide - the source search path when calling @code{gnatstub}, see the description - of @code{gnatstub} switches below. - - @menu - * Running gnatstub:: - * Switches for gnatstub:: - @end menu - - @node Running gnatstub - @section Running @code{gnatstub} - - @noindent - @code{gnatstub} has the command-line interface of the form - - @smallexample - $ gnatstub [switches] filename [directory] - @end smallexample - - @noindent - where - @table @code - @item filename - is the name of the source file that contains a library unit declaration - for which a body must be created. This name should follow the GNAT file name - conventions. No crunching is allowed for this file name. The file - name may contain the path information. - - @item directory - indicates the directory to place a body stub (default is the - current directory) - - @item switches - is an optional sequence of switches as described in the next section - @end table - - @node Switches for gnatstub - @section Switches for @code{gnatstub} - - @table @code - - @item -f - If the destination directory already contains a file with a name of the body file - for the argument spec file, replace it with the generated body stub. - - @item -hs - Put the comment header (i.e. all the comments preceding the - compilation unit) from the source of the library unit declaration - into the body stub. - - @item -hg - Put a sample comment header into the body stub. - - @item -IDIR - @itemx -I- - These switches have the same meaning as in calls to gcc. - They define the source search path in the call to gcc issued - by @code{gnatstub} to compile an argument source file. - - @item -i@var{n} - (@var{n} is a decimal natural number). Set the indentation level in the - generated body sample to n, '-i0' means "no indentation", - the default indentation is 3. - - @item -k - Do not remove the tree file (i.e. the snapshot of the compiler internal - structures used by @code{gnatstub}) after creating the body stub. - - @item -l@var{n} - (@var{n} is a decimal positive number) Set the maximum line length in the - body stub to n, the default is 78. - - @item -q - Quiet mode: do not generate a confirmation when a body is - successfully created or a message when a body is not required for an - argument unit. - - @item -r - Reuse the tree file (if it exists) instead of creating it: instead of - creating the tree file for the library unit declaration, gnatstub - tries to find it in the current directory and use it for creating - a body. If the tree file is not found, no body is created. @code{-r} - also implies @code{-k}, whether or not - @code{-k} is set explicitly. - - @item -t - Overwrite the existing tree file: if the current directory already - contains the file which, according to the GNAT file name rules should - be considered as a tree file for the argument source file, gnatstub - will refuse to create the tree file needed to create a body sampler, - unless @code{-t} option is set - - @item -v - Verbose mode: generate version information. - - @end table - - @node Reducing the Size of Ada Executables with gnatelim - @chapter Reducing the Size of Ada Executables with @code{gnatelim} - @findex gnatelim - - @menu - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - @end menu - - @node About gnatelim - @section About @code{gnatelim} - - @noindent - When a program shares a set of Ada - packages with other programs, it may happen that this program uses - only a fraction of the subprograms defined in these packages. The code - created for these unused subprograms increases the size of the executable. - - @code{gnatelim} tracks unused subprograms in an Ada program and - outputs a list of GNAT-specific @code{Eliminate} pragmas (see next - section) marking all the subprograms that are declared but never called. - By placing the list of @code{Eliminate} pragmas in the GNAT configuration - file @file{gnat.adc} and recompiling your program, you may decrease the - size of its executable, because the compiler will not generate the code - for 'eliminated' subprograms. - - @code{gnatelim} needs as its input data a set of tree files - (see @ref{Tree Files}) representing all the components of a program to - process and a bind file for a main subprogram (see - @ref{Preparing Tree and Bind Files for gnatelim}). - - @node Eliminate Pragma - @section @code{Eliminate} Pragma - @findex Eliminate - - @noindent - The simplified syntax of the Eliminate pragma used by @code{gnatelim} is: - - @smallexample - @cartouche - @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name); - @end cartouche - @end smallexample - - @noindent - where - @table @code - @item Library_Unit_Name - full expanded Ada name of a library unit - - @item Subprogram_Name - a simple or expanded name of a subprogram declared within this - compilation unit - - @end table - - @noindent - The effect of an @code{Eliminate} pragma placed in the GNAT configuration - file @file{gnat.adc} is: - - @itemize @bullet - - @item - If the subprogram @code{Subprogram_Name} is declared within - the library unit @code{Library_Unit_Name}, the compiler will not generate - code for this subprogram. This applies to all overloaded subprograms denoted - by @code{Subprogram_Name}. - - @item - If a subprogram marked by the pragma @code{Eliminate} is used (called) - in a program, the compiler will produce an error message in the place where - it is called. - @end itemize - - @node Tree Files - @section Tree Files - @cindex Tree file - - @noindent - A tree file stores a snapshot of the compiler internal data - structures at the very end of a successful compilation. It contains all the - syntactic and semantic information for the compiled unit and all the - units upon which it depends semantically. - To use tools that make use of tree files, you - need to first produce the right set of tree files. - - GNAT produces correct tree files when -gnatt -gnatc options are set - in a gcc call. The tree files have an .adt extension. - Therefore, to produce a tree file for the compilation unit contained in a file - named @file{foo.adb}, you must use the command - - @smallexample - $ gcc -c -gnatc -gnatt foo.adb - @end smallexample - - @noindent - and you will get the tree file @file{foo.adt}. - compilation. - - @node Preparing Tree and Bind Files for gnatelim - @section Preparing Tree and Bind Files for @code{gnatelim} - - @noindent - A set of tree files covering the program to be analyzed with - @code{gnatelim} and - the bind file for the main subprogram does not have to - be in the current directory. - '-T' gnatelim option may be used to provide - the search path for tree files, and '-b' - option may be used to point to the bind - file to process (see @ref{Running gnatelim}) - - If you do not have the appropriate set of tree - files and the right bind file, you - may create them in the current directory using the following procedure. - - Let @code{Main_Prog} be the name of a main subprogram, and suppose - this subprogram is in a file named @file{main_prog.adb}. - - To create a bind file for @code{gnatelim}, run @code{gnatbind} for - the main subprogram. @code{gnatelim} can work with both Ada and C - bind files; when both are present, it uses the Ada bind file. - The following commands will build the program and create the bind file: - - @smallexample - $ gnatmake -c Main_Prog - $ gnatbind main_prog - @end smallexample - - @noindent - To create a minimal set of tree files covering the whole program, call - @code{gnatmake} for this program as follows: - - @smallexample - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end smallexample - - @noindent - The @code{-c} gnatmake option turns off the bind and link - steps, that are useless anyway because the sources are compiled with - @option{-gnatc} option which turns off code generation. - - The @code{-f} gnatmake option forces - recompilation of all the needed sources. - - This sequence of actions will create all the data needed by @code{gnatelim} - from scratch and therefore guarantee its consistency. If you would like to - use some existing set of files as @code{gnatelim} output, you must make - sure that the set of files is complete and consistent. You can use the - @code{-m} switch to check if there are missed tree files - - Note, that @code{gnatelim} needs neither object nor ALI files. - - @node Running gnatelim - @section Running @code{gnatelim} - - @noindent - @code{gnatelim} has the following command-line interface: - - @smallexample - $ gnatelim [options] name - @end smallexample - - @noindent - @code{name} should be a full expanded Ada name of a main subprogram - of a program (partition). - - @code{gnatelim} options: - - @table @code - @item -q - Quiet mode: by default @code{gnatelim} generates to the standard error - stream a trace of the source file names of the compilation units being - processed. This option turns this trace off. - - @item -v - Verbose mode: @code{gnatelim} version information is printed as Ada - comments to the standard output stream. - - @item -a - Also look for subprograms from the GNAT run time that can be eliminated. - - @item -m - Check if any tree files are missing for an accurate result. - - @item -T@var{dir} - When looking for tree files also look in directory @var{dir} - - @item -b@var{bind_file} - Specifies @var{bind_file} as the bind file to process. If not set, the name - of the bind file is computed from the full expanded Ada name of a main subprogram. - - @item -d@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - mode desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Gnatelim.Options} unit in the compiler - source file @file{gnatelim-options.adb}. - @end table - - @noindent - @code{gnatelim} sends its output to the standard output stream, and all the - tracing and debug information is sent to the standard error stream. - In order to produce a proper GNAT configuration file - @file{gnat.adc}, redirection must be used: - - @smallexample - $ gnatelim Main_Prog > gnat.adc - @end smallexample - - @noindent - or - - @smallexample - $ gnatelim Main_Prog >> gnat.adc - @end smallexample - - @noindent - In order to append the @code{gnatelim} output to the existing contents of - @file{gnat.adc}. - - @node Correcting the List of Eliminate Pragmas - @section Correcting the List of Eliminate Pragmas - - @noindent - In some rare cases it may happen that @code{gnatelim} will try to eliminate - subprograms which are actually called in the program. In this case, the - compiler will generate an error message of the form: - - @smallexample - file.adb:106:07: cannot call eliminated subprogram "My_Prog" - @end smallexample - - @noindent - You will need to manually remove the wrong @code{Eliminate} pragmas from - the @file{gnat.adc} file. It is advised that you recompile your program - from scratch after that because you need a consistent @file{gnat.adc} file - during the entire compilation. - - @node Making Your Executables Smaller - @section Making Your Executables Smaller - - @noindent - In order to get a smaller executable for your program you now have to - recompile the program completely with the new @file{gnat.adc} file - created by @code{gnatelim} in your current directory: - - @smallexample - $ gnatmake -f Main_Prog - @end smallexample - - @noindent - (you will need @code{-f} option for gnatmake to - recompile everything - with the set of pragmas @code{Eliminate} you have obtained with - @code{gnatelim}). - - Be aware that the set of @code{Eliminate} pragmas is specific to each - program. It is not recommended to merge sets of @code{Eliminate} - pragmas created for different programs in one @file{gnat.adc} file. - - @node Summary of the gnatelim Usage Cycle - @section Summary of the gnatelim Usage Cycle - - @noindent - Here is a quick summary of the steps to be taken in order to reduce - the size of your executables with @code{gnatelim}. You may use - other GNAT options to control the optimization level, - to produce the debugging information, to set search path, etc. - - @enumerate - @item - Produce a bind file and a set of tree files - - @smallexample - $ gnatmake -c Main_Prog - $ gnatbind main_prog - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end smallexample - - @item - Generate a list of @code{Eliminate} pragmas - @smallexample - $ gnatelim Main_Prog >[>] gnat.adc - @end smallexample - - @item - Recompile the application - - @smallexample - $ gnatmake -f Main_Prog - @end smallexample - - @end enumerate - - @node Other Utility Programs - @chapter Other Utility Programs - - @noindent - This chapter discusses some other utility programs available in the Ada - environment. - - @menu - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - * Installing gnathtml:: - @end menu - - @node Using Other Utility Programs with GNAT - @section Using Other Utility Programs with GNAT - - @noindent - The object files generated by GNAT are in standard system format and in - particular the debugging information uses this format. This means - programs generated by GNAT can be used with existing utilities that - depend on these formats. - - In general, any utility program that works with C will also often work with - Ada programs generated by GNAT. This includes software utilities such as - gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such - as Purify. - - @node The gnatpsta Utility Program - @section The @code{gnatpsta} Utility Program - - @noindent - Many of the definitions in package Standard are implementation-dependent. - However, the source of this package does not exist as an Ada source - file, so these values cannot be determined by inspecting the source. - They can be determined by examining in detail the coding of - @file{cstand.adb} which creates the image of Standard in the compiler, - but this is awkward and requires a great deal of internal knowledge - about the system. - - The @code{gnatpsta} utility is designed to deal with this situation. - It is an Ada program that dynamically determines the - values of all the relevant parameters in Standard, and prints them - out in the form of an Ada source listing for Standard, displaying all - the values of interest. This output is generated to - @file{stdout}. - - To determine the value of any parameter in package Standard, simply - run @code{gnatpsta} with no qualifiers or arguments, and examine - the output. This is preferable to consulting documentation, because - you know that the values you are getting are the actual ones provided - by the executing system. - - @node The External Symbol Naming Scheme of GNAT - @section The External Symbol Naming Scheme of GNAT - - @noindent - In order to interpret the output from GNAT, when using tools that are - originally intended for use with other languages, it is useful to - understand the conventions used to generate link names from the Ada - entity names. - - All link names are in all lowercase letters. With the exception of library - procedure names, the mechanism used is simply to use the full expanded - Ada name with dots replaced by double underscores. For example, suppose - we have the following package spec: - - @smallexample - @group - @cartouche - @b{package} QRS @b{is} - MN : Integer; - @b{end} QRS; - @end cartouche - @end group - @end smallexample - - @noindent - The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so - the corresponding link name is @code{qrs__mn}. - @findex Export - Of course if a @code{pragma Export} is used this may be overridden: - - @smallexample - @group - @cartouche - @b{package} Exports @b{is} - Var1 : Integer; - @b{pragma} Export (Var1, C, External_Name => "var1_name"); - Var2 : Integer; - @b{pragma} Export (Var2, C, Link_Name => "var2_link_name"); - @b{end} Exports; - @end cartouche - @end group - @end smallexample - - @noindent - In this case, the link name for @var{Var1} is whatever link name the - C compiler would assign for the C function @var{var1_name}. This typically - would be either @var{var1_name} or @var{_var1_name}, depending on operating - system conventions, but other possibilities exist. The link name for - @var{Var2} is @var{var2_link_name}, and this is not operating system - dependent. - - @findex _main - One exception occurs for library level procedures. A potential ambiguity - arises between the required name @code{_main} for the C main program, - and the name we would otherwise assign to an Ada library level procedure - called @code{Main} (which might well not be the main program). - - To avoid this ambiguity, we attach the prefix @code{_ada_} to such - names. So if we have a library level procedure such as - - @smallexample - @group - @cartouche - @b{procedure} Hello (S : String); - @end cartouche - @end group - @end smallexample - - @noindent - the external name of this procedure will be @var{_ada_hello}. - - @node Ada Mode for Glide - @section Ada Mode for @code{Glide} - - @noindent - The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the - user in understanding existing code and facilitates writing new code. It - furthermore provides some utility functions for easier integration of - standard Emacs features when programming in Ada. - - @subsection General Features: - - @itemize @bullet - @item - Full Integrated Development Environment : - - @itemize @bullet - @item - support of 'project files' for the configuration (directories, - compilation options,...) - - @item - compiling and stepping through error messages. - - @item - running and debugging your applications within Glide. - @end itemize - - @item - easy to use for beginners by pull-down menus, - - @item - user configurable by many user-option variables. - @end itemize - - @subsection Ada Mode Features That Help Understanding Code: - - @itemize @bullet - @item - functions for easy and quick stepping through Ada code, - - @item - getting cross reference information for identifiers (e.g. find the - defining place by a keystroke), - - @item - displaying an index menu of types and subprograms and move point to - the chosen one, - - @item - automatic color highlighting of the various entities in Ada code. - @end itemize - - @subsection Glide Support for Writing Ada Code: - - @itemize @bullet - @item - switching between spec and body files with possible - autogeneration of body files, - - @item - automatic formating of subprograms parameter lists. - - @item - automatic smart indentation according to Ada syntax, - - @item - automatic completion of identifiers, - - @item - automatic casing of identifiers, keywords, and attributes, - - @item - insertion of statement templates, - - @item - filling comment paragraphs like filling normal text, - @end itemize - - For more information, please refer to the online Glide documentation - available in the Glide --> Help Menu. - - @node Converting Ada Files to html with gnathtml - @section Converting Ada Files to html with @code{gnathtml} - - @noindent - This @code{Perl} script allows Ada source files to be browsed using - standard Web browsers. For installation procedure, see the section - @xref{Installing gnathtml}. - - Ada reserved keywords are highlighted in a bold font and Ada comments in - a blue font. Unless your program was compiled with the gcc @option{-gnatx} - switch to suppress the generation of cross-referencing information, user - defined variables and types will appear in a different color; you will - be able to click on any identifier and go to its declaration. - - The command line is as follow: - @smallexample - $ perl gnathtml.pl [switches] ada-files - @end smallexample - - You can pass it as many Ada files as you want. @code{gnathtml} will generate - an html file for every ada file, and a global file called @file{index.htm}. - This file is an index of every identifier defined in the files. - - The available switches are the following ones : - - @table @code - @item -83 - @cindex @code{-83} (@code{gnathtml}) - Only the subset on the Ada 83 keywords will be highlighted, not the full - Ada 95 keywords set. - - @item -cc @var{color} - This option allows you to change the color used for comments. The default - value is green. The color argument can be any name accepted by html. - - @item -d - @cindex @code{-d} (@code{gnathtml}) - If the ada files depend on some other files (using for instance the - @code{with} command, the latter will also be converted to html. - Only the files in the user project will be converted to html, not the files - in the run-time library itself. - - @item -D - This command is the same as -d above, but @code{gnathtml} will also look - for files in the run-time library, and generate html files for them. - - @item -f - @cindex @code{-f} (@code{gnathtml}) - By default, gnathtml will generate html links only for global entities - ('with'ed units, global variables and types,...). If you specify the - @code{-f} on the command line, then links will be generated for local - entities too. - - @item -l @var{number} - @cindex @code{-l} (@code{gnathtml}) - If this switch is provided and @var{number} is not 0, then @code{gnathtml} - will number the html files every @var{number} line. - - @item -I @var{dir} - @cindex @code{-I} (@code{gnathtml}) - Specify a directory to search for library files (@file{.ali} files) and - source files. You can provide several -I switches on the command line, - and the directories will be parsed in the order of the command line. - - @item -o @var{dir} - @cindex @code{-o} (@code{gnathtml}) - Specify the output directory for html files. By default, gnathtml will - saved the generated html files in a subdirectory named @file{html/}. - - @item -p @var{file} - @cindex @code{-p} (@code{gnathtml}) - If you are using Emacs and the most recent Emacs Ada mode, which provides - a full Integrated Development Environment for compiling, checking, - running and debugging applications, you may be using @file{.adp} files - to give the directories where Emacs can find sources and object files. - - Using this switch, you can tell gnathtml to use these files. This allows - you to get an html version of your application, even if it is spread - over multiple directories. - - @item -sc @var{color} - @cindex @code{-sc} (@code{gnathtml}) - This option allows you to change the color used for symbol definitions. - The default value is red. The color argument can be any name accepted by html. - - @item -t @var{file} - @cindex @code{-t} (@code{gnathtml}) - This switch provides the name of a file. This file contains a list of - file names to be converted, and the effect is exactly as though they had - appeared explicitly on the command line. This - is the recommended way to work around the command line length limit on some - systems. - - @end table - - @node Installing gnathtml - @section Installing @code{gnathtml} - - @noindent - @code{Perl} needs to be installed on your machine to run this script. - @code{Perl} is freely available for almost every architecture and - Operating System via the Internet. - - On Unix systems, you may want to modify the first line of the script - @code{gnathtml}, to explicitly tell the Operating system where Perl - is. The syntax of this line is : - @smallexample - #!full_path_name_to_perl - @end smallexample - - @noindent - Alternatively, you may run the script using the following command line: - - @smallexample - $ perl gnathtml.pl [switches] files - @end smallexample - - - @node Running and Debugging Ada Programs - @chapter Running and Debugging Ada Programs - @cindex Debugging - - @noindent - This chapter discusses how to debug Ada programs. An incorrect Ada program - may be handled in three ways by the GNAT compiler: - - @enumerate - @item - The illegality may be a violation of the static semantics of Ada. In - that case GNAT diagnoses the constructs in the program that are illegal. - It is then a straightforward matter for the user to modify those parts of - the program. - - @item - The illegality may be a violation of the dynamic semantics of Ada. In - that case the program compiles and executes, but may generate incorrect - results, or may terminate abnormally with some exception. - - @item - When presented with a program that contains convoluted errors, GNAT - itself may terminate abnormally without providing full diagnostics on - the incorrect user program. - @end enumerate - - @menu - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - @end menu - - @cindex Debugger - @findex gdb - - @node The GNAT Debugger GDB - @section The GNAT Debugger GDB - - @noindent - @code{GDB} is a general purpose, platform-independent debugger that - can be used to debug mixed-language programs compiled with @code{GCC}, - and in particular is capable of debugging Ada programs compiled with - GNAT. The latest versions of @code{GDB} are Ada-aware and can handle - complex Ada data structures. - - The manual @cite{Debugging with GDB} - contains full details on the usage of @code{GDB}, including a section on - its usage on programs. This manual should be consulted for full - details. The section that follows is a brief introduction to the - philosophy and use of @code{GDB}. - - When GNAT programs are compiled, the compiler optionally writes debugging - information into the generated object file, including information on - line numbers, and on declared types and variables. This information is - separate from the generated code. It makes the object files considerably - larger, but it does not add to the size of the actual executable that - will be loaded into memory, and has no impact on run-time performance. The - generation of debug information is triggered by the use of the - -g switch in the gcc or gnatmake command used to carry out - the compilations. It is important to emphasize that the use of these - options does not change the generated code. - - The debugging information is written in standard system formats that - are used by many tools, including debuggers and profilers. The format - of the information is typically designed to describe C types and - semantics, but GNAT implements a translation scheme which allows full - details about Ada types and variables to be encoded into these - standard C formats. Details of this encoding scheme may be found in - the file exp_dbug.ads in the GNAT source distribution. However, the - details of this encoding are, in general, of no interest to a user, - since @code{GDB} automatically performs the necessary decoding. - - When a program is bound and linked, the debugging information is - collected from the object files, and stored in the executable image of - the program. Again, this process significantly increases the size of - the generated executable file, but it does not increase the size of - the executable program itself. Furthermore, if this program is run in - the normal manner, it runs exactly as if the debug information were - not present, and takes no more actual memory. - - However, if the program is run under control of @code{GDB}, the - debugger is activated. The image of the program is loaded, at which - point it is ready to run. If a run command is given, then the program - will run exactly as it would have if @code{GDB} were not present. This - is a crucial part of the @code{GDB} design philosophy. @code{GDB} is - entirely non-intrusive until a breakpoint is encountered. If no - breakpoint is ever hit, the program will run exactly as it would if no - debugger were present. When a breakpoint is hit, @code{GDB} accesses - the debugging information and can respond to user commands to inspect - variables, and more generally to report on the state of execution. - - @node Running GDB - @section Running GDB - - - Please refer to the debugging section of the chapter specific to your - cross environment at the end of this manual. - - @node Introduction to GDB Commands - @section Introduction to GDB Commands - - @noindent - @code{GDB} contains a large repertoire of commands. The manual - @cite{Debugging with GDB} - includes extensive documentation on the use - of these commands, together with examples of their use. Furthermore, - the command @var{help} invoked from within @code{GDB} activates a simple help - facility which summarizes the available commands and their options. - In this section we summarize a few of the most commonly - used commands to give an idea of what @code{GDB} is about. You should create - a simple program with debugging information and experiment with the use of - these @code{GDB} commands on the program as you read through the - following section. - - @table @code - @item set args @var{arguments} - The @var{arguments} list above is a list of arguments to be passed to - the program on a subsequent run command, just as though the arguments - had been entered on a normal invocation of the program. The @code{set args} - command is not needed if the program does not require arguments. - - @item run - The @code{run} command causes execution of the program to start from - the beginning. If the program is already running, that is to say if - you are currently positioned at a breakpoint, then a prompt will ask - for confirmation that you want to abandon the current execution and - restart. - - @item breakpoint @var{location} - The breakpoint command sets a breakpoint, that is to say a point at which - execution will halt and @code{GDB} will await further - commands. @var{location} is - either a line number within a file, given in the format @code{file:linenumber}, - or it is the name of a subprogram. If you request that a breakpoint be set on - a subprogram that is overloaded, a prompt will ask you to specify on which of - those subprograms you want to breakpoint. You can also - specify that all of them should be breakpointed. If the program is run - and execution encounters the breakpoint, then the program - stops and @code{GDB} signals that the breakpoint was encountered by - printing the line of code before which the program is halted. - - @item breakpoint exception @var{name} - A special form of the breakpoint command which breakpoints whenever - exception @var{name} is raised. - If @var{name} is omitted, - then a breakpoint will occur when any exception is raised. - - @item print @var{expression} - This will print the value of the given expression. Most simple - Ada expression formats are properly handled by @code{GDB}, so the expression - can contain function calls, variables, operators, and attribute references. - - @item continue - Continues execution following a breakpoint, until the next breakpoint or the - termination of the program. - - @item step - Executes a single line after a breakpoint. If the next statement is a subprogram - call, execution continues into (the first statement of) the - called subprogram. - - @item next - Executes a single line. If this line is a subprogram call, executes and - returns from the call. - - @item list - Lists a few lines around the current source location. In practice, it - is usually more convenient to have a separate edit window open with the - relevant source file displayed. Successive applications of this command - print subsequent lines. The command can be given an argument which is a - line number, in which case it displays a few lines around the specified one. - - @item backtrace - Displays a backtrace of the call chain. This command is typically - used after a breakpoint has occurred, to examine the sequence of calls that - leads to the current breakpoint. The display includes one line for each - activation record (frame) corresponding to an active subprogram. - - @item up - At a breakpoint, @code{GDB} can display the values of variables local - to the current frame. The command @code{up} can be used to - examine the contents of other active frames, by moving the focus up - the stack, that is to say from callee to caller, one frame at a time. - - @item down - Moves the focus of @code{GDB} down from the frame currently being - examined to the frame of its callee (the reverse of the previous command), - - @item frame @var{n} - Inspect the frame with the given number. The value 0 denotes the frame - of the current breakpoint, that is to say the top of the call stack. - - @end table - - The above list is a very short introduction to the commands that - @code{GDB} provides. Important additional capabilities, including conditional - breakpoints, the ability to execute command sequences on a breakpoint, - the ability to debug at the machine instruction level and many other - features are described in detail in @cite{Debugging with GDB}. - Note that most commands can be abbreviated - (for example, c for continue, bt for backtrace). - - @node Using Ada Expressions - @section Using Ada Expressions - @cindex Ada expressions - - @noindent - @code{GDB} supports a fairly large subset of Ada expression syntax, with some - extensions. The philosophy behind the design of this subset is - - @itemize @bullet - @item - That @code{GDB} should provide basic literals and access to operations for - arithmetic, dereferencing, field selection, indexing, and subprogram calls, - leaving more sophisticated computations to subprograms written into the - program (which therefore may be called from @code{GDB}). - - @item - That type safety and strict adherence to Ada language restrictions - are not particularly important to the @code{GDB} user. - - @item - That brevity is important to the @code{GDB} user. - @end itemize - - Thus, for brevity, the debugger acts as if there were - implicit @code{with} and @code{use} clauses in effect for all user-written - packages, thus making it unnecessary to fully qualify most names with - their packages, regardless of context. Where this causes ambiguity, - @code{GDB} asks the user's intent. - - For details on the supported Ada syntax, see @cite{Debugging with GDB}. - - @node Calling User-Defined Subprograms - @section Calling User-Defined Subprograms - - @noindent - An important capability of @code{GDB} is the ability to call user-defined - subprograms while debugging. This is achieved simply by entering - a subprogram call statement in the form: - - @smallexample - call subprogram-name (parameters) - @end smallexample - - @noindent - The keyword @code{call} can be omitted in the normal case where the - @code{subprogram-name} does not coincide with any of the predefined - @code{GDB} commands. - - The effect is to invoke the given subprogram, passing it the - list of parameters that is supplied. The parameters can be expressions and - can include variables from the program being debugged. The - subprogram must be defined - at the library level within your program, and @code{GDB} will call the - subprogram within the environment of your program execution (which - means that the subprogram is free to access or even modify variables - within your program). - - The most important use of this facility is in allowing the inclusion of - debugging routines that are tailored to particular data structures - in your program. Such debugging routines can be written to provide a suitably - high-level description of an abstract type, rather than a low-level dump - of its physical layout. After all, the standard - @code{GDB print} command only knows the physical layout of your - types, not their abstract meaning. Debugging routines can provide information - at the desired semantic level and are thus enormously useful. - - For example, when debugging GNAT itself, it is crucial to have access to - the contents of the tree nodes used to represent the program internally. - But tree nodes are represented simply by an integer value (which in turn - is an index into a table of nodes). - Using the @code{print} command on a tree node would simply print this integer - value, which is not very useful. But the PN routine (defined in file - treepr.adb in the GNAT sources) takes a tree node as input, and displays - a useful high level representation of the tree node, which includes the - syntactic category of the node, its position in the source, the integers - that denote descendant nodes and parent node, as well as varied - semantic information. To study this example in more detail, you might want to - look at the body of the PN procedure in the stated file. - - @node Using the Next Command in a Function - @section Using the Next Command in a Function - - @noindent - When you use the @code{next} command in a function, the current source - location will advance to the next statement as usual. A special case - arises in the case of a @code{return} statement. - - Part of the code for a return statement is the "epilog" of the function. - This is the code that returns to the caller. There is only one copy of - this epilog code, and it is typically associated with the last return - statement in the function if there is more than one return. In some - implementations, this epilog is associated with the first statement - of the function. - - The result is that if you use the @code{next} command from a return - statement that is not the last return statement of the function you - may see a strange apparent jump to the last return statement or to - the start of the function. You should simply ignore this odd jump. - The value returned is always that from the first return statement - that was stepped through. - - @node Ada Exceptions - @section Breaking on Ada Exceptions - @cindex Exceptions - - @noindent - You can set breakpoints that trip when your program raises - selected exceptions. - - @table @code - @item break exception - Set a breakpoint that trips whenever (any task in the) program raises - any exception. - - @item break exception @var{name} - Set a breakpoint that trips whenever (any task in the) program raises - the exception @var{name}. - - @item break exception unhandled - Set a breakpoint that trips whenever (any task in the) program raises an - exception for which there is no handler. - - @item info exceptions - @itemx info exceptions @var{regexp} - The @code{info exceptions} command permits the user to examine all defined - exceptions within Ada programs. With a regular expression, @var{regexp}, as - argument, prints out only those exceptions whose name matches @var{regexp}. - @end table - - @node Ada Tasks - @section Ada Tasks - @cindex Tasks - - @noindent - @code{GDB} allows the following task-related commands: - - @table @code - @item info tasks - This command shows a list of current Ada tasks, as in the following example: - - @smallexample - @iftex - @leftskip=0cm - @end iftex - (gdb) info tasks - ID TID P-ID Thread Pri State Name - 1 8088000 0 807e000 15 Child Activation Wait main_task - 2 80a4000 1 80ae000 15 Accept/Select Wait b - 3 809a800 1 80a4800 15 Child Activation Wait a - * 4 80ae800 3 80b8000 15 Running c - @end smallexample - - @noindent - In this listing, the asterisk before the first task indicates it to be the - currently running task. The first column lists the task ID that is used - to refer to tasks in the following commands. - - @item break @var{linespec} task @var{taskid} - @itemx break @var{linespec} task @var{taskid} if @dots{} - @cindex Breakpoints and tasks - These commands are like the @code{break @dots{} thread @dots{}}. - @var{linespec} specifies source lines. - - Use the qualifier @samp{task @var{taskid}} with a breakpoint command - to specify that you only want @code{GDB} to stop the program when a - particular Ada task reaches this breakpoint. @var{taskid} is one of the - numeric task identifiers assigned by @code{GDB}, shown in the first - column of the @samp{info tasks} display. - - If you do not specify @samp{task @var{taskid}} when you set a - breakpoint, the breakpoint applies to @emph{all} tasks of your - program. - - You can use the @code{task} qualifier on conditional breakpoints as - well; in this case, place @samp{task @var{taskid}} before the - breakpoint condition (before the @code{if}). - - @item task @var{taskno} - @cindex Task switching - - This command allows to switch to the task referred by @var{taskno}. In - particular, This allows to browse the backtrace of the specified - task. It is advised to switch back to the original task before - continuing execution otherwise the scheduling of the program may be - perturbated. - @end table - - @noindent - For more detailed information on the tasking support, see @cite{Debugging with GDB}. - - @node Debugging Generic Units - @section Debugging Generic Units - @cindex Debugging Generic Units - @cindex Generics - - @noindent - GNAT always uses code expansion for generic instantiation. This means that - each time an instantiation occurs, a complete copy of the original code is - made, with appropriate substitutions of formals by actuals. - - It is not possible to refer to the original generic entities in - @code{GDB}, but it is always possible to debug a particular instance of - a generic, by using the appropriate expanded names. For example, if we have - - @smallexample - @group - @cartouche - @b{procedure} g @b{is} - - @b{generic package} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer); - @b{end} k; - - @b{package body} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer) @b{is} - @b{begin} - v1 := v1 + 1; - @b{end} kp; - @b{end} k; - - @b{package} k1 @b{is new} k; - @b{package} k2 @b{is new} k; - - var : integer := 1; - - @b{begin} - k1.kp (var); - k2.kp (var); - k1.kp (var); - k2.kp (var); - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Then to break on a call to procedure kp in the k2 instance, simply - use the command: - - @smallexample - (gdb) break g.k2.kp - @end smallexample - - @noindent - When the breakpoint occurs, you can step through the code of the - instance in the normal manner and examine the values of local variables, as for - other units. - - @node GNAT Abnormal Termination or Failure to Terminate - @section GNAT Abnormal Termination or Failure to Terminate - @cindex GNAT Abnormal Termination or Failure to Terminate - - @noindent - When presented with programs that contain serious errors in syntax - or semantics, - GNAT may on rare occasions experience problems in operation, such - as aborting with a - segmentation fault or illegal memory access, raising an internal - exception, terminating abnormally, or failing to terminate at all. - In such cases, you can activate - various features of GNAT that can help you pinpoint the construct in your - program that is the likely source of the problem. - - The following strategies are presented in increasing order of - difficulty, corresponding to your experience in using GNAT and your - familiarity with compiler internals. - - @enumerate - @item - Run @code{gcc} with the @option{-gnatf}. This first - switch causes all errors on a given line to be reported. In its absence, - only the first error on a line is displayed. - - The @option{-gnatdO} switch causes errors to be displayed as soon as they - are encountered, rather than after compilation is terminated. If GNAT - terminates prematurely or goes into an infinite loop, the last error - message displayed may help to pinpoint the culprit. - - @item - Run @code{gcc} with the @code{-v (verbose)} switch. In this mode, - @code{gcc} produces ongoing information about the progress of the - compilation and provides the name of each procedure as code is - generated. This switch allows you to find which Ada procedure was being - compiled when it encountered a code generation problem. - - @item - @cindex @option{-gnatdc} switch - Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific - switch that does for the front-end what @code{-v} does for the back end. - The system prints the name of each unit, either a compilation unit or - nested unit, as it is being analyzed. - @item - Finally, you can start - @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the - front-end of GNAT, and can be run independently (normally it is just - called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you - would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The - @code{where} command is the first line of attack; the variable - @code{lineno} (seen by @code{print lineno}), used by the second phase of - @code{gnat1} and by the @code{gcc} backend, indicates the source line at - which the execution stopped, and @code{input_file name} indicates the name of - the source file. - @end enumerate - - @node Naming Conventions for GNAT Source Files - @section Naming Conventions for GNAT Source Files - - @noindent - In order to examine the workings of the GNAT system, the following - brief description of its organization may be helpful: - - @itemize @bullet - @item - Files with prefix @file{sc} contain the lexical scanner. - - @item - All files prefixed with @file{par} are components of the parser. The - numbers correspond to chapters of the Ada 95 Reference Manual. For example, - parsing of select statements can be found in @file{par-ch9.adb}. - - @item - All files prefixed with @file{sem} perform semantic analysis. The - numbers correspond to chapters of the Ada standard. For example, all - issues involving context clauses can be found in @file{sem_ch10.adb}. In - addition, some features of the language require sufficient special processing - to justify their own semantic files: sem_aggr for aggregates, sem_disp for - dynamic dispatching, etc. - - @item - All files prefixed with @file{exp} perform normalization and - expansion of the intermediate representation (abstract syntax tree, or AST). - these files use the same numbering scheme as the parser and semantics files. - For example, the construction of record initialization procedures is done in - @file{exp_ch3.adb}. - - @item - The files prefixed with @file{bind} implement the binder, which - verifies the consistency of the compilation, determines an order of - elaboration, and generates the bind file. - - @item - The files @file{atree.ads} and @file{atree.adb} detail the low-level - data structures used by the front-end. - - @item - The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of - the abstract syntax tree as produced by the parser. - - @item - The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of - all entities, computed during semantic analysis. - - @item - Library management issues are dealt with in files with prefix - @file{lib}. - - @item - @findex Ada - @cindex Annex A - Ada files with the prefix @file{a-} are children of @code{Ada}, as - defined in Annex A. - - @item - @findex Interfaces - @cindex Annex B - Files with prefix @file{i-} are children of @code{Interfaces}, as - defined in Annex B. - - @item - @findex System - Files with prefix @file{s-} are children of @code{System}. This includes - both language-defined children and GNAT run-time routines. - - @item - @findex GNAT - Files with prefix @file{g-} are children of @code{GNAT}. These are useful - general-purpose packages, fully documented in their specifications. All - the other @file{.c} files are modifications of common @code{gcc} files. - @end itemize - - @node Getting Internal Debugging Information - @section Getting Internal Debugging Information - - @noindent - Most compilers have internal debugging switches and modes. GNAT - does also, except GNAT internal debugging switches and modes are not - secret. A summary and full description of all the compiler and binder - debug flags are in the file @file{debug.adb}. You must obtain the - sources of the compiler to see the full detailed effects of these flags. - - The switches that print the source of the program (reconstructed from - the internal tree) are of general interest for user programs, as are the - options to print - the full internal tree, and the entity table (the symbol table - information). The reconstructed source provides a readable version of the - program after the front-end has completed analysis and expansion, and is useful - when studying the performance of specific constructs. For example, constraint - checks are indicated, complex aggregates are replaced with loops and - assignments, and tasking primitives are replaced with run-time calls. - - @node Stack Traceback - @section Stack Traceback - @cindex traceback - @cindex stack traceback - @cindex stack unwinding - - @noindent - Traceback is a mechanism to display the sequence of subprogram calls that - leads to a specified execution point in a program. Often (but not always) - the execution point is an instruction at which an exception has been raised. - This mechanism is also known as @i{stack unwinding} because it obtains - its information by scanning the run-time stack and recovering the activation - records of all active subprograms. Stack unwinding is one of the most - important tools for program debugging. - - @noindent - The first entry stored in traceback corresponds to the deepest calling level, - that is to say the subprogram currently executing the instruction - from which we want to obtain the traceback. - - @noindent - Note that there is no runtime performance penalty when stack traceback - is enabled and no exception are raised during program execution. - - @menu - * Non-Symbolic Traceback:: - * Symbolic Traceback:: - @end menu - - @node Non-Symbolic Traceback - @subsection Non-Symbolic Traceback - @cindex traceback, non-symbolic - - @noindent - Note: this feature is not supported on all platforms. See - @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported - platforms. - - @menu - * Tracebacks From an Unhandled Exception:: - * Tracebacks From Exception Occurrences (non-symbolic):: - * Tracebacks From Anywhere in a Program (non-symbolic):: - @end menu - - @node Tracebacks From an Unhandled Exception - @subsubsection Tracebacks From an Unhandled Exception - - @noindent - A runtime non-symbolic traceback is a list of addresses of call instructions. - To enable this feature you must use the @code{-E} - @code{gnatbind}'s option. With this option a stack traceback is stored as part - of exception information. It is possible to retrieve this information using the - standard @code{Ada.Exception.Exception_Information} routine. - - @noindent - Let's have a look at a simple example: - - @smallexample - @cartouche - @group - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @noindent - As we see the traceback lists a sequence of addresses for the unhandled - exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to - guess that this exception come from procedure P1. To translate these - addresses into the source lines where the calls appear, the - @code{addr2line} tool, described below, is invaluable. The use of this tool - requires the program to be compiled with debug information. - - @smallexample - $ gnatmake -g stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - - $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 - 0x4011f1 0x77e892a4 - - 00401373 at d:/stb/stb.adb:5 - 0040138B at d:/stb/stb.adb:10 - 0040139C at d:/stb/stb.adb:14 - 00401335 at d:/stb/b~stb.adb:104 - 004011C4 at /build/.../crt1.c:200 - 004011F1 at /build/.../crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - @code{addr2line} has a number of other useful options: - - @table @code - @item --functions - to get the function name corresponding to any location - - @item --demangle=gnat - to use the @b{gnat} decoding mode for the function names. Note that - for binutils version 2.9.x the option is simply @code{--demangle}. - @end table - - @smallexample - $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b - 0x40139c 0x401335 0x4011c4 0x4011f1 - - 00401373 in stb.p1 at d:/stb/stb.adb:5 - 0040138B in stb.p2 at d:/stb/stb.adb:10 - 0040139C in stb at d:/stb/stb.adb:14 - 00401335 in main at d:/stb/b~stb.adb:104 - 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200 - 004011F1 in at /build/.../crt1.c:222 - @end smallexample - - @noindent - From this traceback we can see that the exception was raised in - @file{stb.adb} at line 5, which was reached from a procedure call in - @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file, - which contains the call to the main program. - @pxref{Running gnatbind}. The remaining entries are assorted runtime routines, - and the output will vary from platform to platform. - - @noindent - It is also possible to use @code{GDB} with these traceback addresses to debug - the program. For example, we can break at a given code location, as reported - in the stack traceback: - - @smallexample - $ gdb -nw stb - - (gdb) break *0x401373 - Breakpoint 1 at 0x401373: file stb.adb, line 5. - @end smallexample - - @noindent - It is important to note that the stack traceback addresses - do not change when debug information is included. This is particularly useful - because it makes it possible to release software without debug information (to - minimize object size), get a field report that includes a stack traceback - whenever an internal bug occurs, and then be able to retrieve the sequence - of calls with the same program compiled with debug information. - - @node Tracebacks From Exception Occurrences (non-symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @noindent - Non-symbolic tracebacks are obtained by using the @code{-E} binder argument. - The stack traceback is attached to the exception information string, and can - be retrieved in an exception handler within the Ada program, by means of the - Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with Ada.Exceptions; - - procedure STB is - - use Ada; - use Ada.Exceptions; - - procedure P1 is - K : Positive := 1; - begin - K := K - 1; - exception - when E : others => - Text_IO.Put_Line (Exception_Information (E)); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @noindent - This program will output: - - @smallexample - $ stb - - Exception name: CONSTRAINT_ERROR - Message: stb.adb:12 - Call stack traceback locations: - 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @node Tracebacks From Anywhere in a Program (non-symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is also possible to retrieve a stack traceback from anywhere in a - program. For this you need to - use the @code{GNAT.Traceback} API. This package includes a procedure called - @code{Call_Chain} that computes a complete stack traceback, as well as useful - display procedures described below. It is not necessary to use the - @code{-E gnatbind} option in this case, because the stack traceback mechanism - is invoked explicitly. - - @noindent - In the following example we compute a traceback at a specific location in - the program, and we display it using @code{GNAT.Debug_Utilities.Image} to - convert addresses to strings: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Debug_Utilities; - - procedure STB is - - use Ada; - use GNAT; - use GNAT.Traceback; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - - Text_IO.Put ("In STB.P1 : "); - - for K in 1 .. Len loop - Text_IO.Put (Debug_Utilities.Image (TB (K))); - Text_IO.Put (' '); - end loop; - - Text_IO.New_Line; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb - $ stb - - In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# - 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# - @end smallexample - - @node Symbolic Traceback - @subsection Symbolic Traceback - @cindex traceback, symbolic - - @noindent - A symbolic traceback is a stack traceback in which procedure names are - associated with each code location. - - @noindent - Note that this feature is not supported on all platforms. See - @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete - list of currently supported platforms. - - @noindent - Note that the symbolic traceback requires that the program be compiled - with debug information. If it is not compiled with debug information - only the non-symbolic information will be valid. - - @menu - * Tracebacks From Exception Occurrences (symbolic):: - * Tracebacks From Anywhere in a Program (symbolic):: - @end menu - - @node Tracebacks From Exception Occurrences (symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback.Symbolic; - - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - procedure P3 is - begin - P2; - end P3; - - begin - P3; - exception - when E : others => - Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl - $ stb - - 0040149F in stb.p1 at stb.adb:8 - 004014B7 in stb.p2 at stb.adb:13 - 004014CF in stb.p3 at stb.adb:18 - 004015DD in ada.stb at stb.adb:22 - 00401461 in main at b~stb.adb:168 - 004011C4 in __mingw_CRTStartup at crt1.c:200 - 004011F1 in mainCRTStartup at crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - The exact sequence of linker options may vary from platform to platform. - The above @code{-largs} section is for Windows platforms. By contrast, - under Unix there is no need for the @code{-largs} section. - Differences across platforms are due to details of linker implementation. - - @node Tracebacks From Anywhere in a Program (symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is possible to get a symbolic stack traceback - from anywhere in a program, just as for non-symbolic tracebacks. - The first step is to obtain a non-symbolic - traceback, and then call @code{Symbolic_Traceback} to compute the symbolic - information. Here is an example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Traceback.Symbolic; - - procedure STB is - - use Ada; - use GNAT.Traceback; - use GNAT.Traceback.Symbolic; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - - @node Inline Assembler - @chapter Inline Assembler - - @noindent - If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program. First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT. However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler. The Inline Assembler approach offers a number of advantages, including the following: - - @itemize @bullet - @item No need to use non-Ada tools - @item Consistent interface over different targets - @item Automatic usage of the proper calling conventions - @item Access to Ada constants and variables - @item Definition of intrinsic routines - @item Possibility of inlining a subprogram comprising assembler code - @item Code optimizer can take Inline Assembler code into account - @end itemize - - This chapter presents a series of examples to show you how to use the Inline Assembler. Although it focuses on the Intel x86, the general approach applies also to other processors. It is assumed that you are familiar with Ada and with assembly language programming. - - @menu - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - @end menu - - @c --------------------------------------------------------------------------- - @node Basic Assembler Syntax - @section Basic Assembler Syntax - - @noindent - The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a - language that descends from the AT&T Unix assembler @emph{as} (and which is often - referred to as ``AT&T syntax''). - The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions. - See the gcc @emph{as} and @emph{gas} (an @emph{as} macro - pre-processor) documentation for further information. - - @table @asis - @item Register names - gcc / @emph{as}: Prefix with ``%''; for example @code{%eax} - @* - Intel: No extra punctuation; for example @code{eax} - - @item Immediate operand - gcc / @emph{as}: Prefix with ``$''; for example @code{$4} - @* - Intel: No extra punctuation; for example @code{4} - - @item Address - gcc / @emph{as}: Prefix with ``$''; for example @code{$loc} - @* - Intel: No extra punctuation; for example @code{loc} - - @item Memory contents - gcc / @emph{as}: No extra punctuation; for example @code{loc} - @* - Intel: Square brackets; for example @code{[loc]} - - @item Register contents - gcc / @emph{as}: Parentheses; for example @code{(%eax)} - @* - Intel: Square brackets; for example @code{[eax]} - - @item Hexadecimal numbers - gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} - @* - Intel: Trailing ``h''; for example @code{A0h} - - @item Operand size - gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word - @* - Intel: Implicit, deduced by assembler; for example @code{mov} - - @item Instruction repetition - gcc / @emph{as}: Split into two lines; for example - @* - @code{rep} - @* - @code{stosl} - @* - Intel: Keep on one line; for example @code{rep stosl} - - @item Order of operands - gcc / @emph{as}: Source first; for example @code{movw $4, %eax} - @* - Intel: Destination first; for example @code{mov eax, 4} - @end table - - @c --------------------------------------------------------------------------- - @node A Simple Example of Inline Assembler - @section A Simple Example of Inline Assembler - - @noindent - The following example will generate a single assembly language statement, @code{nop}, which does nothing. Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility. - - @smallexample - @group - with System.Machine_Code; use System.Machine_Code; - procedure Nothing is - begin - Asm ("nop"); - end Nothing; - @end group - @end smallexample - - @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction. - @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions. - - The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}. - - Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}. You can build the executable in the usual way: - @smallexample - gnatmake nothing - @end smallexample - However, the interesting aspect of this example is not its run-time behavior but rather the - generated assembly code. To see this output, invoke the compiler as follows: - @smallexample - gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb} - @end smallexample - where the options are: - - @table @code - @item -c - compile only (no bind or link) - @item -S - generate assembler listing - @item -fomit-frame-pointer - do not set up separate stack frames - @item -gnatp - do not add runtime checks - @end table - - This gives a human-readable assembler version of the code. The resulting - file will have the same name as the Ada source file, but with a @code{.s} extension. - In our example, the file @file{nothing.s} has the following contents: - - @smallexample - @group - .file "nothing.adb" - gcc2_compiled.: - ___gnu_compiled_ada: - .text - .align 4 - .globl __ada_nothing - __ada_nothing: - #APP - nop - #NO_APP - jmp L1 - .align 2,0x90 - L1: - ret - @end group - @end smallexample - - The assembly code you included is clearly indicated by - the compiler, between the @code{#APP} and @code{#NO_APP} - delimiters. The character before the 'APP' and 'NOAPP' - can differ on different targets. For example, Linux uses '#APP' while - on NT you will see '/APP'. - - If you make a mistake in your assembler code (such as using the - wrong size modifier, or using a wrong operand for the instruction) GNAT - will report this error in a temporary file, which will be deleted when - the compilation is finished. Generating an assembler file will help - in such cases, since you can assemble this file separately using the - @emph{as} assembler that comes with gcc. - - Assembling the file using the command - - @smallexample - as @file{nothing.s} - @end smallexample - @noindent - will give you error messages whose lines correspond to the assembler - input file, so you can easily find and correct any mistakes you made. - If there are no errors, @emph{as} will generate an object file @file{nothing.out}. - - @c --------------------------------------------------------------------------- - @node Output Variables in Inline Assembler - @section Output Variables in Inline Assembler - - @noindent - The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements. - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags; - @end group - @end smallexample - - In order to have a nicely aligned assembly listing, we have separated - multiple assembler statements in the Asm template string with linefeed (ASCII.LF) - and horizontal tab (ASCII.HT) characters. The resulting section of the - assembly output file is: - - @smallexample - @group - #APP - pushfl - popl %eax - movl %eax, -40(%ebp) - #NO_APP - @end group - @end smallexample - - It would have been legal to write the Asm invocation as: - - @smallexample - Asm ("pushfl popl %%eax movl %%eax, %0") - @end smallexample - - but in the generated assembler file, this would come out as: - - @smallexample - #APP - pushfl popl %eax movl %eax, -40(%ebp) - #NO_APP - @end smallexample - - which is not so convenient for the human reader. - - We use Ada comments - at the end of each line to explain what the assembler instructions - actually do. This is a useful convention. - - When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign. Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}. In the generated assembly code, one of the percent signs will be stripped off. - - Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}. - An output variable is illustrated in - the third statement in the Asm template string: - @smallexample - movl %%eax, %0 - @end smallexample - The intent is to store the contents of the eax register in a variable that can be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization. The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable. - - Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}: - @smallexample - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end smallexample - - The output is defined by the @code{Asm_Output} attribute of the target type; the general format is - @smallexample - Type'Asm_Output (constraint_string, variable_name) - @end smallexample - - The constraint string directs the compiler how - to store/access the associated variable. In the example - @smallexample - Unsigned_32'Asm_Output ("=m", Flags); - @end smallexample - the @code{"m"} (memory) constraint tells the compiler that the variable - @code{Flags} should be stored in a memory variable, thus preventing - the optimizer from keeping it in a register. In contrast, - @smallexample - Unsigned_32'Asm_Output ("=r", Flags); - @end smallexample - uses the @code{"r"} (register) constraint, telling the compiler to - store the variable in a register. - - If the constraint is preceded by the equal character (@strong{=}), it tells the - compiler that the variable will be used to store data into it. - - In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer - to choose whatever it deems best. - - There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following: - - @table @code - @item = - output constraint - @item g - global (i.e. can be stored anywhere) - @item m - in memory - @item I - a constant - @item a - use eax - @item b - use ebx - @item c - use ecx - @item d - use edx - @item S - use esi - @item D - use edi - @item r - use one of eax, ebx, ecx or edx - @item q - use one of eax, ebx, ecx, edx, esi or edi - @end table - - The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string. - - You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer. Thus in - @smallexample - @group - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end group - @end smallexample - @noindent - @code{%0} will be replaced in the expanded code by the appropriate operand, - whatever - the compiler decided for the @code{Flags} variable. - - In general, you may have any number of output variables: - @itemize @bullet - @item - Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. - @item - Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes - @end itemize - - For example: - @smallexample - @group - Asm ("movl %%eax, %0" & LF & HT & - "movl %%ebx, %1" & LF & HT & - "movl %%ecx, %2", - Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A - Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B - Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C - @end group - @end smallexample - @noindent - where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program. - - As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_2 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax", -- save flags in eax - Outputs => Unsigned_32'Asm_Output ("=a", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_2; - @end group - @end smallexample - - @noindent - The @code{"a"} constraint tells the compiler that the @code{Flags} - variable will come from the eax register. Here is the resulting code: - - @smallexample - @group - #APP - pushfl - popl %eax - #NO_APP - movl %eax,-40(%ebp) - @end group - @end smallexample - - @noindent - The compiler generated the store of eax into Flags after - expanding the assembler code. - - Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_3 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "pop %0", -- save flags in Flags - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_3; - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Input Variables in Inline Assembler - @section Input Variables in Inline Assembler - - @noindent - The example in this section illustrates how to specify the source operands for assembly language statements. The program simply increments its input value by 1: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Incr (Value); - Put_Line ("Value after is" & Value'Img); - end Increment; - @end group - @end smallexample - - The @code{Outputs} parameter to @code{Asm} specifies - that the result will be in the eax register and that it is to be stored in the @code{Result} - variable. - - The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an - @code{Asm_Input} attribute. The - @code{"="} constraint, indicating an output value, is not present. - - You can have multiple input variables, in the same way that you can have more - than one output variable. - - The parameter count (%0, %1) etc, now starts at the first input - statement, and continues with the output statements. - When both parameters use the same variable, the - compiler will treat them as the same %n operand, which is the case here. - - Just as the @code{Outputs} parameter causes the register to be stored into the - target variable after execution of the assembler statements, so does the - @code{Inputs} parameter cause its variable to be loaded into the register before execution - of the - assembler statements. - - Thus the effect of the @code{Asm} invocation is: - @enumerate - @item load the 32-bit value of @code{Value} into eax - @item execute the @code{incl %eax} instruction - @item store the contents of eax into the @code{Result} variable - @end enumerate - - The resulting assembler file (with @code{-O2} optimization) contains: - @smallexample - @group - _increment__incr.1: - subl $4,%esp - movl 8(%esp),%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - movl %ecx,(%esp) - addl $4,%esp - ret - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Inlining Inline Assembler Code - @section Inlining Inline Assembler Code - - @noindent - For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame) - can be significant, compared to the amount of code in the subprogram body. - A solution is to apply Ada's @code{Inline} pragma to the subprogram, - which directs the compiler to expand invocations of the subprogram at the point(s) - of call, instead of setting up a stack frame for out-of-line calls. - Here is the resulting program: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment_2 is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - pragma Inline (Increment); - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Increment (Value); - Put_Line ("Value after is" & Value'Img); - end Increment_2; - @end group - @end smallexample - - Compile the program with both optimization (@code{-O2}) and inlining - enabled (@option{-gnatpn} instead of @option{-gnatp}). - - The @code{Incr} function is still compiled as usual, but at the - point in @code{Increment} where our function used to be called: - - @smallexample - @group - pushl %edi - call _increment__incr.1 - @end group - @end smallexample - - @noindent - the code for the function body directly appears: - - @smallexample - @group - movl %esi,%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - @end group - @end smallexample - - @noindent - thus saving the overhead of stack frame setup and an out-of-line call. - - @c --------------------------------------------------------------------------- - @node Other Asm Functionality - @section Other @code{Asm} Functionality - - @noindent - This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations. - - @menu - * The Clobber Parameter:: - * The Volatile Parameter:: - @end menu - - @c --------------------------------------------------------------------------- - @node The Clobber Parameter - @subsection The @code{Clobber} Parameter - - @noindent - One of the dangers of intermixing assembly language and a compiled language such as Ada is - that the compiler needs to be aware of which registers are being used by the assembly code. - In some cases, such as the earlier examples, the constraint string is sufficient to - indicate register usage (e.g. "a" for the eax register). But more generally, the - compiler needs an explicit identification of the registers that are used by the Inline - Assembly statements. - - Using a register that the compiler doesn't know about - could be a side effect of an instruction (like @code{mull} - storing its result in both eax and edx). - It can also arise from explicit register usage in your - assembly code; for example: - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out)); - @end group - @end smallexample - @noindent - where the compiler (since it does not analyze the @code{Asm} template string) - does not know you are using the ebx register. - - In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, - to identify the registers that will be used by your assembly code: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx"); - @end group - @end smallexample - - The Clobber parameter is a static string expression specifying the - register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign. - Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"} - - The @code{Clobber} parameter has several additional uses: - @enumerate - @item Use the "register" name @code{cc} to indicate that flags might have changed - @item Use the "register" name @code{memory} if you changed a memory location - @end enumerate - - @c --------------------------------------------------------------------------- - @node The Volatile Parameter - @subsection The @code{Volatile} Parameter - @cindex Volatile parameter - - @noindent - Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects. - For example, when - an @code{Asm} invocation with an input variable is inside a loop, the compiler might move - the loading of the input variable outside the loop, regarding it as a - one-time initialization. - - If this effect is not desired, you can disable such optimizations by setting the - @code{Volatile} parameter to @code{True}; for example: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx", - Volatile => True); - @end group - @end smallexample - - By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs} - parameter. - - Although setting @code{Volatile} to @code{True} prevents unwanted optimizations, - it will also disable other optimizations that might be important for efficiency. - In general, you should set @code{Volatile} to @code{True} only if the compiler's - optimizations have created problems. - - @c --------------------------------------------------------------------------- - @node A Complete Example - @section A Complete Example - - @noindent - This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler - capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}. - The package declares a collection of functions that detect the properties of the 32-bit - x86 processor that is running the program. The main procedure invokes these functions - and displays the information. - - The Intel_CPU package could be enhanced by adding functions to - detect the type of x386 co-processor, the processor caching options and - special operations such as the SIMD extensions. - - Although the Intel_CPU package has been written for 32-bit Intel - compatible CPUs, it is OS neutral. It has been tested on DOS, - Windows/NT and Linux. - - @menu - * Check_CPU Procedure:: - * Intel_CPU Package Specification:: - * Intel_CPU Package Body:: - @end menu - - @c --------------------------------------------------------------------------- - @node Check_CPU Procedure - @subsection @code{Check_CPU} Procedure - @cindex Check_CPU procedure - - @smallexample - --------------------------------------------------------------------- - -- -- - -- Uses the Intel_CPU package to identify the CPU the program is -- - -- running on, and some of the features it supports. -- - -- -- - --------------------------------------------------------------------- - - with Intel_CPU; -- Intel CPU detection functions - with Ada.Text_IO; -- Standard text I/O - with Ada.Command_Line; -- To set the exit status - - procedure Check_CPU is - - Type_Found : Boolean := False; - -- Flag to indicate that processor was identified - - Features : Intel_CPU.Processor_Features; - -- The processor features - - Signature : Intel_CPU.Processor_Signature; - -- The processor type signature - - begin - - ----------------------------------- - -- Display the program banner. -- - ----------------------------------- - - Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name & - ": check Intel CPU version and features, v1.0"); - Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever"); - Ada.Text_IO.New_Line; - - ----------------------------------------------------------------------- - -- We can safely start with the assumption that we are on at least -- - -- a x386 processor. If the CPUID instruction is present, then we -- - -- have a later processor type. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Has_CPUID = False then - - -- No CPUID instruction, so we assume this is indeed a x386 - -- processor. We can still check if it has a FP co-processor. - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line - ("x386-type processor with a FP co-processor"); - else - Ada.Text_IO.Put_Line - ("x386-type processor without a FP co-processor"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check for CPUID - - ----------------------------------------------------------------------- - -- If CPUID is supported, check if this is a true Intel processor, -- - -- if it is not, display a warning. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then - Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor"); - Ada.Text_IO.Put_Line ("*** Some information may be incorrect"); - end if; -- check if Intel - - ---------------------------------------------------------------------- - -- With the CPUID instruction present, we can assume at least a -- - -- x486 processor. If the CPUID support level is < 1 then we have -- - -- to leave it at that. -- - ---------------------------------------------------------------------- - - if Intel_CPU.CPUID_Level < 1 then - - -- Ok, this is a x486 processor. we still can get the Vendor ID - Ada.Text_IO.Put_Line ("x486-type processor"); - Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID); - - -- We can also check if there is a FPU present - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line ("Floating-Point support"); - else - Ada.Text_IO.Put_Line ("No Floating-Point support"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check CPUID level - - --------------------------------------------------------------------- - -- With a CPUID level of 1 we can use the processor signature to -- - -- determine it's exact type. -- - --------------------------------------------------------------------- - - Signature := Intel_CPU.Signature; - - ---------------------------------------------------------------------- - -- Ok, now we go into a lot of messy comparisons to get the -- - -- processor type. For clarity, no attememt to try to optimize the -- - -- comparisons has been made. Note that since Intel_CPU does not -- - -- support getting cache info, we cannot distinguish between P5 -- - -- and Celeron types yet. -- - ---------------------------------------------------------------------- - - -- x486SL - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486SL processor"); - end if; - - -- x486DX2 Write-Back - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0111# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor"); - end if; - - -- x486DX4 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 processor"); - end if; - - -- x486DX4 Overdrive - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor"); - end if; - - -- Pentium (60, 66) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium processor (60, 66)"); - end if; - - -- Pentium (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive (60, 66) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)"); - end if; - - -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive processor for x486 processor-based systems - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor for x486 processor-based systems"); - end if; - - -- Pentium processor with MMX technology (166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor with MMX technology (166, 200)"); - end if; - - -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor with MMX " & - "technology for Pentium processor (75, 90, 100, 120, 133)"); - end if; - - -- Pentium Pro processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro processor"); - end if; - - -- Pentium II processor, model 3 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium II processor, model 3"); - end if; - - -- Pentium II processor, model 5 or Celeron processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0101# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium II processor, model 5 or Celeron processor"); - end if; - - -- Pentium Pro OverDrive processor - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor"); - end if; - - -- If no type recognized, we have an unknown. Display what - -- we _do_ know - if Type_Found = False then - Ada.Text_IO.Put_Line ("Unknown processor"); - end if; - - ----------------------------------------- - -- Display processor stepping level. -- - ----------------------------------------- - - Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img); - - --------------------------------- - -- Display vendor ID string. -- - --------------------------------- - - Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID); - - ------------------------------------ - -- Get the processors features. -- - ------------------------------------ - - Features := Intel_CPU.Features; - - ----------------------------- - -- Check for a FPU unit. -- - ----------------------------- - - if Features.FPU = True then - Ada.Text_IO.Put_Line ("Floating-Point unit available"); - else - Ada.Text_IO.Put_Line ("no Floating-Point unit"); - end if; -- check for FPU - - -------------------------------- - -- List processor features. -- - -------------------------------- - - Ada.Text_IO.Put_Line ("Supported features: "); - - -- Virtual Mode Extension - if Features.VME = True then - Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension"); - end if; - - -- Debugging Extension - if Features.DE = True then - Ada.Text_IO.Put_Line (" DE - Debugging Extension"); - end if; - - -- Page Size Extension - if Features.PSE = True then - Ada.Text_IO.Put_Line (" PSE - Page Size Extension"); - end if; - - -- Time Stamp Counter - if Features.TSC = True then - Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter"); - end if; - - -- Model Specific Registers - if Features.MSR = True then - Ada.Text_IO.Put_Line (" MSR - Model Specific Registers"); - end if; - - -- Physical Address Extension - if Features.PAE = True then - Ada.Text_IO.Put_Line (" PAE - Physical Address Extension"); - end if; - - -- Machine Check Extension - if Features.MCE = True then - Ada.Text_IO.Put_Line (" MCE - Machine Check Extension"); - end if; - - -- CMPXCHG8 instruction supported - if Features.CX8 = True then - Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction"); - end if; - - -- on-chip APIC hardware support - if Features.APIC = True then - Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support"); - end if; - - -- Fast System Call - if Features.SEP = True then - Ada.Text_IO.Put_Line (" SEP - Fast System Call"); - end if; - - -- Memory Type Range Registers - if Features.MTRR = True then - Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers"); - end if; - - -- Page Global Enable - if Features.PGE = True then - Ada.Text_IO.Put_Line (" PGE - Page Global Enable"); - end if; - - -- Machine Check Architecture - if Features.MCA = True then - Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture"); - end if; - - -- Conditional Move Instruction Supported - if Features.CMOV = True then - Ada.Text_IO.Put_Line - (" CMOV - Conditional Move Instruction Supported"); - end if; - - -- Page Attribute Table - if Features.PAT = True then - Ada.Text_IO.Put_Line (" PAT - Page Attribute Table"); - end if; - - -- 36-bit Page Size Extension - if Features.PSE_36 = True then - Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension"); - end if; - - -- MMX technology supported - if Features.MMX = True then - Ada.Text_IO.Put_Line (" MMX - MMX technology supported"); - end if; - - -- Fast FP Save and Restore - if Features.FXSR = True then - Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore"); - end if; - - --------------------- - -- Program done. -- - --------------------- - - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - - exception - - when others => - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); - raise; - - end Check_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Specification - @subsection @code{Intel_CPU} Package Specification - @cindex Intel_CPU package specification - - @smallexample - ------------------------------------------------------------------------- - -- -- - -- file: intel_cpu.ads -- - -- -- - -- ********************************************* -- - -- * WARNING: for 32-bit Intel processors only * -- - -- ********************************************* -- - -- -- - -- This package contains a number of subprograms that are useful in -- - -- determining the Intel x86 CPU (and the features it supports) on -- - -- which the program is running. -- - -- -- - -- The package is based upon the information given in the Intel -- - -- Application Note AP-485: "Intel Processor Identification and the -- - -- CPUID Instruction" as of April 1998. This application note can be -- - -- found on www.intel.com. -- - -- -- - -- It currently deals with 32-bit processors only, will not detect -- - -- features added after april 1998, and does not guarantee proper -- - -- results on Intel-compatible processors. -- - -- -- - -- Cache info and x386 fpu type detection are not supported. -- - -- -- - -- This package does not use any privileged instructions, so should -- - -- work on any OS running on a 32-bit Intel processor. -- - -- -- - ------------------------------------------------------------------------- - - with Interfaces; use Interfaces; - -- for using unsigned types - - with System.Machine_Code; use System.Machine_Code; - -- for using inline assembler code - - with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; - -- for inserting control characters - - package Intel_CPU is - - ---------------------- - -- Processor bits -- - ---------------------- - - subtype Num_Bits is Natural range 0 .. 31; - -- the number of processor bits (32) - - -------------------------- - -- Processor register -- - -------------------------- - - -- define a processor register type for easy access to - -- the individual bits - - type Processor_Register is array (Num_Bits) of Boolean; - pragma Pack (Processor_Register); - for Processor_Register'Size use 32; - - ------------------------- - -- Unsigned register -- - ------------------------- - - -- define a processor register type for easy access to - -- the individual bytes - - type Unsigned_Register is - record - L1 : Unsigned_8; - H1 : Unsigned_8; - L2 : Unsigned_8; - H2 : Unsigned_8; - end record; - - for Unsigned_Register use - record - L1 at 0 range 0 .. 7; - H1 at 0 range 8 .. 15; - L2 at 0 range 16 .. 23; - H2 at 0 range 24 .. 31; - end record; - - for Unsigned_Register'Size use 32; - - --------------------------------- - -- Intel processor vendor ID -- - --------------------------------- - - Intel_Processor : constant String (1 .. 12) := "GenuineIntel"; - -- indicates an Intel manufactured processor - - ------------------------------------ - -- Processor signature register -- - ------------------------------------ - - -- a register type to hold the processor signature - - type Processor_Signature is - record - Stepping : Natural range 0 .. 15; - Model : Natural range 0 .. 15; - Family : Natural range 0 .. 15; - Processor_Type : Natural range 0 .. 3; - Reserved : Natural range 0 .. 262143; - end record; - - for Processor_Signature use - record - Stepping at 0 range 0 .. 3; - Model at 0 range 4 .. 7; - Family at 0 range 8 .. 11; - Processor_Type at 0 range 12 .. 13; - Reserved at 0 range 14 .. 31; - end record; - - for Processor_Signature'Size use 32; - - ----------------------------------- - -- Processor features register -- - ----------------------------------- - - -- a processor register to hold the processor feature flags - - type Processor_Features is - record - FPU : Boolean; -- floating point unit on chip - VME : Boolean; -- virtual mode extension - DE : Boolean; -- debugging extension - PSE : Boolean; -- page size extension - TSC : Boolean; -- time stamp counter - MSR : Boolean; -- model specific registers - PAE : Boolean; -- physical address extension - MCE : Boolean; -- machine check extension - CX8 : Boolean; -- cmpxchg8 instruction - APIC : Boolean; -- on-chip apic hardware - Res_1 : Boolean; -- reserved for extensions - SEP : Boolean; -- fast system call - MTRR : Boolean; -- memory type range registers - PGE : Boolean; -- page global enable - MCA : Boolean; -- machine check architecture - CMOV : Boolean; -- conditional move supported - PAT : Boolean; -- page attribute table - PSE_36 : Boolean; -- 36-bit page size extension - Res_2 : Natural range 0 .. 31; -- reserved for extensions - MMX : Boolean; -- MMX technology supported - FXSR : Boolean; -- fast FP save and restore - Res_3 : Natural range 0 .. 127; -- reserved for extensions - end record; - - for Processor_Features use - record - FPU at 0 range 0 .. 0; - VME at 0 range 1 .. 1; - DE at 0 range 2 .. 2; - PSE at 0 range 3 .. 3; - TSC at 0 range 4 .. 4; - MSR at 0 range 5 .. 5; - PAE at 0 range 6 .. 6; - MCE at 0 range 7 .. 7; - CX8 at 0 range 8 .. 8; - APIC at 0 range 9 .. 9; - Res_1 at 0 range 10 .. 10; - SEP at 0 range 11 .. 11; - MTRR at 0 range 12 .. 12; - PGE at 0 range 13 .. 13; - MCA at 0 range 14 .. 14; - CMOV at 0 range 15 .. 15; - PAT at 0 range 16 .. 16; - PSE_36 at 0 range 17 .. 17; - Res_2 at 0 range 18 .. 22; - MMX at 0 range 23 .. 23; - FXSR at 0 range 24 .. 24; - Res_3 at 0 range 25 .. 31; - end record; - - for Processor_Features'Size use 32; - - ------------------- - -- Subprograms -- - ------------------- - - function Has_FPU return Boolean; - -- return True if a FPU is found - -- use only if CPUID is not supported - - function Has_CPUID return Boolean; - -- return True if the processor supports the CPUID instruction - - function CPUID_Level return Natural; - -- return the CPUID support level (0, 1 or 2) - -- can only be called if the CPUID instruction is supported - - function Vendor_ID return String; - -- return the processor vendor identification string - -- can only be called if the CPUID instruction is supported - - function Signature return Processor_Signature; - -- return the processor signature - -- can only be called if the CPUID instruction is supported - - function Features return Processor_Features; - -- return the processors features - -- can only be called if the CPUID instruction is supported - - private - - ------------------------ - -- EFLAGS bit names -- - ------------------------ - - ID_Flag : constant Num_Bits := 21; - -- ID flag bit - - end Intel_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Body - @subsection @code{Intel_CPU} Package Body - @cindex Intel_CPU package body - - @smallexample - package body Intel_CPU is - - --------------------------- - -- Detect FPU presence -- - --------------------------- - - -- There is a FPU present if we can set values to the FPU Status - -- and Control Words. - - function Has_FPU return Boolean is - - Register : Unsigned_16; - -- processor register to store a word - - begin - - -- check if we can change the status word - Asm ( - - -- the assembler code - "finit" & LF & HT & -- reset status word - "movw $0x5A5A, %%ax" & LF & HT & -- set value status word - "fnstsw %0" & LF & HT & -- save status word - "movw %%ax, %0", -- store status word - - -- output stored in Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register), - - -- tell compiler that we used eax - Clobber => "eax"); - - -- if the status word is zero, there is no FPU - if Register = 0 then - return False; -- no status word - end if; -- check status word value - - -- check if we can get the control word - Asm ( - - -- the assembler code - "fnstcw %0", -- save the control word - - -- output into Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register)); - - -- check the relevant bits - if (Register and 16#103F#) /= 16#003F# then - return False; -- no control word - end if; -- check control word value - - -- FPU found - return True; - - end Has_FPU; - - -------------------------------- - -- Detect CPUID instruction -- - -------------------------------- - - -- The processor supports the CPUID instruction if it is possible - -- to change the value of ID flag bit in the EFLAGS register. - - function Has_CPUID return Boolean is - - Original_Flags, Modified_Flags : Processor_Register; - -- EFLAG contents before and after changing the ID flag - - begin - - -- try flipping the ID flag in the EFLAGS register - Asm ( - - -- the assembler code - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %%eax" & LF & HT & -- pop EFLAGS into eax - "movl %%eax, %0" & LF & HT & -- save EFLAGS content - "xor $0x200000, %%eax" & LF & HT & -- flip ID flag - "push %%eax" & LF & HT & -- push EFLAGS on stack - "popfl" & LF & HT & -- load EFLAGS register - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %1", -- save EFLAGS content - - -- output values, may be anything - -- Original_Flags is %0 - -- Modified_Flags is %1 - Outputs => - (Processor_Register'Asm_output ("=g", Original_Flags), - Processor_Register'Asm_output ("=g", Modified_Flags)), - - -- tell compiler eax is destroyed - Clobber => "eax"); - - -- check if CPUID is supported - if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then - return True; -- ID flag was modified - else - return False; -- ID flag unchanged - end if; -- check for CPUID - - end Has_CPUID; - - ------------------------------- - -- Get CPUID support level -- - ------------------------------- - - function CPUID_Level return Natural is - - Level : Unsigned_32; - -- returned support level - - begin - - -- execute CPUID, storing the results in the Level register - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero is stored in eax - -- returning the support level in eax - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- eax is stored in Level - Outputs => Unsigned_32'Asm_output ("=a", Level), - - -- tell compiler ebx, ecx and edx registers are destroyed - Clobber => "ebx, ecx, edx"); - - -- return the support level - return Natural (Level); - - end CPUID_Level; - - -------------------------------- - -- Get CPU Vendor ID String -- - -------------------------------- - - -- The vendor ID string is returned in the ebx, ecx and edx register - -- after executing the CPUID instruction with eax set to zero. - -- In case of a true Intel processor the string returned is - -- "GenuineIntel" - - function Vendor_ID return String is - - Ebx, Ecx, Edx : Unsigned_Register; - -- registers containing the vendor ID string - - Vendor_ID : String (1 .. 12); - -- the vendor ID string - - begin - - -- execute CPUID, storing the results in the processor registers - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero stored in eax - -- vendor ID string returned in ebx, ecx and edx - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- ebx is stored in Ebx - -- ecx is stored in Ecx - -- edx is stored in Edx - Outputs => (Unsigned_Register'Asm_output ("=b", Ebx), - Unsigned_Register'Asm_output ("=c", Ecx), - Unsigned_Register'Asm_output ("=d", Edx))); - - -- now build the vendor ID string - Vendor_ID( 1) := Character'Val (Ebx.L1); - Vendor_ID( 2) := Character'Val (Ebx.H1); - Vendor_ID( 3) := Character'Val (Ebx.L2); - Vendor_ID( 4) := Character'Val (Ebx.H2); - Vendor_ID( 5) := Character'Val (Edx.L1); - Vendor_ID( 6) := Character'Val (Edx.H1); - Vendor_ID( 7) := Character'Val (Edx.L2); - Vendor_ID( 8) := Character'Val (Edx.H2); - Vendor_ID( 9) := Character'Val (Ecx.L1); - Vendor_ID(10) := Character'Val (Ecx.H1); - Vendor_ID(11) := Character'Val (Ecx.L2); - Vendor_ID(12) := Character'Val (Ecx.H2); - - -- return string - return Vendor_ID; - - end Vendor_ID; - - ------------------------------- - -- Get processor signature -- - ------------------------------- - - function Signature return Processor_Signature is - - Result : Processor_Signature; - -- processor signature returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one is stored in eax - -- processor signature returned in eax - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- eax is stored in Result - Outputs => Processor_Signature'Asm_output ("=a", Result), - - -- tell compiler that ebx, ecx and edx are also destroyed - Clobber => "ebx, ecx, edx"); - - -- return processor signature - return Result; - - end Signature; - - ------------------------------ - -- Get processor features -- - ------------------------------ - - function Features return Processor_Features is - - Result : Processor_Features; - -- processor features returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one stored in eax - -- processor features returned in edx - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- edx is stored in Result - Outputs => Processor_Features'Asm_output ("=d", Result), - - -- tell compiler that ebx and ecx are also destroyed - Clobber => "ebx, ecx"); - - -- return processor signature - return Result; - - end Features; - - end Intel_CPU; - @end smallexample - @c END OF INLINE ASSEMBLER CHAPTER - @c =============================== - - - @node VxWorks Topics - @chapter VxWorks Topics - - @noindent - This chapter describes topics that are specific to the GNAT for VxWorks - configurations. - - @menu - * Kernel Configuration for VxWorks:: - * Kernel Compilation Issues for VxWorks:: - * Handling Relocation Issues for PowerPc Targets:: - * Support for Software Floating Point on PowerPC Processors:: - * Interrupt Handling for VxWorks:: - * Simulating Command Line Arguments for VxWorks:: - * Debugging Issues for VxWorks:: - * Using GNAT from the Tornado 2 Project Facility:: - * Frequently Asked Questions for VxWorks:: - @end menu - - @node Kernel Configuration for VxWorks - @section Kernel Configuration for VxWorks - - @noindent - When configuring your VxWorks kernel we recommend including the target - shell. If you omit it from the configuration, you may get undefined - symbols at load time, e.g. - - @smallexample - -> ld < hello.exe - Loading hello.exe - Undefined symbols: - mkdir - @end smallexample - - @noindent - Generally, such undefined symbols are harmless since these are used by - optional parts of the GNAT run time. However if running your application - generates a VxWorks exception or illegal instruction, you should reconfigure - your kernel to resolve these symbols. - - @node Kernel Compilation Issues for VxWorks - @section Kernel Compilation Issues for VxWorks - - @noindent - If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps. - (Note that these recommendations apply to @file{cygnus-2.7.2-960126}, - shipped with Tornado 2 as the C compiler toolchain.) - - @itemize @bullet - @item - Compile your Ada module without linking it with the VxWorks Library: - @smallexample - gnatmake foo.adb -largs -nostdlib - @end smallexample - - @item - Edit your makefile and add on the @code{LIBS} line the exact path and name - of the GCC library file provided with GNAT. - @smallexample - LIBS = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \ - /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a - @end smallexample - - @noindent - To know the exact name and location of this file, type - @code{-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the - one provided with GNAT. - @smallexample - ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name - /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a - @end smallexample - @end itemize - - - @node Handling Relocation Issues for PowerPc Targets - @section Handling Relocation Issues for PowerPc Targets - @cindex Relocation issues for PowerPc VxWorks targets - @cindex PowerPc VxWorks, relocation issues - @cindex VxWorks PowerPc, relocation issues - - @noindent - Under certain circumstances, loading a program onto a PowerPC - board will fail with the message - @emph{Relocation value does not fit in 24 bits}. - - For some background on this issue, please refer to WRS' SPRs - 6040, 20257, and 22767. - In summary, - VxWorks on the PowerPC follows the variation of the SVR4 ABI known - as the Embedded ABI (@emph{EABI}). - @cindex Embedded ABI (for VxWorks on PowerPc) - @cindex EABI (for VxWorks on PowerPc) - In order to save space and time in - embedded applications, the EABI specifies that the default for - subprogram calls should be the branch instruction with relative - addressing using an immediate operand. The immediate operand - to this instruction (relative address) is 24 bits wide. It - is sign extended and 2#00# is appended for the last 2 bits (all - instructions must be on a 4 byte boundary). - The resulting - 26 bit offset means that the target of the branch must be within - +/- 32 Mbytes of the relative branch instruction. When VxWorks - is loading a program it completes the linking phase by - resolving all of the unresolved references in the object being - loaded. When one of those references is a relative address in - a branch instruction, and the linker determines that the target - is more than 32 Mbytes away from the branch, the error occurs. - - This only happens when the BSP is configured to use - more than 32 MBytes of memory. The VxWorks kernel is loaded into - low memory addresses, and the error usually occurs when the target - loader is used (because it loads objects into high memory, and thus - calls from the program to the VxWorks kernel can be too far). - @cindex VxWorks kernel (relocation issues on PowerPc) - - One way to solve this problem is to use the Tornado - host loader; this will place programs in low memory, close to the kernel. - - Another approach is to make use of the @code{-mlongcall} option to the - compiler; - @cindex @code{-mlongcall} (gcc) - GNAT has incorporated WRS' - gcc modification that implements this option. - If a subprogram call is - compiled with the @code{-mlongcall} option, then the generated code - constructs an absolute address in a register and uses a branch - instruction with absolute addressing mode. - - Starting with release 3.15, the GNAT runtime libraries that are - distributed are compiled with the @code{-mlongcall} option. In many - cases the use of these libraries is sufficient to avoid the - relocation problem, since it is the runtime library that contains - calls to the VxWorks kernel that need to span the address space gap. - If you are using an earlier GNAT release or a manually-built runtime, - you should recompile the GNAT runtime library with @code{-mlongcall}; - you can use the - @file{Makefile.adalib} file from the @file{adalib} directory. - - Application code may need to be compiled with @code{-mlongcall} if there - are calls directly to the kernel, the application is very large, - or in some specialized linking/loading scenarios. - - You can compile individual files with @code{-mlongcall} by placing this - option on the @code{gcc} command line (for brevity we are omitting the - @code{powerpc-wrs-vxworks-} prefix on the commands shown in this - paragraph). - If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be - passed to all invocations of @code{gcc} that @code{gnatmake} directly performs. - Note that one other compilation is made by @code{gnatlink}, on the file created - by @code{gnatbind} for the elaboration package body - (see @ref{Binding Using gnatbind}). - Passing @code{-mlongcall} to @code{gnatlink}, either directly - on the @code{gnatlink} command line or by including @code{-mlongcall} in the - @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the - binder file with the @code{-mlongcall} option. - - To see the effect of @code{-mlongcall}, consider the following small example: - - @smallexample - procedure Proc is - procedure Imported_Proc; - pragma Import (Ada, Imported_Proc); - begin - Imported_Proc; - end; - @end smallexample - - @noindent - If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated: - - @smallexample - _ada_proc: - ... - bl imported_proc - ... - @end smallexample - - @noindent - In contrast, here is the result with the @code{-mlongcall} option: - - @smallexample - _ada_proc: - ... - addis 9,0,imported_proc@@ha - addi 0,9,imported_proc@@l - mtlr 0 - blrl - ... - @end smallexample - - - @node Support for Software Floating Point on PowerPC Processors - @section Support for Software Floating Point on PowerPC Processors - - @noindent - The PowerPC 860 processor does not have hardware floating-point support. - In order to build and run GNAT modules properly, you need to install and - invoke software-emulated floating-point support as follows: - - @itemize @bullet - @item - At installation time: - @itemize @bullet - @item - Create a file @file{ada_object_path} under the directory - @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1} - (by default @file{BASE}=@file{c:\gnatpro}) - containing the following line: - @smallexample - rts-soft-float\adalib - @end smallexample - - @item - Create a file @file{ada_source_path} under the directory - @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1} - (by default @file{BASE}=@file{c:\gnatpro}) - containing the following line: - @smallexample - rts-soft-float\adainclude - @end smallexample - @end itemize - - @item - When using the compiler, specify @option{-msoft-float} - as a compiler and a linker option, e.g.: - @smallexample - $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float - @end smallexample - @end itemize - - - @node Interrupt Handling for VxWorks - @section Interrupt Handling for VxWorks - - @noindent - GNAT offers a range of options for hardware interrupt handling. In rough - order of latency and lack of restrictions: - - @itemize @bullet - @item Directly vectored interrupt procedure handlers - @item Directly vectored interrupt procedures that signal a task using - a suspension object - @item Ada 95 protected procedure handlers for interrupts - @item Ada 83 style interrupt entry handlers for interrupts - @end itemize - - @noindent - In general, the range of possible solutions trades off latency versus - restrictions in the handler code. Restrictions in direct vectored - interrupt handlers are documented in the @cite{VxWorks Programmer's Guide}. - Protected procedure handlers have only the - restriction that no potentially blocking operations are performed within - the handler. Interrupt entries have no restrictions. We recommend the - use of the protected procedure mechanism as providing the best balance - of these considerations for most applications. - - All handler types must explicitly perform any required hardware cleanups, - such as issuing an end-of-interrupt if necessary. - - For VxWorks/AE, applications that handle interrupts must be loaded into - the kernel protection domain. - - @itemize @bullet - @item Direct Vectored Interrupt Routines - - @noindent - This approach provides the lowest interrupt latency, but has the most - restrictions on what VxWorks and Ada runtime calls can be made, as well - as on what Ada entities are accessible to the handler code. Such handlers - are most useful when there are stringent latency requirements, and very - little processing is to be performed in the handler. Access to the - necessary VxWorks routines for setting up such handlers is provided in - the package @code{Interfaces.VxWorks}. - - VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}. - Note in particular that floating point context is not automatically saved and - restored when interrupts are vectored to the handler. If the handler is - to execute floating point instructions, the statements involved must be - bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined - in @code{Interfaces.VxWorks}. - - In general, it is a good idea to save and restore the handler that was - installed prior to application startup. The routines @code{intVecGet} - and @code{intVecSet} are used for this purpose. The Ada handler code - is installed into the vector table using routine @code{intConnect}, - which generates wrapper code to save and restore registers. - - Example: - - @smallexample - with Interfaces.VxWorks; use Interfaces.VxWorks; - with System; - - package P is - - Count : Natural := 0; - pragma Atomic (Count); - - -- Interrupt level used by this example - Level : constant := 1; - - -- Be sure to use a reasonable interrupt number for the target - -- board! Refer to the BSP for details. - Interrupt : constant := 16#14#; - - procedure Handler (Parameter : System.Address); - - end P; - - package body P is - - procedure Handler (parameter : System.Address) is - S : Status; - begin - Count := Count + 1; - -- Acknowledge interrupt. Not necessary for all interrupts. - S := sysBusIntAck (intLevel => Level); - end Handler; - end P; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - - with P; use P; - procedure Useint is - task T; - - S : Status; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - -- Save old handler - Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt)); - begin - S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access); - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Put_Line ("value of count:" & P.Count'Img); - end loop; - - -- Restore previous handler - S := sysIntDisable (intLevel => Level); - intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler); - end Useint; - @end smallexample - - @item Direct Vectored Interrupt Routines - - @noindent - A variation on the direct vectored routine that allows for less restrictive - handler code is to separate the interrupt processing into two levels. - - The first level is the same as in the previous section. Here we perform - simple hardware actions and signal a task pending on a Suspension_Object - (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex - and time-consuming operations. The routine @code{Set_True} signals a task - whose body loops and pends on the suspension object using @code{Suspend_Until_True}. - The suspension object is declared in a scope global to both the handler and - the task. This approach can be thought of as a slightly higher-level - application of the @code{C} example using a binary semaphore given in the - VxWorks Programmer's Manual. In fact, the implementation of - @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks - binary semaphore. - - This approach has a latency between the direct vectored approach and the - protected procedure approach. There are no restrictions in the Ada task - code, while the handler code has the same restrictions as any other - direct interrupt handler. - - Example: - - @smallexample - with System; - package Sem_Handler is - - Count : Natural := 0; - pragma Atomic (Count); - - -- Interrupt level used by this example - Level : constant := 1; - Interrupt : constant := 16#14#; - - -- Interrupt handler providing "immediate" handling - procedure Handler (Param : System.Address); - - -- Task whose body provides "deferred" handling - task Receiver is - pragma Interrupt_Priority - (System.Interrupt_Priority'First + Level + 1); - end Receiver; - - end Sem_Handler; - - with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control; - with Interfaces.VxWorks; use Interfaces.VxWorks; - package body Sema_Handler is - - SO : Suspension_Object; - - task body Receiver is - begin - loop - -- Wait for notification from immediate handler - Suspend_Until_True (SO); - - -- Interrupt processing - Count := Count + 1; - end loop; - end Receiver; - - procedure Handler (Param : System.Address) is - S : STATUS; - begin - -- Hardware cleanup, if necessary - S := sysBusIntAck (Level); - - -- Signal the task - Set_True (SO); - end Handler; - - end Sem_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - with Sem_Handler; use Sem_Handler; - procedure Useint is - - S : STATUS; - - task T; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - -- Save old handler - Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt)); - begin - S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access); - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Put_Line ("value of Count:" & Sem_Handler.Count'Img); - end loop; - - -- Restore handler - S := sysIntDisable (intLevel => Level); - intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler); - abort Receiver; - end Useint; - @end smallexample - - @item Protected Procedure Handlers for Interrupts - - @noindent - This is the recommended default mechanism for interrupt handling. - It essentially wraps the hybrid handler / task mechanism in a higher-level - abstraction, and provides a good balance between latency and capability. - - Vectored interrupts are designated by their interrupt number, starting from - 0 and ranging to the number of entries in the interrupt vector table - 1. - - In the GNAT VxWorks implementation, the following priority mappings are used: - @itemize @bullet - @item Normal task priorities are in the range 0 .. 245. - @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager} - task. - @item Interrupt priority 247 is used for vectored interrupts - that do not correspond to those generated via an interrupt controller. - @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels - 0 .. 7. - @item Priority 256 is reserved to the VxWorks kernel. - @end itemize - - Except for reserved priorities, the above are recommendations for setting the - ceiling priority of a protected object that handles interrupts, or the - priority of a task with interrupt entries. It's a very good idea to follow - these recommendations for vectored interrupts that come in through the PIC - as it will determine the priority of execution of the code in the protected - procedure or interrupt entry. - - No vectored interrupt numbers are reserved in this implementation, because - dedicated interrupts are determined by the board support package. Obviously, - careful consideration of the hardware is necessary when handling interrupts. - The VxWorks BSP for the board is the definitive reference for interrupt - assignments. - - Example: - - @smallexample - package PO_Handler is - - -- Interrupt level used by this example - Level : constant := 1; - - Interrupt : constant := 16#14#; - - protected Protected_Handler is - procedure Handler; - pragma Attach_Handler (Handler, Interrupt); - - function Count return Natural; - - pragma Interrupt_Priority (248); - private - The_Count : Natural := 0; - end Protected_Handler; - - end PO_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - package body PO_Handler is - - protected body Protected_Handler is - - procedure Handler is - S : Status; - begin - -- Hardware cleanup if necessary - S := sysBusIntAck (Level); - - -- Interrupt processing - The_Count := The_Count + 1; - end Handler; - - function Count return Natural is - begin - return The_Count; - end Count; - end Protected_Handler; - - end PO_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - - with PO_Handler; use PO_Handler; - procedure Useint is - - task T; - - S : STATUS; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - begin - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Put_Line ("value of count:" & Protected_Handler.Count'Img); - end loop; - - S := sysIntDisable (intLevel => Level); - end Useint; - @end smallexample - - @noindent - This is obviously significantly higher-level and easier to write than the - previous examples. - - @item Ada 83 Style Interrupt Entries - - GNAT provides a full implementation of the Ada 83 interrupt entry mechanism - for vectored interrupts. However, due to latency issues, - we only recommend using these for backward compatibility. The comments in - the previous section regarding interrupt priorities and reserved interrupts - apply here. - - In order to associate an interrupt with an entry, GNAT provides the - standard Ada convenience routine @code{Ada.Interrupts.Reference}. It is used - as follows: - - @smallexample - Interrupt_Address : constant System.Address := - Ada.Interrupts.Reference (Int_Num); - - task Handler_Task is - pragma Interrupt_Priority (248); -- For instance - entry Handler; - for Handler'Address use Interrupt_Address; - end Handler_Task; - @end smallexample - - @noindent - Since there is no restriction within an interrupt entry on blocking operations, - be sure to perform any hardware interrupt controller related operations before - executing a call that could block within the entry's accept statements. It - is assumed that interrupt entries are always open alternatives when they - appear within a selective wait statement. The presence of a guard gives - undefined behavior. - - Example: - - @smallexample - with Ada.Interrupts; - with System; - package Task_Handler is - - -- Interrupt level used by this example - Level : constant := 1; - - Interrupt : constant := 16#14#; - - Interrupt_Address : constant System.Address := - Ada.Interrupts.Reference (Int_Num); - - task Handler_Task is - pragma Interrupt_Priority (248); -- For instance - entry Handler; - for Handler'Address use Interrupt_Address; - - entry Count (Value : out Natural); - end Handler_Task; - end Task_Handler; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - package body Task_Handler is - - task body Handler_Task is - The_Count : Natural := 0; - S : STATUS; - begin - loop - select - accept Handler do - -- Hardware cleanup if necessary - S := sysBusIntAck (Level); - - -- Interrupt processing - The_Count := The_Count + 1; - end Handler; - or - accept Count (Value : out Natural) do - Value := The_Count; - end Count; - end select; - end loop; - end Handler_Task; - - end Handler_Task; - - with Interfaces.VxWorks; use Interfaces.VxWorks; - with Ada.Text_IO; use Ada.Text_IO; - - with Handler_Task; use Handler_Task; - procedure Useint is - - task T; - - S : STATUS; - Current_Count : Natural := 0; - - task body T is - begin - for I in 1 .. 10 loop - Put_Line ("Generating an interrupt..."); - delay 1.0; - - -- Generate interrupt, using interrupt number - S := sysBusIntGen (Level, Interrupt); - end loop; - end T; - - begin - S := sysIntEnable (intLevel => Level); - - for I in 1 .. 10 loop - delay 2.0; - Handler_Task.Count (Current_Count); - Put_Line ("value of count:" & Current_Count'Img); - end loop; - - S := sysIntDisable (intLevel => Level); - abort Handler_Task; - end Useint; - @end smallexample - @end itemize - - - @node Simulating Command Line Arguments for VxWorks - @section Simulating Command Line Arguments for VxWorks - - @noindent - The GNAT implementation of @code{Ada.Command_Line} relies on the standard C - symbols @code{argv} and @code{argc}. The model for invoking "programs" under - VxWorks does not provide these symbols. The typical method for invoking a - program under VxWorks is to call the @code{sp} function in order to spawn a - thread in which to execute a designated function (in GNAT, this is the implicit - main generated by gnatbind. @code{sp} provides the capability to push a variable - number of arguments onto the stack when the function is invoked. But this does - not work for the implicit Ada main, because it has no way of knowing how many - arguments might be required. This eliminates the possibility to use - @code{Ada.Command_Line}. - - One way to solve this problem is to define symbols in the VxWorks environment, - then import them into the Ada application. For example, we could define the - following package that imports two symbols, one an int and the other a string: - - @smallexample - with Interfaces.C.Strings; - use Interfaces.C.Strings; - package Args is - -- Define and import a variable for each argument - Int_Arg : Interfaces.C.Int; - String_Arg : Chars_Ptr; - private - pragma Import (C, Int_Arg, "intarg"); - pragma Import (C, String_Arg, "stringarg"); - end Args; - @end smallexample - - @noindent - An Ada unit could then use the two imported variables @code{Int_Arg} and - @code{String_Arg} as follows: - - @smallexample - with Args; use Args; - with Interfaces.C.Strings; - use Interfaces.C, Interfaces.C.Strings; - with Ada.Text_IO; use Ada.Text_IO; - procedure Argtest is - begin - Put_Line (Int'Image (Int_Arg)); - Put_Line (Value (String_Arg)); - end Argtest; - @end smallexample - - @noindent - When invoking the application from the shell, one will then set the values - to be imported, and spawn the application, as follows: - - @smallexample - -> intarg=10 - -> stringarg="Hello" - -> sp (argtest) - @end smallexample - - - @node Debugging Issues for VxWorks - @section Debugging Issues for VxWorks - - @noindent - The debugger can be launched directly from the Tornado environment or from @code{glide} - through its graphical interface: @code{gvd}. It can also be used - directly in text mode as shown below: - @noindent - The command to run @code{GDB} in text mode is - - @smallexample - $ @i{target}-gdb - @end smallexample - - @noindent - where @i{target} is the name of target of the cross GNAT - compiler. In contrast with native @code{gdb}, it is not useful to give the name of - the program to debug on the command line. Before starting a debugging - session, one needs to connect to the VxWorks-configured board and load - the relocatable object produced by @code{gnatlink}. This can be achieved - by the following commands: - - @smallexample - (vxgdb) target wtx myboard - (vxgdb) load program - @end smallexample - - @noindent - where @code{myboard} is the host name or IP number of the target board, and - @code{wtx} is the name of debugging protocol used to communicate - with the VxWorks board. Early versions of VxWorks, up tp 5.2, only - support the @code{} protocol whereas starting with VxWorks 5.3 - and Tornado, another protocol called @code{} was made available. The - choice of the protocol can be made when configuring the VxWorks - kernel itself. When available, the @code{} is greatly preferable - and actually the only supported protocol with GNAT. When the debugger - is launched directly from Tornado, the proper @code{target} command - is automatically generated by the environment. - - The GNAT debugger can be used for debugging multitasking programs in two - different modes and some minimal understanding of these modes is - necessary in order to use the debugger effectively. The two modes are: - - @itemize @bullet - @item Monotask mode: attach to, and debug, a single task. - This mode is equivalent to the capabilities offered by CrossWind. The - debugger interacts with a single task, while not affecting other tasks - (insofar as possible). This is the DEFAULT mode. - - @item Multitask mode: - The debugger has control over all Ada tasks in an application. It is - possible to gather information about all application tasks, and to - switch from one to another within a single debugging session. - @end itemize - - @noindent - It is not advised to switch between the two modes within a debugging - session. A third mode called System mode is also available and can be - used in place of the Multitask mode. Consult the Tornado documentation - for this. - - Among the criteria for selecting the appropriate mode is the effect of - task synchronization on the application's behavior. Debugging a - tasking application affects the timing of the application; minimizing - such effects may be critical in certain situations. The two modes have - different effects: monotask mode only affects the attached task: - others will run normally (if possible). Multitask mode stops all tasks - at each breakpoint and restarts them on single-step, next, finish or - continue; this may help avoid deadlocks in the presence of task - synchronization despite the inherent latency of stopping and - restarting the tasks. - - @subsection Using the debugger in monotask mode - - @noindent - There are two ways to begin your debugging session: - - @itemize @bullet - @item The program is already running on the board. - - @noindent - The sequence of commands to use this mode is: - @itemize @bullet - @item Launch GVD (possibly from the Tornado menu) - - @noindent - Verify that the debugger has access to the debug information of both - your program and the kernel. The Console window should have a message - "Looking for all loaded modules:" followed by the names of the modules - on the board and "ok". If you have some error messages here instead of - "ok", the debugging session may not work as expected. - - @item Attach to the desired task using - @smallexample - File --> Attach... - @end smallexample - @noindent - This task is stopped by the debugger. Other tasks continue to operate - normally (unless they are blocked by synchronization with the stopped - task). The source window should display the code on which the task has - been stopped, and if the stack display is enabled, it should reflect - the stack of the task. - @end itemize - - @item The program hasn't been loaded yet on the board - @itemize @bullet - @item Launch GVD (possibly from the Tornado menu) - @item Load your program to the board: - @smallexample - File --> Open Program... - @end smallexample - - @noindent - GVD should display: - @smallexample - Downloading your_program ...done. - Reading symbols from your_program...expanding to full symbols...done. - @end smallexample - - @item Set breakpoints in your program. - - @noindent - WARNING: they must be set in the main task (if your program runs - several tasks) - - @item Run your program using one of the three methods below: - @itemize @bullet - @item - Click on button or - - @item Menu - @smallexample - Program --> Run/Start - @end smallexample - - @item - Type in GVD's Console window - @smallexample - (gdb) run your_program - @end smallexample - @end itemize - @end itemize - - @item Whichever method you chose to start your debugging session, - you can use the following commands at this point: - @itemize @bullet - @item Browse sources and set breakpoints - @item Examine the call stack (Data --> call stack) - @item Go "up" and "down" in the call stack ("up" & "down" buttons) - @item Examine data - (Data --> Display local variables, or any of the other methods for viewing data in GVD) - @item Continue/finish - @end itemize - - Next/step/finish will only work if the top frame in the call stack has - debug information. This is almost never the case when first attaching - to the task since the task is usually stopped by the attach operation - in the GNAT runtime. You can verify which frames of the call stack - have debug information by: - @smallexample - Data --> call stack - (contextual menu inside the call stack window) - add "file location" - @end smallexample - - @noindent - If the current frame does not have a "file location", then there is no - debug information for the frame. We strongly recommended that you set - breakpoints in the source where debug information can be found and - "continue" until a breakpoint is reached before using - "next/step". Another convenient possibility is to use the "continue - until" capability available from the contextual menu of the Source - window. - - You can also examine the state of other tasks using - @smallexample - Data -> tasks - @end smallexample - - @noindent - but you can't "switch" to another task by clicking on the - elements of the task list. If you try to, you will get an error - message in GVD's console: - @smallexample - "Task switching is not allowed when multi-tasks mode is not active" - @end smallexample - - @noindent - Once you have completed your debugging session on the attached - task, you can detach from the task: - @smallexample - File --> detach - @end smallexample - - @noindent - The task resumes normal execution at this stage. WARNING: when you - detach from a task, be sure that you are in a frame where there is - debug information. Otherwise, the task won't resume properly. You can - then start another attach/detach cycle if you wish. - - Note that it is possible to launch several GVD sessions and - simultaneously attach each to a distinct task in monotask mode: - @smallexample - File --> New Debugger... (uncheck the box: Replace Current Debugger) - File --> Attach... (in the new window) - File --> detach - @end smallexample - @end itemize - - - @subsection Using the debugger in Multitask mode - - @noindent - The steps are as follows - - @itemize @bullet - @item - Launch GVD (possibly from the Tornado menu) - - @noindent - There are two possibilities: - @itemize @bullet - @item - If the program is already loaded on the target board, you need only verify - that debug information has been found by the debugger as described - above. - - @item - Otherwise, load the program on the board using - @smallexample - File --> Open program - @end smallexample - @end itemize - - @item Set breakpoints in the desired parts of the program - - @item Start the program - - @noindent - The simplest way to start the debugger in multitask mode is to use the - menu - @smallexample - Program --> Run/Start - @end smallexample - - @noindent - and check the box "enable vxWorks multi-tasks mode". - You can also use the following gdb commands in the console window - @smallexample - (gdb) set multi-tasks-mode on - (gdb) run your_program - @end smallexample - - @item Debug the stopped program - - @noindent - Once stopped at a breakpoint - (or if you pressed the "stop" button), you can use all the standard - commands listed for monotask mode + task switching (using Data --> - tasks). Using next/step under this mode is possible with the same - restrictions as for monotask mode, but is not recommended because all - tasks are restarted, leading to the possibility that a different task - hits a breakpoint before the stepping operation has completed. Such - an occurrence can result in a confusing state for both the user and - the debugger. So we strongly suggest the use of only breakpoints and - "continue" in this mode. - @end itemize - - A final reminder: whatever the mode, whether you are debugging or not, - the program has to be reloaded before each new execution, so that data - initialized by the loader is set correctly. For instance, if you wish - to restart the same execution of the same program, you can use the - following sequence of gdb commands in the console window: - @smallexample - (gdb) detach - (gdb) unload your_program(.exe) - (gdb) load your_program(.exe) - (gdb) run your_program - @end smallexample - - - @node Using GNAT from the Tornado 2 Project Facility - @section Using GNAT from the Tornado 2 Project Facility - @cindex Tornado II Project - - @menu - * The GNAT Toolchain as Used from the Tornado 2 Project Facility:: - * Building a Simple Application:: - * Mixing C and Ada Code in a Tornado 2 Project:: - * Compilation Switches:: - * Autoscale and Minimal Kernel Configuration:: - * Adapting BSPs to GNAT:: - * Using GNAT Project Files in a Tornado 2 Project:: - @end menu - - @noindent - This section describes how to add an Ada module in a Tornado project - using the Tornado 2 Project facility described in - @cite{Tornado User's Guide}, Chapter 4. - All recommendations apply for both 'Downloadable Modules' and 'Kernel' - project types. - - - @node The GNAT Toolchain as Used from the Tornado 2 Project Facility - @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility - - @noindent - Tornado 2 allows you to integrate third-party C toolchains. - (@cite{Tornado 2 API Programmer's Guide}, Chapter 7). - Thus the GNAT toolchain will be seen as a new C toolchain when used from - the Tornado 2 Project Facility. For each processor you can compile for, - you will find a gnat toolchain, e.g. PPC604gnat. These toolchains will - allow you to include Ada modules into your projects, and simply build them. - - The name of the so-called C compiler is @emph{cc_gnat_}, the name - of the 'linker' is @emph{ld_gnat_}, where is an architecture; e.g., - PPC. These scripts will call the correct executables during the compilation or - link processes, thus the C compiler, the C linker, or the GNAT toolchain, - depending on the context. - - - @node Building a Simple Application - @subsection Building a Simple Application - - @noindent - First, create a new project, using one of the gnat toolchains. - - To add an Ada source file to the current project, just click on - @code{Project -> Add/Include}, browse to the relevant file, and include it. - The Ada source file included should be the Ada entry point. Only - one Ada entry point is allowed in a project. Any other required Ada source - files will be automatically compiled and linked by the underlying tools. - - You can now compile the project, @code{Build->Rebuild all}. - A log of the compilation process can be found in the build directory, in - @file{gnatbuild.log}. It contains all the calls executed by the scripts, and - associated information. - - - @node Mixing C and Ada Code in a Tornado 2 Project - @subsection Mixing C and Ada Code in a Tornado 2 Project - - @noindent - You can mix C and Ada code in your projects. Your source files and the build - options should comply with the recommendations from the section - @cite{Interfacing to C}. - This means that you can have several or no C source files, and one or no Ada entry - point in your Tornado 2 Project. - - - @node Compilation Switches - @subsection Compilation Switches - @noindent - Once you have included all your source files, you may modify some compilation - and linking options. - To pass specific options to the GNAT toolchain, go to the Project's build - settings, on the @code{C/C++ Compiler} tab, and add your arguments in the - input window. - - You must comply with several rules to pass arguments to GNAT. - Arguments to be passed should be - - @itemize @bullet - - @item after any arguments passed to the C toolchain. - - @item prefixed depending on the tool that uses them, with the following syntax - - @itemize @bullet - @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake - @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind - @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink - @end itemize - @end itemize - - @noindent - You will find more information on the compilation process of Ada source files - in the section @cite{The GNAT Compilation Model}. - For a list of all available switches, refer to the sections describing - @code{gnatmake}, @code{gnatbind} and @code{gnatlink}. - - Here is an example that passes the option @code{-v} to the GNAT compiler : - @smallexample - -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT - -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604 - -cargs -v - @end smallexample - - @noindent - Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker, - and @code{-v} and @code{-g} to the compiler : - @smallexample - -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT - -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604 - -cargs -v -g -O2 -bargs -v -largs -v - @end smallexample - - @noindent - In both examples, the following arguments have been automatically added by the Project - Facility, and will be used by the C compiler. - @smallexample - -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT - -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604 - @end smallexample - - @noindent - Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input - boxes is used by the GNAT toolchain. It is required for the compilation - process. You should not remove it from any input box. - - - @node Autoscale and Minimal Kernel Configuration - @subsection Autoscale and Minimal Kernel Configuration - - @noindent - The Autoscale feature, present in the Project Facility can be used on your - VxWorks Kernel projects to determine the minimum set of components required - for your kernel to work. - (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.) - This feature is also available for projects involving Ada code. Just click on - @code{Project->Autoscale} to launch a check and determine the minimal kernel - configuration. - - - @node Adapting BSPs to GNAT - @subsection Adapting BSPs to GNAT - - @noindent - To use your Board Support Packages with the GNAT toolchain, you will have to adapt them, - either manually or using the @code{adaptbsp4gnat} script. - This procedure is described in the @cite{Tornado API Programmer's Guide}, - Chapter 7. - Here is a summary of this setup, depending on the context. - - @itemize @bullet - @item To do the adaptation manually: - - @itemize @bullet - - @item Copy your BSP directory contents into a new directory - - @item Go to this directory - - @item Edit the file @file{Makefile}, - - @itemize @bullet - @item Set tool to gnat, @code{TOOL=gnat} - - @item Reverse the order of the following lines - @itemize @bullet - @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)} - @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)} - @end itemize - - @end itemize - - @end itemize - - @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat} - script. Its syntax is @code{adaptbsp4gnat }. - - @noindent - This script follows the different steps described above to perform the - adaptation. - The name of the new bsp is given after the modification. By default, if - @file{} is the name of your BSP, @file{-gnat}, will be the name of - the BSP created. - @end itemize - - - @node Using GNAT Project Files in a Tornado 2 Project - @subsection Using GNAT Project Files in a Tornado 2 Project - - @noindent - You can use GNAT Project files to compile your Ada files. - To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}. - The path to the project file can be either absolute, or relative to the build - directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}). - Your project file should set the @code{Object_Dir} variable to a specific - value. - @smallexample - project Sample is - - Target := external ("TARGET_DIR"); - for Object_Dir use Target; - - end Sample; - @end smallexample - - - @node Frequently Asked Questions for VxWorks - @section Frequently Asked Questions for VxWorks - - @itemize @bullet - - @item - When I run my program twice on the board, it does not work, why? - - @noindent - Usually, Ada programs require elaboration and finalization, so the - compiler creates a wrapper procedure whose name is the same as the Ada - name of the main subprogram, which takes care of calling the elaboration - and finalization routines before and after your program. But the static - part of the elaboration is taken care of while loading the program - itself and thus if you launch it twice this part of the elaboration will - not be performed. This affects the proper elaboration of the - GNAT runtime and thus it is mandatory to reload your program before - relaunching it. - - @item - Can I load a collection of subprograms rather than a standalone program? - - @noindent - It is possible to write Ada programs with multiple entry points which - can be called from the VxWorks shell; you just need to consider your - main program as the VxWorks shell itself and generate an Ada subsystem - callable from outside @xref{Binding with Non-Ada Main Programs}. If you - use this method, you need to call @code{adainit} manually before calling - any Ada entry point. - - @item - When I use the @code{break exception} command, I get the message - @code{"exception" is not a function}, why? - - You are not in the proper language mode. Issue the command: - @smallexample - (vxgdb) set language ada - @end smallexample - - @item - When I load a large application from the VxWorks shell using the "ld" - command, the load hangs and never finishes. How can I load large - executables? - - This is a classic VxWorks problem when using the default "rsh" communication - method. Using NFS instead should work. Use the @code{nfsShowMount} command to - verify that your program is in a NFS mounted directory. - - @item - When I load a large application from the debugger using the wtx target - connection, the load never finishes, why? - - Make sure that the memory cache size parameter of the target server is - large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.) - See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2. - - @item - When I spawn my program under the VxWorks shell, interactive input does - not work, why? - - Only programs directly launched from the shell can have interactive - input. For a program spawned with the @code{sp} or @code{taskSpawn} - command, you need to have file redirection for input: - @smallexample - -> # here you can have interactive input - -> main - -> # here you cannot - -> sp main - -> # neither here - -> taskSpawn("ess",100,0,8000000,main) - -> # but you can input from a file: - -> taskSpawn("Bae",100,0,8000000,main) < input_file - @end smallexample - @end itemize - - - @node LynxOS Topics - @chapter LynxOS Topics - @noindent - This chapter describes topics that are specific to the GNAT for LynxOS - cross configurations. - - @menu - * Getting Started with GNAT on LynxOS:: - * Kernel Configuration for LynxOS:: - * Patch Level Issues for LynxOS:: - * Debugging Issues for LynxOS:: - * An Example Debugging Session for LynxOS:: - @end menu - - @node Getting Started with GNAT on LynxOS - @section Getting Started with GNAT on LynxOS - - @noindent - This section is a starting point for using GNAT to develop and - execute Ada 95 programs for LynuxWorks' LynxOS target environment from a - Unix host environment. - We assume that you know how to use GNAT in a native environment - and how to start a telnet or other login session to connect to your LynxOS board. - - To compile code for a LynxOS system running on a PowerPC - board, the basic compiler command is - @command{powerpc-xcoff-lynxos-gcc}. - - With GNAT, the easiest way to build the basic @code{Hello World} program is - with @code{gnatmake}. For the LynxOS PowerPC target this would look - like: - - @smallexample - $ powerpc-xcoff-lynxos-gnatmake hello - @i{powerpc-xcoff-lynxos-gcc -c hello.adb - powerpc-xcoff-lynxos-gnatbind -x hello.ali - powerpc-xcoff-lynxos-gnatlink hello.ali} - @end smallexample - - @noindent - (The first line is the command entered by the user -- the subseqent three - are the programs run by @code{gnatmake}.) - - This creates the executable @command{hello}" which you then need to load on the - board (using ftp or an NFS directory for example) to run it. - - - @node Kernel Configuration for LynxOS - @section Kernel Configuration for LynxOS - - @noindent - The appropriate configuration for your LynxOS kernel depends - on the target system and the requirements of your application. GNAT itself - adds no additional demands; however in some situations it may be appropriate - to increase the conservative - resource assumptions made by the default configuration. - - Kernel parameters limiting the maximum number of file descriptors, - kernel and user threads, synchronization objects, etc., may be set in the - file @file{uparam.h}. You may also wish to modify the file - @file{/etc/starttab}, which places limits on data, stack, and core file - size. See the documentation provided by LynuxWorks for more information. - - - @node Patch Level Issues for LynxOS - @section Patch Level Issues for LynxOS - - @noindent - The GNAT runtime requires that your system run at patch level 040 or - later. Please see the file @file{PatchCompatibility.txt} from the - distribution for more information. - - - @node Debugging Issues for LynxOS - @section Debugging Issues for LynxOS - - @noindent - GNAT's debugger is based on the same GNU gdb technology as the debugger - provided by LynxOS, though with a great number of extensions and - enhancements to support the Ada language and GNAT. The LynxOS - documentation is relevant to understanding how to get the debugger - started if you run into difficulties. - - To demonstrate a debugging session, we will use a slightly more complex - program called @file{demo1.adb}, which can be found in the @file{examples} - directory of the GNAT distribution. This program is compiled with - debugging information as follows: - - @smallexample - $ powerpc-xcoff-lynxos-gnatmake -g demo1 - powerpc-xcoff-lynxos-gcc -c -g demo1.adb - powerpc-xcoff-lynxos-gcc -c -g gen_list.adb - powerpc-xcoff-lynxos-gcc -c -g instr.adb - powerpc-xcoff-lynxos-gnatbind -x demo1.ali - powerpc-xcoff-lynxos-gnatlink -g demo1.ali - @end smallexample - - @noindent - Once the executable is created, copy it to your working directory on the - board. In this directory, you will have to launch the gdb server and - choose a free port number on your TCP/IP socket. Presuming the Internet - hostname of the board is @file{myboard} and the port chosen is 2345, - issue the following command: - - @smallexample - myboard> gdbserver myboard:2345 demo1 - @end smallexample - - @noindent - Then return to your host environment. - - The graphical debugger interface, @command{gvd}, supports both native - and cross environments at the same time. @command{gvd} can be launched from - @command{Glide} (see @file{README.Glide} for more information on customizing - @command{Glide} for LynxOS) or it can be launched from the command line as - follows: - - @smallexample - $ gvd --debugger powerpc-xcoff-lynxos-gdb - @end smallexample - - @noindent - Then to attach to the target, enter in @command{gvd}'s command line window: - - @smallexample - (gdb) target remote myboard:2345 - @end smallexample - - @noindent - For more information see the GVD documentation. - - The comments below concern debugging directly from the command line but - they also apply to @command{gvd}, though in most cases an equivalent - graphical command is also available. - - To run the cross debugger from the command line without the visual - interface use the command @code{powerpc-xcoff-lynxos-gdb}. - - You will see something like: - - @smallexample - GNU gdb 4.17.gnat.3.14a1 - Copyright 1998 Free Software Foundation, Inc. - GDB is free software, covered by the GNU General Public License, and you are - welcome to change it and/or distribute copies of it under certain conditions. - Type "show copying" to see the conditions. - There is absolutely no warranty for GDB. Type "show warranty" for details. - This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc - off-lynxos". - (gdb) - @end smallexample - - @noindent - Where @command{(gdb)} is the debugger's prompt. The first thing to do at the - prompt from within @command{gdb} is to load the symbol table from the - executable: - - @smallexample - (gdb) file demo1 - Reading symbols from demo1...done. - (gdb) - @end smallexample - - @noindent - You then have to attach to the server running on the board. Issue the command: - - @smallexample - (gdb) target remote myboard:2345 - @end smallexample - - @noindent - After the server has been started and attached from the host, the program is - running on the target but has halted execution at the very beginning. - The following commands set a breakpoint and continue execution: - - @smallexample - (gdb) break demo1.adb:37 - Breakpoint 1 at 0x100064d0: file demo1.adb, line 37. - (gdb) cont - Continuing. - - Breakpoint 1, demo1 () at demo1.adb:37 - 37 Set_Name (Fuel, "Fuel"); - (gdb) - @end smallexample - - @noindent - Here the execution has stopped at the breakpoint set above. Now - you can use the standard @code{gdb} commands to examine the stack and - program variables. - - Note that once execution has completed, the server on the board must be - restarted before a new debugging session may begin. - - @node An Example Debugging Session for LynxOS - @section An Example Debugging Session for LynxOS - - @noindent - Carrying on a little further with the debugging session, the following - example illustrates some of the usual debugging commands for moving - around and seeing where you are: - - @smallexample - (gdb) next - 38 Set_Name (Water, "Water"); - (gdb) bt - #0 demo1 () at demo1.adb:38 - #1 0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at - b~demo1.adb:118 - #2 0x10017538 in runmainthread () - #3 0x10001048 in __start () - (gdb) up - #1 0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at - b~demo1.adb:118 - 118 Ada_Main_Program; - (gdb) down - #0 demo1 () at demo1.adb:38 - 38 Set_Name (Water, "Water"); - (gdb) - @end smallexample - - @noindent - To examine and modify variables (of a tagged type here): - - @smallexample - (gdb) print speed - $1 = (name => "Speed ", value => -286331154) - (gdb) ptype speed - type = new instr.instrument with record - value: instr.speed; - end record - (gdb) speed.value := 3 - $2 = 3 - (gdb) print speed - $3 = (name => "Speed ", value => 3) - (gdb) info local - speed = (name => "Speed ", value => 3) - fuel = (name => "Fuel ", value => -286331154) - oil = (name => ' ' , value => -286331154, size => 20, - fill => 42 '*', empty => 46 '.') - water = (name => ' ' , value => -286331154, size => 20, - fill => 42 '*', empty => 46 '.') - time = (name => ' ' , seconds => 0, minutes => 0, hours => - 0) - chrono = (name => ' ' , seconds => 0, minutes => 0, - hours => 0) - db = (access demo1.dash_board.internal) 0x0 - (gdb) - @end smallexample - - @noindent - And finally letting the program it run to completion: - - @smallexample - (gdb) c - Continuing. - - Program exited normally. - (gdb) - @end smallexample - - - @node Performance Considerations - @chapter Performance Considerations - @cindex Performance - - @noindent - The GNAT system provides a number of options that allow a trade-off - between - - @itemize @bullet - @item - performance of the generated code - - @item - speed of compilation - - @item - minimization of dependences and recompilation - - @item - the degree of run-time checking. - @end itemize - - @noindent - The defaults (if no options are selected) aim at improving the speed - of compilation and minimizing dependences, at the expense of performance - of the generated code: - - @itemize @bullet - @item - no optimization - - @item - no inlining of subprogram calls - - @item - all run-time checks enabled except overflow and elaboration checks - @end itemize - - @noindent - These options are suitable for most program development purposes. This - chapter describes how you can modify these choices, and also provides - some guidelines on debugging optimized code. - - @menu - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - @end menu - - @node Controlling Run-Time Checks - @section Controlling Run-Time Checks - - @noindent - By default, GNAT generates all run-time checks, except arithmetic overflow - checking for integer operations and checks for access before elaboration on - subprogram calls. The latter are not required in default mode, because all - necessary checking is done at compile time. - @cindex @option{-gnatp} (@code{gcc}) - @cindex @option{-gnato} (@code{gcc}) - Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to - be modified. @xref{Run-Time Checks}. - - Our experience is that the default is suitable for most development - purposes. - - We treat integer overflow specially because these - are quite expensive and in our experience are not as important as other - run-time checks in the development process. Note that division by zero - is not considered an overflow check, and divide by zero checks are - generated where required by default. - - Elaboration checks are off by default, and also not needed by default, since - GNAT uses a static elaboration analysis approach that avoids the need for - run-time checking. This manual contains a full chapter discussing the issue - of elaboration checks, and if the default is not satisfactory for your use, - you should read this chapter. - - For validity checks, the minimal checks required by the Ada Reference - Manual (for case statements and assignments to array elements) are on - by default. These can be suppressed by use of the @option{-gnatVn} switch. - Note that in Ada 83, there were no validity checks, so if the Ada 83 mode - is acceptable (or when comparing GNAT performance with an Ada 83 compiler), - it may be reasonable to routinely use @option{-gnatVn}. Validity checks - are also suppressed entirely if @option{-gnatp} is used. - - @cindex Overflow checks - @cindex Checks, overflow - @findex Suppress - @findex Unsuppress - @cindex pragma Suppress - @cindex pragma Unsuppress - Note that the setting of the switches controls the default setting of - the checks. They may be modified using either @code{pragma Suppress} (to - remove checks) or @code{pragma Unsuppress} (to add back suppressed - checks) in the program source. - - @node Optimization Levels - @section Optimization Levels - @cindex @code{-O} (@code{gcc}) - - @noindent - The default is optimization off. This results in the fastest compile - times, but GNAT makes absolutely no attempt to optimize, and the - generated programs are considerably larger and slower than when - optimization is enabled. You can use the - @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3, - on the @code{gcc} command line to control the optimization level: - - @table @code - @item -O0 - no optimization (the default) - - @item -O1 - medium level optimization - - @item -O2 - full optimization - - @item -O3 - full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - @end table - - Higher optimization levels perform more global transformations on the - program and apply more expensive analysis algorithms in order to generate - faster and more compact code. The price in compilation time, and the - resulting improvement in execution time, - both depend on the particular application and the hardware environment. - You should experiment to find the best level for your application. - - Note: Unlike some other compilation systems, @code{gcc} has - been tested extensively at all optimization levels. There are some bugs - which appear only with optimization turned on, but there have also been - bugs which show up only in @emph{unoptimized} code. Selecting a lower - level of optimization does not improve the reliability of the code - generator, which in practice is highly reliable at all optimization - levels. - - Note regarding the use of @code{-O3}: The use of this optimization level - is generally discouraged with GNAT, since it often results in larger - executables which run more slowly. See further discussion of this point - in @pxref{Inlining of Subprograms}. - - @node Debugging Optimized Code - @section Debugging Optimized Code - - @noindent - Since the compiler generates debugging tables for a compilation unit before - it performs optimizations, the optimizing transformations may invalidate some - of the debugging data. You therefore need to anticipate certain - anomalous situations that may arise while debugging optimized code. This - section describes the most common cases. - - @enumerate - @item - @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC - bouncing back and forth in the code. This may result from any of the following - optimizations: - - @itemize @bullet - @item - @i{Common subexpression elimination:} using a single instance of code for a - quantity that the source computes several times. As a result you - may not be able to stop on what looks like a statement. - - @item - @i{Invariant code motion:} moving an expression that does not change within a - loop, to the beginning of the loop. - - @item - @i{Instruction scheduling:} moving instructions so as to - overlap loads and stores (typically) with other code, or in - general to move computations of values closer to their uses. Often - this causes you to pass an assignment statement without the assignment - happening and then later bounce back to the statement when the - value is actually needed. Placing a breakpoint on a line of code - and then stepping over it may, therefore, not always cause all the - expected side-effects. - @end itemize - - @item - @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two - identical pieces of code are merged and the program counter suddenly - jumps to a statement that is not supposed to be executed, simply because - it (and the code following) translates to the same thing as the code - that @emph{was} supposed to be executed. This effect is typically seen in - sequences that end in a jump, such as a @code{goto}, a @code{return}, or - a @code{break} in a C @code{switch} statement. - - @item - @i{The "roving variable":} The symptom is an unexpected value in a variable. - There are various reasons for this effect: - - @itemize @bullet - @item - In a subprogram prologue, a parameter may not yet have been moved to its - "home". - - @item - A variable may be dead, and its register re-used. This is - probably the most common cause. - - @item - As mentioned above, the assignment of a value to a variable may - have been moved. - - @item - A variable may be eliminated entirely by value propagation or - other means. In this case, GCC may incorrectly generate debugging - information for the variable - @end itemize - - @noindent - In general, when an unexpected value appears for a local variable or parameter - you should first ascertain if that value was actually computed by - your program, as opposed to being incorrectly reported by the debugger. - Record fields or - array elements in an object designated by an access value - are generally less of a problem, once you have ascertained that the access value - is sensible. - Typically, this means checking variables in the preceding code and in the - calling subprogram to verify that the value observed is explainable from other - values (one must apply the procedure recursively to those - other values); or re-running the code and stopping a little earlier - (perhaps before the call) and stepping to better see how the variable obtained - the value in question; or continuing to step @emph{from} the point of the - strange value to see if code motion had simply moved the variable's - assignments later. - @end enumerate - - @node Inlining of Subprograms - @section Inlining of Subprograms - - @noindent - A call to a subprogram in the current unit is inlined if all the - following conditions are met: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else that @code{gcc} - cannot support in inlined subprograms. - - @item - The call occurs after the definition of the body of the subprogram. - - @item - @cindex pragma Inline - @findex Inline - Either @code{pragma Inline} applies to the subprogram or it is - small and automatic inlining (optimization level @code{-O3}) is - specified. - @end itemize - - @noindent - Calls to subprograms in @code{with}'ed units are normally not inlined. - To achieve this level of inlining, the following conditions must all be - true: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else @code{gcc} cannot - support in inlined subprograms. - - @item - The call appears in a body (not in a package spec). - - @item - There is a @code{pragma Inline} for the subprogram. - - @item - @cindex @option{-gnatn} (@code{gcc}) - The @code{-gnatn} switch - is used in the @code{gcc} command line - @end itemize - - Note that specifying the @option{-gnatn} switch causes additional - compilation dependencies. Consider the following: - - @smallexample - @group - @cartouche - @b{package} R @b{is} - @b{procedure} Q; - @b{pragma} Inline (Q); - @b{end} R; - @b{package body} R @b{is} - ... - @b{end} R; - - @b{with} R; - @b{procedure} Main @b{is} - @b{begin} - ... - R.Q; - @b{end} Main; - @end cartouche - @end group - @end smallexample - - @noindent - With the default behavior (no @option{-gnatn} switch specified), the - compilation of the @code{Main} procedure depends only on its own source, - @file{main.adb}, and the spec of the package in file @file{r.ads}. This - means that editing the body of @code{R} does not require recompiling - @code{Main}. - - On the other hand, the call @code{R.Q} is not inlined under these - circumstances. If the @option{-gnatn} switch is present when @code{Main} - is compiled, the call will be inlined if the body of @code{Q} is small - enough, but now @code{Main} depends on the body of @code{R} in - @file{r.adb} as well as on the spec. This means that if this body is edited, - the main program must be recompiled. Note that this extra dependency - occurs whether or not the call is in fact inlined by @code{gcc}. - - The use of front end inlining with @option{-gnatN} generates similar - additional dependencies. - - @cindex @code{-fno-inline} (@code{gcc}) - Note: The @code{-fno-inline} switch - can be used to prevent - all inlining. This switch overrides all other conditions and ensures - that no inlining occurs. The extra dependences resulting from - @option{-gnatn} will still be active, even if - this switch is used to suppress the resulting inlining actions. - - Note regarding the use of @code{-O3}: There is no difference in inlining - behavior between @code{-O2} and @code{-O3} for subprograms with an explicit - pragma @code{Inline} assuming the use of @option{-gnatn} - or @option{-gnatN} (the switches that activate inlining). If you have used - pragma @code{Inline} in appropriate cases, then it is usually much better - to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which - in this case only has the effect of inlining subprograms you did not - think should be inlined. We often find that the use of @code{-O3} slows - down code by performing excessive inlining, leading to increased instruction - cache pressure from the increased code size. So the bottom line here is - that you should not automatically assume that @code{-O3} is better than - @code{-O2}, and indeed you should use @code{-O3} only if tests show that - it actually improves performance. - - - @include fdl.texi - @c GNU Free Documentation License - - @node Index,,GNU Free Documentation License, Top - @unnumbered Index - - @printindex cp - - @contents - - @bye --- 0 ---- diff -Nrc3pad gcc-3.4.0/gcc/ada/gnat_ug_wnt.texi gcc-3.4.1/gcc/ada/gnat_ug_wnt.texi *** gcc-3.4.0/gcc/ada/gnat_ug_wnt.texi 2004-03-20 15:33:53.000000000 +0000 --- gcc-3.4.1/gcc/ada/gnat_ug_wnt.texi 1970-01-01 00:00:00.000000000 +0000 *************** *** 1,20665 **** - \input texinfo @c -*-texinfo-*- - @c %**start of header - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c o - @c GNAT DOCUMENTATION o - @c o - @c G N A T _ U G o - @c o - @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. o - @c o - @c GNAT is free software; you can redistribute it and/or modify it under o - @c terms of the GNU General Public License as published by the Free Soft- o - @c ware Foundation; either version 2, or (at your option) any later ver- o - @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o - @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o - @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o - @c for more details. You should have received a copy of the GNU General o - @c Public License distributed with GNAT; see file COPYING. If not, write o - @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o - @c MA 02111-1307, USA. o - @c o - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - @c - @c GNAT_UG Style Guide - @c - @c 1. Always put a @noindent on the line before the first paragraph - @c after any of these commands: - @c - @c @chapter - @c @section - @c @subsection - @c @subsubsection - @c @subsubsubsection - @c - @c @end smallexample - @c @end itemize - @c @end enumerate - @c - @c 2. DO NOT use @example. Use @smallexample instead. - @c - @c 3. Each @chapter, @section, @subsection, @subsubsection, etc. - @c command must be preceded by two empty lines - @c - @c 4. The @item command must be on a line of its own if it is in an - @c @itemize or @enumerate command. - @c - @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" - @c or "ali". - @c - @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo - - - @setfilename gnat_ug_wnt.info - @settitle GNAT User's Guide for Windows NT - @dircategory GNU Ada tools - @direntry - * GNAT User's Guide (gnat_ug_wnt). GNAT User's Guide for Windows NT. - @end direntry - - - - @include gcc-common.texi - - @setchapternewpage odd - @syncodeindex fn cp - @c %**end of header - - @copying - Copyright @copyright{} 1995-2003, Free Software Foundation - - Permission is granted to copy, distribute and/or modify this document - under the terms of the GNU Free Documentation License, Version 1.2 - or any later version published by the Free Software Foundation; - with the Invariant Sections being ``GNU Free Documentation License'', with the - Front-Cover Texts being - ``GNAT User's Guide for Windows NT'', - and with no Back-Cover Texts. - A copy of the license is included in the section entitled ``GNU - Free Documentation License''. - @end copying - - @titlepage - - - @title GNAT User's Guide - @center @titlefont{for Windows NT} - - - - @subtitle GNAT, The GNU Ada 95 Compiler - @subtitle GNAT Version for GCC @value{version-GCC} - - @author Ada Core Technologies, Inc. - - @page - @vskip 0pt plus 1filll - - @insertcopying - - @end titlepage - - @ifnottex - @node Top, About This Guide, (dir), (dir) - @top GNAT User's Guide - - - GNAT User's Guide for Windows NT - - - - GNAT, The GNU Ada 95 Compiler - - GNAT Version for GCC @value{version-GCC} - - Ada Core Technologies, Inc. - - @insertcopying - - @menu - * About This Guide:: - * Getting Started with GNAT:: - * The GNAT Compilation Model:: - * Compiling Using gcc:: - * Binding Using gnatbind:: - * Linking Using gnatlink:: - * The GNAT Make Program gnatmake:: - * Renaming Files Using gnatchop:: - * Configuration Pragmas:: - * Handling Arbitrary File Naming Conventions Using gnatname:: - * GNAT Project Manager:: - * Elaboration Order Handling in GNAT:: - * The Cross-Referencing Tools gnatxref and gnatfind:: - * File Name Krunching Using gnatkr:: - * Preprocessing Using gnatprep:: - * The GNAT Library Browser gnatls:: - * GNAT and Libraries:: - * Using the GNU make Utility:: - * Finding Memory Problems with gnatmem:: - * Finding Memory Problems with GNAT Debug Pool:: - * Creating Sample Bodies Using gnatstub:: - * Reducing the Size of Ada Executables with gnatelim:: - * Other Utility Programs:: - * Running and Debugging Ada Programs:: - * Inline Assembler:: - * Microsoft Windows Topics:: - * Performance Considerations:: - * GNU Free Documentation License:: - * Index:: - - --- The Detailed Node Listing --- - - About This Guide - - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - - - Getting Started with GNAT - - * Running GNAT:: - * Running a Simple Ada Program:: - * Running a Program with Multiple Units:: - * Using the gnatmake Utility:: - - The GNAT Compilation Model - - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - - Foreign Language Representation - - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - - Compiling Ada Programs With gcc - - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - - Switches for gcc - - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - - Binding Ada Programs With gnatbind - - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - - Linking Using gnatlink - - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - - The GNAT Make Program gnatmake - - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - - Renaming Files Using gnatchop - - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - - Configuration Pragmas - - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - - Handling Arbitrary File Naming Conventions Using gnatname - - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - - GNAT Project Manager - - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - - Elaboration Order Handling in GNAT - - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - - The Cross-Referencing Tools gnatxref and gnatfind - - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - - File Name Krunching Using gnatkr - - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - - Preprocessing Using gnatprep - - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - - - The GNAT Library Browser gnatls - - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - - - GNAT and Libraries - - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - - Using the GNU make Utility - - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - - Finding Memory Problems with gnatmem - - * Running gnatmem (GDB Mode):: - * Running gnatmem (GMEM Mode):: - * Switches for gnatmem:: - * Examples of gnatmem Usage:: - * GDB and GMEM Modes:: - * Implementation Note:: - - - Finding Memory Problems with GNAT Debug Pool - - Creating Sample Bodies Using gnatstub - - * Running gnatstub:: - * Switches for gnatstub:: - - Reducing the Size of Ada Executables with gnatelim - - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - - Other Utility Programs - - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - - - Running and Debugging Ada Programs - - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - - Inline Assembler - - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - - Microsoft Windows Topics - - * Using GNAT on Windows:: - * GNAT Setup Tool:: - * CONSOLE and WINDOWS subsystems:: - * Temporary Files:: - * Mixed-Language Programming on Windows:: - * Windows Calling Conventions:: - * Introduction to Dynamic Link Libraries (DLLs):: - * Using DLLs with GNAT:: - * Building DLLs with GNAT:: - * GNAT and Windows Resources:: - * GNAT and COM/DCOM Objects:: - - - Performance Considerations - - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - - * Index:: - @end menu - @end ifnottex - - @node About This Guide - @unnumbered About This Guide - - @noindent - This guide describes the use of GNAT, a compiler and software development - toolset for the full Ada 95 programming language. - It describes the features of the compiler and tools, and details - how to use them to build Ada 95 applications. - - @menu - * What This Guide Contains:: - * What You Should Know before Reading This Guide:: - * Related Information:: - * Conventions:: - @end menu - - @node What This Guide Contains - @unnumberedsec What This Guide Contains - - @noindent - This guide contains the following chapters: - @itemize @bullet - @item - @ref{Getting Started with GNAT}, describes how to get started compiling - and running Ada programs with the GNAT Ada programming environment. - @item - @ref{The GNAT Compilation Model}, describes the compilation model used - by GNAT. - @item - @ref{Compiling Using gcc}, describes how to compile - Ada programs with @code{gcc}, the Ada compiler. - @item - @ref{Binding Using gnatbind}, describes how to - perform binding of Ada programs with @code{gnatbind}, the GNAT binding - utility. - @item - @ref{Linking Using gnatlink}, - describes @code{gnatlink}, a - program that provides for linking using the GNAT run-time library to - construct a program. @code{gnatlink} can also incorporate foreign language - object units into the executable. - @item - @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a - utility that automatically determines the set of sources - needed by an Ada compilation unit, and executes the necessary compilations - binding and link. - @item - @ref{Renaming Files Using gnatchop}, describes - @code{gnatchop}, a utility that allows you to preprocess a file that - contains Ada source code, and split it into one or more new files, one - for each compilation unit. - @item - @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT. - @item - @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override - the default GNAT file naming conventions, either for an individual unit or globally. - @item - @ref{GNAT Project Manager}, describes how to use project files to organize large projects. - @item - @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with - elaboration order issues. - @item - @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses - @code{gnatxref} and @code{gnatfind}, two tools that provide an easy - way to navigate through sources. - @item - @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr} - file name krunching utility, used to handle shortened - file names on operating systems with a limit on the length of names. - @item - @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a - preprocessor utility that allows a single source file to be used to - generate multiple or parameterized source files, by means of macro - substitution. - @item - @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a - utility that displays information about compiled units, including dependences - on the corresponding sources files, and consistency of compilations. - @item - @ref{GNAT and Libraries}, describes the process of creating and using - Libraries with GNAT. It also describes how to recompile the GNAT run-time - library. - - @item - @ref{Using the GNU make Utility}, describes some techniques for using - the GNAT toolset in Makefiles. - - @item - @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a - utility that monitors dynamic allocation and deallocation activity in a - program, and displays information about incorrect deallocations and sources - of possible memory leaks. - @item - @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to - use the GNAT-specific Debug Pool in order to detect as early as possible - the use of incorrect memory references. - - @item - @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub}, - a utility that generates empty but compilable bodies for library units. - - @item - @ref{Reducing the Size of Ada Executables with gnatelim}, describes - @code{gnatelim}, a tool which detects unused subprograms and helps - the compiler to create a smaller executable for the program. - - @item - @ref{Other Utility Programs}, discusses several other GNAT utilities, - including @code{gnatpsta}. - - @item - @ref{Running and Debugging Ada Programs}, describes how to run and debug - Ada programs. - - @item - @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program. - - - @item - @ref{Performance Considerations}, reviews the trade offs between using - defaults or options in program development. - @end itemize - - @node What You Should Know before Reading This Guide - @unnumberedsec What You Should Know before Reading This Guide - - @cindex Ada 95 Language Reference Manual - @noindent - This user's guide assumes that you are familiar with Ada 95 language, as - described in the International Standard ANSI/ISO/IEC-8652:1995, Jan - 1995. - - @node Related Information - @unnumberedsec Related Information - - @noindent - For further information about related tools, refer to the following - documents: - - @itemize @bullet - @item - @cite{GNAT Reference Manual}, which contains all reference - material for the GNAT implementation of Ada 95. - - @item - @cite{Ada 95 Language Reference Manual}, which contains all reference - material for the Ada 95 programming language. - - @item - @cite{Debugging with GDB} - contains all details on the use of the GNU source-level debugger. - - @item - @cite{GNU Emacs Manual} - contains full information on the extensible editor and programming - environment Emacs. - - @end itemize - - @node Conventions - @unnumberedsec Conventions - @cindex Conventions - @cindex Typographical conventions - - @noindent - Following are examples of the typographical and graphic conventions used - in this guide: - - @itemize @bullet - @item - @code{Functions}, @code{utility program names}, @code{standard names}, - and @code{classes}. - - @item - @samp{Option flags} - - @item - @file{File Names}, @file{button names}, and @file{field names}. - - @item - @var{Variables}. - - @item - @emph{Emphasis}. - - @item - [optional information or parameters] - - @item - Examples are described by text - @smallexample - and then shown this way. - @end smallexample - @end itemize - - @noindent - Commands that are entered by the user are preceded in this manual by the - characters @w{"@code{$ }"} (dollar sign followed by space). If your system - uses this sequence as a prompt, then the commands will appear exactly as - you see them in the manual. If your system uses some other prompt, then - the command will appear with the @code{$} replaced by whatever prompt - character you are using. - - - @node Getting Started with GNAT - @chapter Getting Started with GNAT - - @noindent - This chapter describes some simple ways of using GNAT to build - executable Ada programs. - - @menu - * Running GNAT:: - * Running a Simple Ada Program:: - - * Running a Program with Multiple Units:: - - * Using the gnatmake Utility:: - * Introduction to Glide and GVD:: - @end menu - - @node Running GNAT - @section Running GNAT - - @noindent - Three steps are needed to create an executable file from an Ada source - file: - - @enumerate - @item - The source file(s) must be compiled. - @item - The file(s) must be bound using the GNAT binder. - @item - All appropriate object files must be linked to produce an executable. - @end enumerate - - @noindent - All three steps are most commonly handled by using the @code{gnatmake} - utility program that, given the name of the main program, automatically - performs the necessary compilation, binding and linking steps. - - @node Running a Simple Ada Program - @section Running a Simple Ada Program - - @noindent - Any text editor may be used to prepare an Ada program. If @code{Glide} is - used, the optional Ada mode may be helpful in laying out the program. The - program text is a normal text file. We will suppose in our initial - example that you have used your editor to prepare the following - standard format text file: - - @smallexample - @group - @cartouche - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - @end cartouche - @end group - @end smallexample - - @noindent - This file should be named @file{hello.adb}. - With the normal default file naming conventions, GNAT requires - that each file - contain a single compilation unit whose file name is the - unit name, - with periods replaced by hyphens; the - extension is @file{ads} for a - spec and @file{adb} for a body. - You can override this default file naming convention by use of the - special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). - Alternatively, if you want to rename your files according to this default - convention, which is probably more convenient if you will be using GNAT - for all your compilations, then the @code{gnatchop} utility - can be used to generate correctly-named source files - (@pxref{Renaming Files Using gnatchop}). - - You can compile the program using the following command (@code{$} is used - as the command prompt in the examples in this document): - - @smallexample - $ gcc -c hello.adb - @end smallexample - - - @noindent - @code{gcc} is the command used to run the compiler. This compiler is - capable of compiling programs in several languages, including Ada 95 and - C. It assumes that you have given it an Ada program if the file extension is - either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile - the specified file. - - The @option{-c} switch is required. It tells @command{gcc} to only do a - compilation. (For C programs, @command{gcc} can also do linking, but this - capability is not used directly for Ada programs, so the @option{-c} - switch must always be present.) - - This compile command generates a file - @file{hello.o}, which is the object - file corresponding to your Ada program. It also generates an "Ada Library Information" file - @file{hello.ali}, - which contains additional information used to check - that an Ada program is consistent. - To build an executable file, - use @code{gnatbind} to bind the program - and @code{gnatlink} to link it. The - argument to both @code{gnatbind} and @code{gnatlink} is the name of the - @file{ali} file, but the default extension of @file{.ali} can - be omitted. This means that in the most common case, the argument - is simply the name of the main program: - - @smallexample - $ gnatbind hello - $ gnatlink hello - @end smallexample - - - @noindent - A simpler method of carrying out these steps is to use - @command{gnatmake}, - a master program that invokes all the required - compilation, binding and linking tools in the correct order. In particular, - @command{gnatmake} automatically recompiles any sources that have been modified - since they were last compiled, or sources that depend - on such modified sources, so that "version skew" is avoided. - @cindex Version skew (avoided by @command{gnatmake}) - - @smallexample - $ gnatmake hello.adb - @end smallexample - - - @noindent - The result is an executable program called @file{hello}, which can be - run by entering: - - @c The following should be removed (BMB 2001-01-23) - @c @smallexample - @c $ ./hello - @c @end smallexample - - @smallexample - $ hello - @end smallexample - - @noindent - assuming that the current directory is on the search path for executable programs. - - @noindent - and, if all has gone well, you will see - - @smallexample - Hello WORLD! - @end smallexample - - @noindent - appear in response to this command. - - - - - @node Running a Program with Multiple Units - @section Running a Program with Multiple Units - - @noindent - Consider a slightly more complicated example that has three files: a - main program, and the spec and body of a package: - - @smallexample - @cartouche - @group - @b{package} Greetings @b{is} - @b{procedure} Hello; - @b{procedure} Goodbye; - @b{end} Greetings; - - @b{with} Ada.Text_IO; @b{use} Ada.Text_IO; - @b{package} @b{body} Greetings @b{is} - @b{procedure} Hello @b{is} - @b{begin} - Put_Line ("Hello WORLD!"); - @b{end} Hello; - - @b{procedure} Goodbye @b{is} - @b{begin} - Put_Line ("Goodbye WORLD!"); - @b{end} Goodbye; - @b{end} Greetings; - @end group - - @group - @b{with} Greetings; - @b{procedure} Gmain @b{is} - @b{begin} - Greetings.Hello; - Greetings.Goodbye; - @b{end} Gmain; - @end group - @end cartouche - @end smallexample - - @noindent - Following the one-unit-per-file rule, place this program in the - following three separate files: - - @table @file - @item greetings.ads - spec of package @code{Greetings} - - @item greetings.adb - body of package @code{Greetings} - - @item gmain.adb - body of main program - @end table - - @noindent - To build an executable version of - this program, we could use four separate steps to compile, bind, and link - the program, as follows: - - @smallexample - $ gcc -c gmain.adb - $ gcc -c greetings.adb - $ gnatbind gmain - $ gnatlink gmain - @end smallexample - - - @noindent - Note that there is no required order of compilation when using GNAT. - In particular it is perfectly fine to compile the main program first. - Also, it is not necessary to compile package specs in the case where - there is an accompanying body; you only need to compile the body. If you want - to submit these files to the compiler for semantic checking and not code generation, - then use the - @option{-gnatc} switch: - - @smallexample - $ gcc -c greetings.ads -gnatc - @end smallexample - - - @noindent - Although the compilation can be done in separate steps as in the - above example, in practice it is almost always more convenient - to use the @code{gnatmake} tool. All you need to know in this case - is the name of the main program's source file. The effect of the above four - commands can be achieved with a single one: - - @smallexample - $ gnatmake gmain.adb - @end smallexample - - - @noindent - In the next section we discuss the advantages of using @code{gnatmake} in - more detail. - - @node Using the gnatmake Utility - @section Using the @command{gnatmake} Utility - - @noindent - If you work on a program by compiling single components at a time using - @code{gcc}, you typically keep track of the units you modify. In order to - build a consistent system, you compile not only these units, but also any - units that depend on the units you have modified. - For example, in the preceding case, - if you edit @file{gmain.adb}, you only need to recompile that file. But if - you edit @file{greetings.ads}, you must recompile both - @file{greetings.adb} and @file{gmain.adb}, because both files contain - units that depend on @file{greetings.ads}. - - @code{gnatbind} will warn you if you forget one of these compilation - steps, so that it is impossible to generate an inconsistent program as a - result of forgetting to do a compilation. Nevertheless it is tedious and - error-prone to keep track of dependencies among units. - One approach to handle the dependency-bookkeeping is to use a - makefile. However, makefiles present maintenance problems of their own: - if the dependencies change as you change the program, you must make - sure that the makefile is kept up-to-date manually, which is also an - error-prone process. - - The @code{gnatmake} utility takes care of these details automatically. - Invoke it using either one of the following forms: - - @smallexample - $ gnatmake gmain.adb - $ gnatmake gmain - @end smallexample - - - @noindent - The argument is the name of the file containing the main program; - you may omit the extension. @code{gnatmake} - examines the environment, automatically recompiles any files that need - recompiling, and binds and links the resulting set of object files, - generating the executable file, @file{gmain}. - In a large program, it - can be extremely helpful to use @code{gnatmake}, because working out by hand - what needs to be recompiled can be difficult. - - Note that @code{gnatmake} - takes into account all the Ada 95 rules that - establish dependencies among units. These include dependencies that result - from inlining subprogram bodies, and from - generic instantiation. Unlike some other - Ada make tools, @code{gnatmake} does not rely on the dependencies that were - found by the compiler on a previous compilation, which may possibly - be wrong when sources change. @code{gnatmake} determines the exact set of - dependencies from scratch each time it is run. - - - @node Introduction to Glide and GVD - @section Introduction to Glide and GVD - @cindex Glide - @cindex GVD - @noindent - Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs. This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger. Additional information may be found in the on-line help for these tools. - - @menu - * Building a New Program with Glide:: - * Simple Debugging with GVD:: - * Other Glide Features:: - @end menu - - @node Building a New Program with Glide - @subsection Building a New Program with Glide - @noindent - The simplest way to invoke Glide is to enter @command{glide} at the command prompt. It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running: - - @smallexample - $ glide& - @end smallexample - - @noindent - Glide will start up with an initial screen displaying the top-level menu items as well as some other information. The menu selections are as follows - @itemize @bullet - @item @code{Buffers} - @item @code{Files} - @item @code{Tools} - @item @code{Edit} - @item @code{Search} - @item @code{Mule} - @item @code{Glide} - @item @code{Help} - @end itemize - - @noindent - For this introductory example, you will need to create a new Ada source file. First, select the @code{Files} menu. This will pop open a menu with around a dozen or so items. To create a file, select the @code{Open file...} choice. Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name. Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name. For this example enter @file{hello.adb} as the name of the file. - - A new buffer will now appear, occupying the entire Glide window, with the file name at the top. The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item. Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file. - - You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines. First, type the following text: - @smallexample - with Ada.Text_IO; use Ada.Text_IO; - procedure Hello is - begin - @end smallexample - - @noindent - Observe that Glide uses different colors to distinguish reserved words from identifiers. Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations. When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left. But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed. - - The main part of the program will be a @code{for} loop. Instead of entering the text explicitly, however, use a statement template. Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives. Choose @code{for loop}. You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed. You should see the beginning of a @code{for} loop appear in the source program window. You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case). Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction). Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax. - - Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop: - @smallexample - Put_Line("Hello, World" & Integer'Image(I)) - @end smallexample - - @noindent - Finally, type @code{end Hello;} as the last line in the program. Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection. You will see a message at the bottom of the buffer confirming that the file has been saved. - - You are now ready to attempt to build the program. Select the @code{Ada} item from the top menu bar. Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable. Thus select @code{Ada build}. This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools. Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window. The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected. - - Correct the error: type in a semicolon to terminate the statement. Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file. This time the build will succeed; the tool output window shows you the options that are supplied by default. The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched. - - To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window: - - @smallexample - Hello, world 1 - Hello, world 2 - Hello, world 3 - Hello, world 4 - Hello, world 5 - @end smallexample - - @node Simple Debugging with GVD - @subsection Simple Debugging with GVD - - @noindent - This section describes how to set breakpoints, examine/modify variables, and step through execution. - - In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}. If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect. You can then launch GVD, e.g. on the @code{hello} program, by issuing the command: - - @smallexample - $ gvd hello - @end smallexample - - @noindent - If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build. Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}. - - GVD comes up in a multi-part window. One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected. - - To the left of the source file pane, you will notice green dots adjacent to some lines. These are lines for which object code exists and where breakpoints can thus be set. You set/reset a breakpoint by clicking the green dot. When a breakpoint is set, the dot is replaced by an @code{X} in a red circle. Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot. - - For this example, set a breakpoint at the statement where @code{Put_Line} is invoked. - - Start program execution by selecting the @code{Run} button on the top menu bar. (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.) Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message. - - You can examine the values of variables in several ways. Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas. - - Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger. Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item. Enter @code{2} as the new value, and press @command{OK}. The box for @code{Ind} shows the update. - - Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}. - - Remove the breakpoint, and resume execution by selecting the @code{Cont} button. You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination. - - - @node Other Glide Features - @subsection Other Glide Features - - @noindent - You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu. These are @emph{shortcut keys} that you can use instead of selecting menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}. - - To abort a Glide command, type @key{Ctrl-g}. - - If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line: - - @smallexample - $ glide hello.adb& - @end smallexample - - @noindent - While you are using Glide, a number of @emph{buffers} exist. You create some explicitly; e.g., when you open/create a file. Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build. If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry. - - If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}. - - If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps: - @itemize @bullet - @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents) - @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu - @end itemize - - @noindent - To exit from Glide, choose @code{Files} @result{} @code{Exit}. - - @node The GNAT Compilation Model - @chapter The GNAT Compilation Model - @cindex GNAT compilation model - @cindex Compilation model - - @menu - * Source Representation:: - * Foreign Language Representation:: - * File Naming Rules:: - * Using Other File Names:: - * Alternative File Naming Schemes:: - * Generating Object Files:: - * Source Dependencies:: - * The Ada Library Information Files:: - * Binding an Ada Program:: - * Mixed Language Programming:: - * Building Mixed Ada & C++ Programs:: - * Comparison between GNAT and C/C++ Compilation Models:: - * Comparison between GNAT and Conventional Ada Library Models:: - @end menu - - @noindent - This chapter describes the compilation model used by GNAT. Although - similar to that used by other languages, such as C and C++, this model - is substantially different from the traditional Ada compilation models, - which are based on a library. The model is initially described without - reference to the library-based model. If you have not previously used an - Ada compiler, you need only read the first part of this chapter. The - last section describes and discusses the differences between the GNAT - model and the traditional Ada compiler models. If you have used other - Ada compilers, this section will help you to understand those - differences, and the advantages of the GNAT model. - - @node Source Representation - @section Source Representation - @cindex Latin-1 - - @noindent - Ada source programs are represented in standard text files, using - Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar - 7-bit ASCII set, plus additional characters used for - representing foreign languages (@pxref{Foreign Language Representation} - for support of non-USA character sets). The format effector characters - are represented using their standard ASCII encodings, as follows: - - @table @code - @item VT - @findex VT - Vertical tab, @code{16#0B#} - - @item HT - @findex HT - Horizontal tab, @code{16#09#} - - @item CR - @findex CR - Carriage return, @code{16#0D#} - - @item LF - @findex LF - Line feed, @code{16#0A#} - - @item FF - @findex FF - Form feed, @code{16#0C#} - @end table - - @noindent - Source files are in standard text file format. In addition, GNAT will - recognize a wide variety of stream formats, in which the end of physical - physical lines is marked by any of the following sequences: - @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful - in accommodating files that are imported from other operating systems. - - @cindex End of source file - @cindex Source file, end - @findex SUB - The end of a source file is normally represented by the physical end of - file. However, the control character @code{16#1A#} (@code{SUB}) is also - recognized as signalling the end of the source file. Again, this is - provided for compatibility with other operating systems where this - code is used to represent the end of file. - - Each file contains a single Ada compilation unit, including any pragmas - associated with the unit. For example, this means you must place a - package declaration (a package @dfn{spec}) and the corresponding body in - separate files. An Ada @dfn{compilation} (which is a sequence of - compilation units) is represented using a sequence of files. Similarly, - you will place each subunit or child unit in a separate file. - - @node Foreign Language Representation - @section Foreign Language Representation - - @noindent - GNAT supports the standard character sets defined in Ada 95 as well as - several other non-standard character sets for use in localized versions - of the compiler (@pxref{Character Set Control}). - @menu - * Latin-1:: - * Other 8-Bit Codes:: - * Wide Character Encodings:: - @end menu - - @node Latin-1 - @subsection Latin-1 - @cindex Latin-1 - - @noindent - The basic character set is Latin-1. This character set is defined by ISO - standard 8859, part 1. The lower half (character codes @code{16#00#} - ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is - used to represent additional characters. These include extended letters - used by European languages, such as French accents, the vowels with umlauts - used in German, and the extra letter A-ring used in Swedish. - - @findex Ada.Characters.Latin_1 - For a complete list of Latin-1 codes and their encodings, see the source - file of library unit @code{Ada.Characters.Latin_1} in file - @file{a-chlat1.ads}. - You may use any of these extended characters freely in character or - string literals. In addition, the extended characters that represent - letters can be used in identifiers. - - @node Other 8-Bit Codes - @subsection Other 8-Bit Codes - - @noindent - GNAT also supports several other 8-bit coding schemes: - - @table @asis - @cindex Latin-2 - @item Latin-2 - Latin-2 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-3 - @cindex Latin-3 - Latin-3 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-4 - @cindex Latin-4 - Latin-4 letters allowed in identifiers, with uppercase and lowercase - equivalence. - - @item Latin-5 - @cindex Latin-5 - @cindex Cyrillic - Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase - equivalence. - - @item IBM PC (code page 437) - @cindex code page 437 - This code page is the normal default for PCs in the U.S. It corresponds - to the original IBM PC character set. This set has some, but not all, of - the extended Latin-1 letters, but these letters do not have the same - encoding as Latin-1. In this mode, these letters are allowed in - identifiers with uppercase and lowercase equivalence. - - @item IBM PC (code page 850) - @cindex code page 850 - This code page is a modification of 437 extended to include all the - Latin-1 letters, but still not with the usual Latin-1 encoding. In this - mode, all these letters are allowed in identifiers with uppercase and - lowercase equivalence. - - @item Full Upper 8-bit - Any character in the range 80-FF allowed in identifiers, and all are - considered distinct. In other words, there are no uppercase and lowercase - equivalences in this range. This is useful in conjunction with - certain encoding schemes used for some foreign character sets (e.g. - the typical method of representing Chinese characters on the PC). - - @item No Upper-Half - No upper-half characters in the range 80-FF are allowed in identifiers. - This gives Ada 83 compatibility for identifier names. - @end table - - @noindent - For precise data on the encodings permitted, and the uppercase and lowercase - equivalences that are recognized, see the file @file{csets.adb} in - the GNAT compiler sources. You will need to obtain a full source release - of GNAT to obtain this file. - - @node Wide Character Encodings - @subsection Wide Character Encodings - - @noindent - GNAT allows wide character codes to appear in character and string - literals, and also optionally in identifiers, by means of the following - possible encoding schemes: - - @table @asis - - @item Hex Coding - In this encoding, a wide character is represented by the following five - character sequence: - - @smallexample - ESC a b c d - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ESC A345 is used to represent the wide character with code - @code{16#A345#}. - This scheme is compatible with use of the full Wide_Character set. - - @item Upper-Half Coding - @cindex Upper-Half Coding - The wide character with encoding @code{16#abcd#} where the upper bit is on (in - other words, "a" is in the range 8-F) is represented as two bytes, - @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control - character, but is not required to be in the upper half. This method can - be also used for shift-JIS or EUC, where the internal coding matches the - external coding. - - @item Shift JIS Coding - @cindex Shift JIS Coding - A wide character is represented by a two-character sequence, - @code{16#ab#} and - @code{16#cd#}, with the restrictions described for upper-half encoding as - described above. The internal character code is the corresponding JIS - character according to the standard algorithm for Shift-JIS - conversion. Only characters defined in the JIS code set table can be - used with this encoding method. - - @item EUC Coding - @cindex EUC Coding - A wide character is represented by a two-character sequence - @code{16#ab#} and - @code{16#cd#}, with both characters being in the upper half. The internal - character code is the corresponding JIS character according to the EUC - encoding algorithm. Only characters defined in the JIS code set table - can be used with this encoding method. - - @item UTF-8 Coding - A wide character is represented using - UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO - 10646-1/Am.2. Depending on the character value, the representation - is a one, two, or three byte sequence: - @smallexample - @iftex - @leftskip=.7cm - @end iftex - 16#0000#-16#007f#: 2#0xxxxxxx# - 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# - 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# - - @end smallexample - - @noindent - where the xxx bits correspond to the left-padded bits of the - 16-bit character value. Note that all lower half ASCII characters - are represented as ASCII bytes and all upper half characters and - other wide characters are represented as sequences of upper-half - (The full UTF-8 scheme allows for encoding 31-bit characters as - 6-byte sequences, but in this implementation, all UTF-8 sequences - of four or more bytes length will be treated as illegal). - @item Brackets Coding - In this encoding, a wide character is represented by the following eight - character sequence: - - @smallexample - [ " a b c d " ] - @end smallexample - - @noindent - Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal - characters (using uppercase letters) of the wide character code. For - example, ["A345"] is used to represent the wide character with code - @code{16#A345#}. It is also possible (though not required) to use the - Brackets coding for upper half characters. For example, the code - @code{16#A3#} can be represented as @code{["A3"]}. - - This scheme is compatible with use of the full Wide_Character set, - and is also the method used for wide character encoding in the standard - ACVC (Ada Compiler Validation Capability) test suite distributions. - - @end table - - @noindent - Note: Some of these coding schemes do not permit the full use of the - Ada 95 character set. For example, neither Shift JIS, nor EUC allow the - use of the upper half of the Latin-1 set. - - @node File Naming Rules - @section File Naming Rules - - @noindent - The default file name is determined by the name of the unit that the - file contains. The name is formed by taking the full expanded name of - the unit and replacing the separating dots with hyphens and using - lowercase for all letters. - - An exception arises if the file name generated by the above rules starts - with one of the characters - a,g,i, or s, - and the second character is a - minus. In this case, the character tilde is used in place - of the minus. The reason for this special rule is to avoid clashes with - the standard names for child units of the packages System, Ada, - Interfaces, and GNAT, which use the prefixes - s- a- i- and g- - respectively. - - The file extension is @file{.ads} for a spec and - @file{.adb} for a body. The following list shows some - examples of these rules. - - @table @file - @item main.ads - Main (spec) - @item main.adb - Main (body) - @item arith_functions.ads - Arith_Functions (package spec) - @item arith_functions.adb - Arith_Functions (package body) - @item func-spec.ads - Func.Spec (child package spec) - @item func-spec.adb - Func.Spec (child package body) - @item main-sub.adb - Sub (subunit of Main) - @item a~bad.adb - A.Bad (child package body) - @end table - - @noindent - Following these rules can result in excessively long - file names if corresponding - unit names are long (for example, if child units or subunits are - heavily nested). An option is available to shorten such long file names - (called file name "krunching"). This may be particularly useful when - programs being developed with GNAT are to be used on operating systems - with limited file name lengths. @xref{Using gnatkr}. - - Of course, no file shortening algorithm can guarantee uniqueness over - all possible unit names; if file name krunching is used, it is your - responsibility to ensure no name clashes occur. Alternatively you - can specify the exact file names that you want used, as described - in the next section. Finally, if your Ada programs are migrating from a - compiler with a different naming convention, you can use the gnatchop - utility to produce source files that follow the GNAT naming conventions. - (For details @pxref{Renaming Files Using gnatchop}.) - - @node Using Other File Names - @section Using Other File Names - @cindex File names - - @noindent - In the previous section, we have described the default rules used by - GNAT to determine the file name in which a given unit resides. It is - often convenient to follow these default rules, and if you follow them, - the compiler knows without being explicitly told where to find all - the files it needs. - - However, in some cases, particularly when a program is imported from - another Ada compiler environment, it may be more convenient for the - programmer to specify which file names contain which units. GNAT allows - arbitrary file names to be used by means of the Source_File_Name pragma. - The form of this pragma is as shown in the following examples: - @cindex Source_File_Name pragma - - @smallexample - @group - @cartouche - @b{pragma} Source_File_Name (My_Utilities.Stacks, - Spec_File_Name => "myutilst_a.ada"); - @b{pragma} Source_File_name (My_Utilities.Stacks, - Body_File_Name => "myutilst.ada"); - @end cartouche - @end group - @end smallexample - - @noindent - As shown in this example, the first argument for the pragma is the unit - name (in this example a child unit). The second argument has the form - of a named association. The identifier - indicates whether the file name is for a spec or a body; - the file name itself is given by a string literal. - - The source file name pragma is a configuration pragma, which means that - normally it will be placed in the @file{gnat.adc} - file used to hold configuration - pragmas that apply to a complete compilation environment. - For more details on how the @file{gnat.adc} file is created and used - @pxref{Handling of Configuration Pragmas} - @cindex @file{gnat.adc} - - GNAT allows completely arbitrary file names to be specified using the - source file name pragma. However, if the file name specified has an - extension other than @file{.ads} or @file{.adb} it is necessary to use a special - syntax when compiling the file. The name in this case must be preceded - by the special sequence @code{-x} followed by a space and the name of the - language, here @code{ada}, as in: - - @smallexample - $ gcc -c -x ada peculiar_file_name.sim - @end smallexample - - @noindent - @code{gnatmake} handles non-standard file names in the usual manner (the - non-standard file name for the main program is simply used as the - argument to gnatmake). Note that if the extension is also non-standard, - then it must be included in the gnatmake command, it may not be omitted. - - @node Alternative File Naming Schemes - @section Alternative File Naming Schemes - @cindex File naming schemes, alternative - @cindex File names - - In the previous section, we described the use of the @code{Source_File_Name} - pragma to allow arbitrary names to be assigned to individual source files. - However, this approach requires one pragma for each file, and especially in - large systems can result in very long @file{gnat.adc} files, and also create - a maintenance problem. - - GNAT also provides a facility for specifying systematic file naming schemes - other than the standard default naming scheme previously described. An - alternative scheme for naming is specified by the use of - @code{Source_File_Name} pragmas having the following format: - @cindex Source_File_Name pragma - - @smallexample - pragma Source_File_Name ( - Spec_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Body_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - pragma Source_File_Name ( - Subunit_File_Name => FILE_NAME_PATTERN - [,Casing => CASING_SPEC] - [,Dot_Replacement => STRING_LITERAL]); - - FILE_NAME_PATTERN ::= STRING_LITERAL - CASING_SPEC ::= Lowercase | Uppercase | Mixedcase - - @end smallexample - - @noindent - The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. - It contains a single asterisk character, and the unit name is substituted - systematically for this asterisk. The optional parameter - @code{Casing} indicates - whether the unit name is to be all upper-case letters, all lower-case letters, - or mixed-case. If no - @code{Casing} parameter is used, then the default is all - lower-case. - - The optional @code{Dot_Replacement} string is used to replace any periods - that occur in subunit or child unit names. If no @code{Dot_Replacement} - argument is used then separating dots appear unchanged in the resulting - file name. - Although the above syntax indicates that the - @code{Casing} argument must appear - before the @code{Dot_Replacement} argument, but it - is also permissible to write these arguments in the opposite order. - - As indicated, it is possible to specify different naming schemes for - bodies, specs, and subunits. Quite often the rule for subunits is the - same as the rule for bodies, in which case, there is no need to give - a separate @code{Subunit_File_Name} rule, and in this case the - @code{Body_File_name} rule is used for subunits as well. - - The separate rule for subunits can also be used to implement the rather - unusual case of a compilation environment (e.g. a single directory) which - contains a subunit and a child unit with the same unit name. Although - both units cannot appear in the same partition, the Ada Reference Manual - allows (but does not require) the possibility of the two units coexisting - in the same environment. - - The file name translation works in the following steps: - - @itemize @bullet - - @item - If there is a specific @code{Source_File_Name} pragma for the given unit, - then this is always used, and any general pattern rules are ignored. - - @item - If there is a pattern type @code{Source_File_Name} pragma that applies to - the unit, then the resulting file name will be used if the file exists. If - more than one pattern matches, the latest one will be tried first, and the - first attempt resulting in a reference to a file that exists will be used. - - @item - If no pattern type @code{Source_File_Name} pragma that applies to the unit - for which the corresponding file exists, then the standard GNAT default - naming rules are used. - - @end itemize - - @noindent - As an example of the use of this mechanism, consider a commonly used scheme - in which file names are all lower case, with separating periods copied - unchanged to the resulting file name, and specs end with ".1.ada", and - bodies end with ".2.ada". GNAT will follow this scheme if the following - two pragmas appear: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.1.ada"); - pragma Source_File_Name - (Body_File_Name => "*.2.ada"); - @end smallexample - - @noindent - The default GNAT scheme is actually implemented by providing the following - default pragmas internally: - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*.ads", Dot_Replacement => "-"); - pragma Source_File_Name - (Body_File_Name => "*.adb", Dot_Replacement => "-"); - @end smallexample - - @noindent - Our final example implements a scheme typically used with one of the - Ada 83 compilers, where the separator character for subunits was "__" - (two underscores), specs were identified by adding @file{_.ADA}, bodies - by adding @file{.ADA}, and subunits by - adding @file{.SEP}. All file names were - upper case. Child units were not present of course since this was an - Ada 83 compiler, but it seems reasonable to extend this scheme to use - the same double underscore separator for child units. - - @smallexample - pragma Source_File_Name - (Spec_File_Name => "*_.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Body_File_Name => "*.ADA", - Dot_Replacement => "__", - Casing = Uppercase); - pragma Source_File_Name - (Subunit_File_Name => "*.SEP", - Dot_Replacement => "__", - Casing = Uppercase); - @end smallexample - - @node Generating Object Files - @section Generating Object Files - - @noindent - An Ada program consists of a set of source files, and the first step in - compiling the program is to generate the corresponding object files. - These are generated by compiling a subset of these source files. - The files you need to compile are the following: - - @itemize @bullet - @item - If a package spec has no body, compile the package spec to produce the - object file for the package. - - @item - If a package has both a spec and a body, compile the body to produce the - object file for the package. The source file for the package spec need - not be compiled in this case because there is only one object file, which - contains the code for both the spec and body of the package. - - @item - For a subprogram, compile the subprogram body to produce the object file - for the subprogram. The spec, if one is present, is as usual in a - separate file, and need not be compiled. - - @item - @cindex Subunits - In the case of subunits, only compile the parent unit. A single object - file is generated for the entire subunit tree, which includes all the - subunits. - - @item - Compile child units independently of their parent units - (though, of course, the spec of all the ancestor unit must be present in order - to compile a child unit). - - @item - @cindex Generics - Compile generic units in the same manner as any other units. The object - files in this case are small dummy files that contain at most the - flag used for elaboration checking. This is because GNAT always handles generic - instantiation by means of macro expansion. However, it is still necessary to - compile generic units, for dependency checking and elaboration purposes. - @end itemize - - @noindent - The preceding rules describe the set of files that must be compiled to - generate the object files for a program. Each object file has the same - name as the corresponding source file, except that the extension is - @file{.o} as usual. - - You may wish to compile other files for the purpose of checking their - syntactic and semantic correctness. For example, in the case where a - package has a separate spec and body, you would not normally compile the - spec. However, it is convenient in practice to compile the spec to make - sure it is error-free before compiling clients of this spec, because such - compilations will fail if there is an error in the spec. - - GNAT provides an option for compiling such files purely for the - purposes of checking correctness; such compilations are not required as - part of the process of building a program. To compile a file in this - checking mode, use the @option{-gnatc} switch. - - @node Source Dependencies - @section Source Dependencies - - @noindent - A given object file clearly depends on the source file which is compiled - to produce it. Here we are using @dfn{depends} in the sense of a typical - @code{make} utility; in other words, an object file depends on a source - file if changes to the source file require the object file to be - recompiled. - In addition to this basic dependency, a given object may depend on - additional source files as follows: - - @itemize @bullet - @item - If a file being compiled @code{with}'s a unit @var{X}, the object file - depends on the file containing the spec of unit @var{X}. This includes - files that are @code{with}'ed implicitly either because they are parents - of @code{with}'ed child units or they are run-time units required by the - language constructs used in a particular unit. - - @item - If a file being compiled instantiates a library level generic unit, the - object file depends on both the spec and body files for this generic - unit. - - @item - If a file being compiled instantiates a generic unit defined within a - package, the object file depends on the body file for the package as - well as the spec file. - - @item - @findex Inline - @cindex @option{-gnatn} switch - If a file being compiled contains a call to a subprogram for which - pragma @code{Inline} applies and inlining is activated with the - @option{-gnatn} switch, the object file depends on the file containing the - body of this subprogram as well as on the file containing the spec. Note - that for inlining to actually occur as a result of the use of this switch, - it is necessary to compile in optimizing mode. - - @cindex @option{-gnatN} switch - The use of @option{-gnatN} activates a more extensive inlining optimization - that is performed by the front end of the compiler. This inlining does - not require that the code generation be optimized. Like @option{-gnatn}, - the use of this switch generates additional dependencies. - - @item - If an object file O depends on the proper body of a subunit through inlining - or instantiation, it depends on the parent unit of the subunit. This means that - any modification of the parent unit or one of its subunits affects the - compilation of O. - - @item - The object file for a parent unit depends on all its subunit body files. - - @item - The previous two rules meant that for purposes of computing dependencies and - recompilation, a body and all its subunits are treated as an indivisible whole. - - @noindent - These rules are applied transitively: if unit @code{A} @code{with}'s - unit @code{B}, whose elaboration calls an inlined procedure in package - @code{C}, the object file for unit @code{A} will depend on the body of - @code{C}, in file @file{c.adb}. - - The set of dependent files described by these rules includes all the - files on which the unit is semantically dependent, as described in the - Ada 95 Language Reference Manual. However, it is a superset of what the - ARM describes, because it includes generic, inline, and subunit dependencies. - - An object file must be recreated by recompiling the corresponding source - file if any of the source files on which it depends are modified. For - example, if the @code{make} utility is used to control compilation, - the rule for an Ada object file must mention all the source files on - which the object file depends, according to the above definition. - The determination of the necessary - recompilations is done automatically when one uses @code{gnatmake}. - @end itemize - - @node The Ada Library Information Files - @section The Ada Library Information Files - @cindex Ada Library Information files - @cindex @file{ali} files - - @noindent - Each compilation actually generates two output files. The first of these - is the normal object file that has a @file{.o} extension. The second is a - text file containing full dependency information. It has the same - name as the source file, but an @file{.ali} extension. - This file is known as the Ada Library Information (@file{ali}) file. - The following information is contained in the @file{ali} file. - - @itemize @bullet - @item - Version information (indicates which version of GNAT was used to compile - the unit(s) in question) - - @item - Main program information (including priority and time slice settings, - as well as the wide character encoding used during compilation). - - @item - List of arguments used in the @code{gcc} command for the compilation - - @item - Attributes of the unit, including configuration pragmas used, an indication - of whether the compilation was successful, exception model used etc. - - @item - A list of relevant restrictions applying to the unit (used for consistency) - checking. - - @item - Categorization information (e.g. use of pragma @code{Pure}). - - @item - Information on all @code{with}'ed units, including presence of - @code{Elaborate} or @code{Elaborate_All} pragmas. - - @item - Information from any @code{Linker_Options} pragmas used in the unit - - @item - Information on the use of @code{Body_Version} or @code{Version} - attributes in the unit. - - @item - Dependency information. This is a list of files, together with - time stamp and checksum information. These are files on which - the unit depends in the sense that recompilation is required - if any of these units are modified. - - @item - Cross-reference data. Contains information on all entities referenced - in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to - provide cross-reference information. - - @end itemize - - @noindent - For a full detailed description of the format of the @file{ali} file, - see the source of the body of unit @code{Lib.Writ}, contained in file - @file{lib-writ.adb} in the GNAT compiler sources. - - @node Binding an Ada Program - @section Binding an Ada Program - - @noindent - When using languages such as C and C++, once the source files have been - compiled the only remaining step in building an executable program - is linking the object modules together. This means that it is possible to - link an inconsistent version of a program, in which two units have - included different versions of the same header. - - The rules of Ada do not permit such an inconsistent program to be built. - For example, if two clients have different versions of the same package, - it is illegal to build a program containing these two clients. - These rules are enforced by the GNAT binder, which also determines an - elaboration order consistent with the Ada rules. - - The GNAT binder is run after all the object files for a program have - been created. It is given the name of the main program unit, and from - this it determines the set of units required by the program, by reading the - corresponding ALI files. It generates error messages if the program is - inconsistent or if no valid order of elaboration exists. - - If no errors are detected, the binder produces a main program, in Ada by - default, that contains calls to the elaboration procedures of those - compilation unit that require them, followed by - a call to the main program. This Ada program is compiled to generate the - object file for the main program. The name of - the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec - @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the - main program unit. - - Finally, the linker is used to build the resulting executable program, - using the object from the main program from the bind step as well as the - object files for the Ada units of the program. - - @node Mixed Language Programming - @section Mixed Language Programming - @cindex Mixed Language Programming - - @menu - * Interfacing to C:: - * Calling Conventions:: - @end menu - - @node Interfacing to C - @subsection Interfacing to C - @noindent - There are two ways to - build a program that contains some Ada files and some other language - files depending on whether the main program is in Ada or not. - If the main program is in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake -c my_main.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind my_main.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. For instance: - @smallexample - gnatlink my_main.ali file1.o file2.o - @end smallexample - @end enumerate - - The three last steps can be grouped in a single command: - @smallexample - gnatmake my_main.adb -largs file1.o file2.o - @end smallexample - - @cindex Binder output file - @noindent - If the main program is in some language other than Ada, you may - have more than one entry point in the Ada subsystem. You must use a - special option of the binder to generate callable routines to initialize - and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). - Calls to the initialization and finalization routines must be inserted in - the main program, or some other appropriate point in the code. The call to - initialize the Ada units must occur before the first Ada subprogram is - called, and the call to finalize the Ada units must occur after the last - Ada subprogram returns. You use the same procedure for building the - program as described previously. In this case, however, the binder - only places the initialization and finalization subprograms into file - @file{b~@var{xxx}.adb} instead of the main program. - So, if the main program is not in Ada, you should proceed as follows: - - @enumerate - @item - Compile the other language files to generate object files. For instance: - @smallexample - gcc -c file1.c - gcc -c file2.c - @end smallexample - - @item - Compile the Ada units to produce a set of object files and ALI - files. For instance: - @smallexample - gnatmake -c entry_point1.adb - gnatmake -c entry_point2.adb - @end smallexample - - @item - Run the Ada binder on the Ada main program. For instance: - @smallexample - gnatbind -n entry_point1.ali entry_point2.ali - @end smallexample - - @item - Link the Ada main program, the Ada objects and the other language - objects. You only need to give the last entry point here. For instance: - @smallexample - gnatlink entry_point2.ali file1.o file2.o - @end smallexample - @end enumerate - - @node Calling Conventions - @subsection Calling Conventions - @cindex Foreign Languages - @cindex Calling Conventions - GNAT follows standard calling sequence conventions and will thus interface - to any other language that also follows these conventions. The following - Convention identifiers are recognized by GNAT: - - @itemize @bullet - @cindex Interfacing to Ada - @cindex Other Ada compilers - @cindex Convention Ada - @item - Ada. This indicates that the standard Ada calling sequence will be - used and all Ada data items may be passed without any limitations in the - case where GNAT is used to generate both the caller and callee. It is also - possible to mix GNAT generated code and code generated by another Ada - compiler. In this case, the data types should be restricted to simple - cases, including primitive types. Whether complex data types can be passed - depends on the situation. Probably it is safe to pass simple arrays, such - as arrays of integers or floats. Records may or may not work, depending - on whether both compilers lay them out identically. Complex structures - involving variant records, access parameters, tasks, or protected types, - are unlikely to be able to be passed. - - Note that in the case of GNAT running - on a platform that supports DEC Ada 83, a higher degree of compatibility - can be guaranteed, and in particular records are layed out in an identical - manner in the two compilers. Note also that if output from two different - compilers is mixed, the program is responsible for dealing with elaboration - issues. Probably the safest approach is to write the main program in the - version of Ada other than GNAT, so that it takes care of its own elaboration - requirements, and then call the GNAT-generated adainit procedure to ensure - elaboration of the GNAT components. Consult the documentation of the other - Ada compiler for further details on elaboration. - - However, it is not possible to mix the tasking run time of GNAT and - DEC Ada 83, All the tasking operations must either be entirely within - GNAT compiled sections of the program, or entirely within DEC Ada 83 - compiled sections of the program. - - @cindex Interfacing to Assembly - @cindex Convention Assembler - @item - Assembler. Specifies assembler as the convention. In practice this has the - same effect as convention Ada (but is not equivalent in the sense of being - considered the same convention). - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembler. - - @cindex Convention Asm - @findex Asm - @item - Asm. Equivalent to Assembly. - - @cindex Interfacing to COBOL - @cindex Convention COBOL - @findex COBOL - @item - COBOL. Data will be passed according to the conventions described - in section B.4 of the Ada 95 Reference Manual. - - @findex C - @cindex Interfacing to C - @cindex Convention C - @item - C. Data will be passed according to the conventions described - in section B.3 of the Ada 95 Reference Manual. - - @cindex Convention Default - @findex Default - @item - Default. Equivalent to C. - - @cindex Convention External - @findex External - @item - External. Equivalent to C. - - @findex C++ - @cindex Interfacing to C++ - @cindex Convention C++ - @item - CPP. This stands for C++. For most purposes this is identical to C. - See the separate description of the specialized GNAT pragmas relating to - C++ interfacing for further details. - - @findex Fortran - @cindex Interfacing to Fortran - @cindex Convention Fortran - @item - Fortran. Data will be passed according to the conventions described - in section B.5 of the Ada 95 Reference Manual. - - @item - Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95 - Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, - this means that the body of the subprogram is provided by the compiler itself, - usually by means of an efficient code sequence, and that the user does not - supply an explicit body for it. In an application program, the pragma can only - be applied to the following two sets of names, which the GNAT compiler - recognizes. - @itemize @bullet - @item - Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_- - Arithmetic. The corresponding subprogram declaration must have - two formal parameters. The - first one must be a signed integer type or a modular type with a binary - modulus, and the second parameter must be of type Natural. - The return type must be the same as the type of the first argument. The size - of this type can only be 8, 16, 32, or 64. - @item binary arithmetic operators: "+", "-", "*", "/" - The corresponding operator declaration must have parameters and result type - that have the same root numeric type (for example, all three are long_float - types). This simplifies the definition of operations that use type checking - to perform dimensional checks: - @smallexample - type Distance is new Long_Float; - type Time is new Long_Float; - type Velocity is new Long_Float; - function "/" (D : Distance; T : Time) - return Velocity; - pragma Import (Intrinsic, "/"); - @end smallexample - @noindent - This common idiom is often programmed with a generic definition and an explicit - body. The pragma makes it simpler to introduce such declarations. It incurs - no overhead in compilation time or code size, because it is implemented as a - single machine instruction. - @end itemize - @noindent - - @findex Stdcall - @cindex Convention Stdcall - @item - Stdcall. This is relevant only to NT/Win95 implementations of GNAT, - and specifies that the Stdcall calling sequence will be used, as defined - by the NT API. - - @findex DLL - @cindex Convention DLL - @item - DLL. This is equivalent to Stdcall. - - @findex Win32 - @cindex Convention Win32 - @item - Win32. This is equivalent to Stdcall. - - @findex Stubbed - @cindex Convention Stubbed - @item - Stubbed. This is a special convention that indicates that the compiler - should provide a stub body that raises @code{Program_Error}. - @end itemize - - @noindent - GNAT additionally provides a useful pragma @code{Convention_Identifier} - that can be used to parametrize conventions and allow additional synonyms - to be specified. For example if you have legacy code in which the convention - identifier Fortran77 was used for Fortran, you can use the configuration - pragma: - - @smallexample - pragma Convention_Identifier (Fortran77, Fortran); - @end smallexample - - @noindent - And from now on the identifier Fortran77 may be used as a convention - identifier (for example in an @code{Import} pragma) with the same - meaning as Fortran. - - @node Building Mixed Ada & C++ Programs - @section Building Mixed Ada & C++ Programs - - @noindent - Building a mixed application containing both Ada and C++ code may be a - challenge for the unaware programmer. As a matter of fact, this - interfacing has not been standardized in the Ada 95 reference manual due - to the immaturity and lack of standard of C++ at the time. This - section gives a few hints that should make this task easier. In - particular the first section addresses the differences with - interfacing with C. The second section looks into the delicate problem - of linking the complete application from its Ada and C++ parts. The last - section give some hints on how the GNAT run time can be adapted in order - to allow inter-language dispatching with a new C++ compiler. - - @menu - * Interfacing to C++:: - * Linking a Mixed C++ & Ada Program:: - * A Simple Example:: - * Adapting the Run Time to a New C++ Compiler:: - @end menu - - @node Interfacing to C++ - @subsection Interfacing to C++ - - @noindent - GNAT supports interfacing with C++ compilers generating code that is - compatible with the standard Application Binary Interface of the given - platform. - - @noindent - Interfacing can be done at 3 levels: simple data, subprograms and - classes. In the first 2 cases, GNAT offer a specific @var{Convention - CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle - names of subprograms and currently GNAT does not provide any help to - solve the demangling problem. This problem can be addressed in 2 ways: - @itemize @bullet - @item - by modifying the C++ code in order to force a C convention using - the @var{extern "C"} syntax. - - @item - by figuring out the mangled name and use it as the Link_Name argument of - the pragma import. - @end itemize - - @noindent - Interfacing at the class level can be achieved by using the GNAT specific - pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT - Reference Manual for additional information. - - @node Linking a Mixed C++ & Ada Program - @subsection Linking a Mixed C++ & Ada Program - - @noindent - Usually the linker of the C++ development system must be used to link - mixed applications because most C++ systems will resolve elaboration - issues (such as calling constructors on global class instances) - transparently during the link phase. GNAT has been adapted to ease the - use of a foreign linker for the last phase. Three cases can be - considered: - @enumerate - - @item - Using GNAT and G++ (GNU C++ compiler) from the same GCC - installation. The c++ linker can simply be called by using the c++ - specific driver called @code{c++}. Note that this setup is not - very common because it may request recompiling the whole GCC - tree from sources and it does not allow to upgrade easily to a new - version of one compiler for one of the two languages without taking the - risk of destabilizing the other. - - @smallexample - $ c++ -c file1.C - $ c++ -c file2.C - $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++ - @end smallexample - - @item - Using GNAT and G++ from 2 different GCC installations. If both compilers - are on the PATH, the same method can be used. It is important to be - aware that environment variables such as C_INCLUDE_PATH, - GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at - the same time and thus may make one of the 2 compilers operate - improperly if they are set for the other. In particular it is important - that the link command has access to the proper gcc library @file{libgcc.a}, - that is to say the one that is part of the C++ compiler - installation. The implicit link command as suggested in the gnatmake - command from the former example can be replaced by an explicit link - command with full verbosity in order to verify which library is used: - @smallexample - $ gnatbind ada_unit - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ - @end smallexample - If there is a problem due to interfering environment variables, it can - be workaround by using an intermediate script. The following example - shows the proper script to use when GNAT has not been installed at its - default location and g++ has been installed at its default location: - - @smallexample - $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - unset BINUTILS_ROOT - unset GCC_ROOT - c++ $* - @end smallexample - - @item - Using a non GNU C++ compiler. The same set of command as previously - described can be used to insure that the c++ linker is - used. Nonetheless, you need to add the path to libgcc explicitely, since some - libraries needed by GNAT are located in this directory: - - @smallexample - - $ gnatlink ada_unit file1.o file2.o --LINK=./my_script - $ cat ./my_script - #!/bin/sh - CC $* `gcc -print-libgcc-file-name` - - @end smallexample - - Where CC is the name of the non GNU C++ compiler. - - @end enumerate - - @node A Simple Example - @subsection A Simple Example - @noindent - The following example, provided as part of the GNAT examples, show how - to achieve procedural interfacing between Ada and C++ in both - directions. The C++ class A has 2 methods. The first method is exported - to Ada by the means of an extern C wrapper function. The second method - calls an Ada subprogram. On the Ada side, The C++ calls is modelized by - a limited record with a layout comparable to the C++ class. The Ada - subprogram, in turn, calls the c++ method. So from the C++ main program - the code goes back and forth between the 2 languages. - - @noindent - Here are the compilation commands - for native configurations: - @smallexample - $ gnatmake -c simple_cpp_interface - $ c++ -c cpp_main.C - $ c++ -c ex7.C - $ gnatbind -n simple_cpp_interface - $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS) - -lstdc++ ex7.o cpp_main.o - @end smallexample - @noindent - Here are the corresponding sources: - @smallexample - - //cpp_main.C - - #include "ex7.h" - - extern "C" @{ - void adainit (void); - void adafinal (void); - void method1 (A *t); - @} - - void method1 (A *t) - @{ - t->method1 (); - @} - - int main () - @{ - A obj; - adainit (); - obj.method2 (3030); - adafinal (); - @} - - //ex7.h - - class Origin @{ - public: - int o_value; - @}; - class A : public Origin @{ - public: - void method1 (void); - virtual void method2 (int v); - A(); - int a_value; - @}; - - //ex7.C - - #include "ex7.h" - #include - - extern "C" @{ void ada_method2 (A *t, int v);@} - - void A::method1 (void) - @{ - a_value = 2020; - printf ("in A::method1, a_value = %d \n",a_value); - - @} - - void A::method2 (int v) - @{ - ada_method2 (this, v); - printf ("in A::method2, a_value = %d \n",a_value); - - @} - - A::A(void) - @{ - a_value = 1010; - printf ("in A::A, a_value = %d \n",a_value); - @} - - -- Ada sources - @b{package} @b{body} Simple_Cpp_Interface @b{is} - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is} - @b{begin} - Method1 (This); - This.A_Value := V; - @b{end} Ada_Method2; - - @b{end} Simple_Cpp_Interface; - - @b{package} Simple_Cpp_Interface @b{is} - @b{type} A @b{is} @b{limited} - @b{record} - O_Value : Integer; - A_Value : Integer; - @b{end} @b{record}; - @b{pragma} Convention (C, A); - - @b{procedure} Method1 (This : @b{in} @b{out} A); - @b{pragma} Import (C, Method1); - - @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer); - @b{pragma} Export (C, Ada_Method2); - - @b{end} Simple_Cpp_Interface; - @end smallexample - - @node Adapting the Run Time to a New C++ Compiler - @subsection Adapting the Run Time to a New C++ Compiler - @noindent - GNAT offers the capability to derive Ada 95 tagged types directly from - preexisting C++ classes and . See "Interfacing with C++" in the GNAT - reference manual. The mechanism used by GNAT for achieving such a goal - has been made user configurable through a GNAT library unit - @code{Interfaces.CPP}. The default version of this file is adapted to - the GNU c++ compiler. Internal knowledge of the virtual - table layout used by the new C++ compiler is needed to configure - properly this unit. The Interface of this unit is known by the compiler - and cannot be changed except for the value of the constants defining the - characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, - CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source - of this unit for more details. - - @node Comparison between GNAT and C/C++ Compilation Models - @section Comparison between GNAT and C/C++ Compilation Models - - @noindent - The GNAT model of compilation is close to the C and C++ models. You can - think of Ada specs as corresponding to header files in C. As in C, you - don't need to compile specs; they are compiled when they are used. The - Ada @code{with} is similar in effect to the @code{#include} of a C - header. - - One notable difference is that, in Ada, you may compile specs separately - to check them for semantic and syntactic accuracy. This is not always - possible with C headers because they are fragments of programs that have - less specific syntactic or semantic rules. - - The other major difference is the requirement for running the binder, - which performs two important functions. First, it checks for - consistency. In C or C++, the only defense against assembling - inconsistent programs lies outside the compiler, in a makefile, for - example. The binder satisfies the Ada requirement that it be impossible - to construct an inconsistent program when the compiler is used in normal - mode. - - @cindex Elaboration order control - The other important function of the binder is to deal with elaboration - issues. There are also elaboration issues in C++ that are handled - automatically. This automatic handling has the advantage of being - simpler to use, but the C++ programmer has no control over elaboration. - Where @code{gnatbind} might complain there was no valid order of - elaboration, a C++ compiler would simply construct a program that - malfunctioned at run time. - - @node Comparison between GNAT and Conventional Ada Library Models - @section Comparison between GNAT and Conventional Ada Library Models - - @noindent - This section is intended to be useful to Ada programmers who have - previously used an Ada compiler implementing the traditional Ada library - model, as described in the Ada 95 Language Reference Manual. If you - have not used such a system, please go on to the next section. - - @cindex GNAT library - In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of - source files themselves acts as the library. Compiling Ada programs does - not generate any centralized information, but rather an object file and - a ALI file, which are of interest only to the binder and linker. - In a traditional system, the compiler reads information not only from - the source file being compiled, but also from the centralized library. - This means that the effect of a compilation depends on what has been - previously compiled. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the version of the unit most recently compiled into the library. - - @item - Inlining is effective only if the necessary body has already been - compiled into the library. - - @item - Compiling a unit may obsolete other units in the library. - @end itemize - - @noindent - In GNAT, compiling one unit never affects the compilation of any other - units because the compiler reads only source files. Only changes to source - files can affect the results of a compilation. In particular: - - @itemize @bullet - @item - When a unit is @code{with}'ed, the unit seen by the compiler corresponds - to the source version of the unit that is currently accessible to the - compiler. - - @item - @cindex Inlining - Inlining requires the appropriate source files for the package or - subprogram bodies to be available to the compiler. Inlining is always - effective, independent of the order in which units are complied. - - @item - Compiling a unit never affects any other compilations. The editing of - sources may cause previous compilations to be out of date if they - depended on the source file being modified. - @end itemize - - @noindent - The most important result of these differences is that order of compilation - is never significant in GNAT. There is no situation in which one is - required to do one compilation before another. What shows up as order of - compilation requirements in the traditional Ada library becomes, in - GNAT, simple source dependencies; in other words, there is only a set - of rules saying what source files must be present when a file is - compiled. - - @node Compiling Using gcc - @chapter Compiling Using @code{gcc} - - @noindent - This chapter discusses how to compile Ada programs using the @code{gcc} - command. It also describes the set of switches - that can be used to control the behavior of the compiler. - @menu - * Compiling Programs:: - * Switches for gcc:: - * Search Paths and the Run-Time Library (RTL):: - * Order of Compilation Issues:: - * Examples:: - @end menu - - @node Compiling Programs - @section Compiling Programs - - @noindent - The first step in creating an executable program is to compile the units - of the program using the @code{gcc} command. You must compile the - following files: - - @itemize @bullet - @item - the body file (@file{.adb}) for a library level subprogram or generic - subprogram - - @item - the spec file (@file{.ads}) for a library level package or generic - package that has no body - - @item - the body file (@file{.adb}) for a library level package - or generic package that has a body - - @end itemize - - @noindent - You need @emph{not} compile the following files - - @itemize @bullet - - @item - the spec of a library unit which has a body - - @item - subunits - @end itemize - - @noindent - because they are compiled as part of compiling related units. GNAT - package specs - when the corresponding body is compiled, and subunits when the parent is - compiled. - @cindex No code generated - If you attempt to compile any of these files, you will get one of the - following error messages (where fff is the name of the file you compiled): - - @smallexample - No code generated for file @var{fff} (@var{package spec}) - No code generated for file @var{fff} (@var{subunit}) - @end smallexample - - @noindent - The basic command for compiling a file containing an Ada unit is - - @smallexample - $ gcc -c [@var{switches}] @file{file name} - @end smallexample - - @noindent - where @var{file name} is the name of the Ada file (usually - having an extension - @file{.ads} for a spec or @file{.adb} for a body). - You specify the - @code{-c} switch to tell @code{gcc} to compile, but not link, the file. - The result of a successful compilation is an object file, which has the - same name as the source file but an extension of @file{.o} and an Ada - Library Information (ALI) file, which also has the same name as the - source file, but with @file{.ali} as the extension. GNAT creates these - two output files in the current directory, but you may specify a source - file in any directory using an absolute or relative path specification - containing the directory information. - - @findex gnat1 - @code{gcc} is actually a driver program that looks at the extensions of - the file arguments and loads the appropriate compiler. For example, the - GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}. - These programs are in directories known to the driver program (in some - configurations via environment variables you set), but need not be in - your path. The @code{gcc} driver also calls the assembler and any other - utilities needed to complete the generation of the required object - files. - - It is possible to supply several file names on the same @code{gcc} - command. This causes @code{gcc} to call the appropriate compiler for - each file. For example, the following command lists three separate - files to be compiled: - - @smallexample - $ gcc -c x.adb y.adb z.c - @end smallexample - - @noindent - calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and - @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}. - The compiler generates three object files @file{x.o}, @file{y.o} and - @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the - Ada compilations. Any switches apply to all the files listed, - except for - @option{-gnat@var{x}} switches, which apply only to Ada compilations. - - @node Switches for gcc - @section Switches for @code{gcc} - - @noindent - The @code{gcc} command accepts switches that control the - compilation process. These switches are fully described in this section. - First we briefly list all the switches, in alphabetical order, then we - describe the switches in more detail in functionally grouped sections. - - @menu - * Output and Error Message Control:: - * Debugging and Assertion Control:: - * Run-Time Checks:: - * Stack Overflow Checking:: - * Run-Time Control:: - * Validity Checking:: - * Style Checking:: - * Using gcc for Syntax Checking:: - * Using gcc for Semantic Checking:: - * Compiling Ada 83 Programs:: - * Character Set Control:: - * File Naming Control:: - * Subprogram Inlining Control:: - * Auxiliary Output Control:: - * Debugging Control:: - * Units to Sources Mapping Files:: - @end menu - - @table @code - @cindex @code{-b} (@code{gcc}) - @item -b @var{target} - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gcc}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item -c - @cindex @code{-c} (@code{gcc}) - Compile. Always use this switch when compiling Ada programs. - - Note: for some other languages when using @code{gcc}, notably in - the case of C and C++, it is possible to use - use @code{gcc} without a @code{-c} switch to - compile and link in one step. In the case of GNAT, you - cannot use this approach, because the binder must be run - and @code{gcc} cannot be used to run the GNAT binder. - - @item -g - @cindex @code{-g} (@code{gcc}) - Generate debugging information. This information is stored in the object - file and copied from there to the final executable file by the linker, - where it can be read by the debugger. You must use the - @code{-g} switch if you plan on using the debugger. - - @item -I@var{dir} - @cindex @code{-I} (@code{gcc}) - @cindex RTL - Direct GNAT to search the @var{dir} directory for source files needed by - the current compilation - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -I- - @cindex @code{-I-} (@code{gcc}) - @cindex RTL - Except for the source file named in the command line, do not look for source files - in the directory containing the source file named in the command line - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -o @var{file} - @cindex @code{-o} (@code{gcc}) - This switch is used in @code{gcc} to redirect the generated object file - and its associated ALI file. Beware of this switch with GNAT, because it may - cause the object file and ALI file to have different names which in turn - may confuse the binder and the linker. - - @item -O[@var{n}] - @cindex @code{-O} (@code{gcc}) - @var{n} controls the optimization level. - - @table @asis - @item n = 0 - No optimization, the default setting if no @code{-O} appears - - @item n = 1 - Normal optimization, the default if you specify @code{-O} without - an operand. - - @item n = 2 - Extensive optimization - - @item n = 3 - Extensive optimization with automatic inlining. This applies only to - inlining within a unit. For details on control of inter-unit inlining - see @xref{Subprogram Inlining Control}. - @end table - - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gcc}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -S - @cindex @code{-S} (@code{gcc}) - Used in place of @code{-c} to - cause the assembler source file to be - generated, using @file{.s} as the extension, - instead of the object file. - This may be useful if you need to examine the generated assembly code. - - @item -v - @cindex @code{-v} (@code{gcc}) - Show commands generated by the @code{gcc} driver. Normally used only for - debugging purposes or if you need to be sure what version of the - compiler you are executing. - - @item -V @var{ver} - @cindex @code{-V} (@code{gcc}) - Execute @var{ver} version of the compiler. This is the @code{gcc} - version, not the GNAT version. - - @item -gnata - Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be - activated. - - @item -gnatA - Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored. - - @item -gnatb - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -gnatc - Check syntax and semantics only (no code generation attempted). - - @item -gnatC - Compress debug information and external symbol name table entries. - - @item -gnatD - Output expanded source files for source level debugging. This switch - also suppress generation of cross-reference information (see -gnatx). - - @item -gnatec@var{path} - Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files}) - - @item -gnatem@var{path} - Specify a mapping file. (see @ref{Units to Sources Mapping Files}) - - @item -gnatE - Full dynamic elaboration checks. - - @item -gnatf - Full errors. Multiple errors per line, all undefined references. - - @item -gnatF - Externals names are folded to all uppercase. - - @item -gnatg - Internal GNAT implementation mode. This should not be used for - applications programs, it is intended only for use by the compiler - and its run-time library. For documentation, see the GNAT sources. - - @item -gnatG - List generated expanded code in source form. - - @item -gnati@var{c} - Identifier character set - (@var{c}=1/2/3/4/8/9/p/f/n/w). - - @item -gnath - Output usage information. The output is written to @file{stdout}. - - @item -gnatk@var{n} - Limit file names to @var{n} (1-999) characters (@code{k} = krunch). - - @item -gnatl - Output full source listing with embedded error messages. - - @item -gnatm@var{n} - Limit number of detected errors to @var{n} (1-999). - - @item -gnatn - Activate inlining across unit boundaries for subprograms for which - pragma @code{inline} is specified. - - @item -gnatN - Activate front end inlining. - - @item -fno-inline - Suppresses all inlining, even if other optimization or inlining switches - are set. - - @item -fstack-check - Activates stack checking. See separate section on stack checking for - details of the use of this option. - - @item -gnato - Enable numeric overflow checking (which is not normally enabled by - default). Not that division by zero is a separate check that is not - controlled by this switch (division by zero checking is on by default). - - @item -gnatp - Suppress all checks. - - @item -gnatq - Don't quit; try semantics, even if parse errors. - - @item -gnatQ - Don't quit; generate @file{ali} and tree files even if illegalities. - - @item -gnatP - Enable polling. This is required on some systems (notably Windows NT) to - obtain asynchronous abort and asynchronous transfer of control capability. - See the description of pragma Polling in the GNAT Reference Manual for - full details. - - @item -gnatR[0/1/2/3][s] - Output representation information for declared types and objects. - - @item -gnats - Syntax check only. - - @item -gnatt - Tree output file to be generated. - - @item -gnatT nnn - Set time slice to specified number of microseconds - - @item -gnatu - List units for this compilation. - - @item -gnatU - Tag all error messages with the unique string "error:" - - @item -gnatv - Verbose mode. Full error output with source lines to @file{stdout}. - - @item -gnatV - Control level of validity checking. See separate section describing - this feature. - - @item -gnatwxxx@var{xxx} - Warning mode where - @var{xxx} is a string of options describing the exact warnings that - are enabled or disabled. See separate section on warning control. - - @item -gnatW@var{e} - Wide character encoding method - (@var{e}=n/h/u/s/e/8). - - @item -gnatx - Suppress generation of cross-reference information. - - @item -gnaty - Enable built-in style checks. See separate section describing this feature. - - @item -gnatz@var{m} - Distribution stub generation and compilation - (@var{m}=r/c for receiver/caller stubs). - - @item -gnat83 - Enforce Ada 83 restrictions. - - @item -pass-exit-codes - Catch exit codes from the compiler and use the most meaningful as - exit status. - @end table - - You may combine a sequence of GNAT switches into a single switch. For - example, the combined switch - - @cindex Combining GNAT switches - @smallexample - -gnatofi3 - @end smallexample - - @noindent - is equivalent to specifying the following sequence of switches: - - @smallexample - -gnato -gnatf -gnati3 - @end smallexample - - @noindent - The following restrictions apply to the combination of switches - in this manner: - - @itemize @bullet - @item - The switch @option{-gnatc} if combined with other switches must come - first in the string. - - @item - The switch @option{-gnats} if combined with other switches must come - first in the string. - - @item - Once a "y" appears in the string (that is a use of the @option{-gnaty} - switch), then all further characters in the switch are interpreted - as style modifiers (see description of @option{-gnaty}). - - @item - Once a "d" appears in the string (that is a use of the @option{-gnatd} - switch), then all further characters in the switch are interpreted - as debug flags (see description of @option{-gnatd}). - - @item - Once a "w" appears in the string (that is a use of the @option{-gnatw} - switch), then all further characters in the switch are interpreted - as warning mode modifiers (see description of @option{-gnatw}). - - @item - Once a "V" appears in the string (that is a use of the @option{-gnatV} - switch), then all further characters in the switch are interpreted - as validity checking options (see description of @option{-gnatV}). - - @end itemize - - @node Output and Error Message Control - @subsection Output and Error Message Control - @findex stderr - - @noindent - The standard default format for error messages is called "brief format." - Brief format messages are written to @file{stderr} (the standard error - file) and have the following form: - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:4:20: ";" should be "is" - @end smallexample - - @noindent - The first integer after the file name is the line number in the file, - and the second integer is the column number within the line. - @code{glide} can parse the error messages - and point to the referenced character. - The following switches provide control over the error message - format: - - @table @code - @item -gnatv - @cindex @option{-gnatv} (@code{gcc}) - @findex stdout - The v stands for verbose. - The effect of this setting is to write long-format error - messages to @file{stdout} (the standard output file. - The same program compiled with the - @option{-gnatv} switch would generate: - - @smallexample - @group - @cartouche - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - @end cartouche - @end group - @end smallexample - - @noindent - The vertical bar indicates the location of the error, and the @samp{>>>} - prefix can be used to search for error messages. When this switch is - used the only source lines output are those with errors. - - @item -gnatl - @cindex @option{-gnatl} (@code{gcc}) - The @code{l} stands for list. - This switch causes a full listing of - the file to be generated. The output might look as follows: - - @smallexample - @group - @cartouche - 1. procedure E is - 2. V : Integer; - 3. funcion X (Q : Integer) - | - >>> Incorrect spelling of keyword "function" - 4. return Integer; - | - >>> ";" should be "is" - 5. begin - 6. return Q + Q; - 7. end; - 8. begin - 9. V := X + X; - 10.end E; - @end cartouche - @end group - @end smallexample - - @noindent - @findex stderr - When you specify the @option{-gnatv} or @option{-gnatl} switches and - standard output is redirected, a brief summary is written to - @file{stderr} (standard error) giving the number of error messages and - warning messages generated. - - @item -gnatU - @cindex @option{-gnatU} (@code{gcc}) - This switch forces all error messages to be preceded by the unique - string "error:". This means that error messages take a few more - characters in space, but allows easy searching for and identification - of error messages. - - @item -gnatb - @cindex @option{-gnatb} (@code{gcc}) - The @code{b} stands for brief. - This switch causes GNAT to generate the - brief format error messages to @file{stderr} (the standard error - file) as well as the verbose - format message or full listing (which as usual is written to - @file{stdout} (the standard output file). - - @item -gnatm@var{n} - @cindex @option{-gnatm} (@code{gcc}) - The @code{m} stands for maximum. - @var{n} is a decimal integer in the - range of 1 to 999 and limits the number of error messages to be - generated. For example, using @option{-gnatm2} might yield - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:3:04: Incorrect spelling of keyword "function" - e.adb:5:35: missing ".." - fatal error: maximum errors reached - compilation abandoned - @end smallexample - - @item -gnatf - @cindex @option{-gnatf} (@code{gcc}) - @cindex Error messages, suppressing - The @code{f} stands for full. - Normally, the compiler suppresses error messages that are likely to be - redundant. This switch causes all error - messages to be generated. In particular, in the case of - references to undefined variables. If a given variable is referenced - several times, the normal format of messages is - @smallexample - @iftex - @leftskip=.7cm - @end iftex - e.adb:7:07: "V" is undefined (more references follow) - @end smallexample - - @noindent - where the parenthetical comment warns that there are additional - references to the variable @code{V}. Compiling the same program with the - @option{-gnatf} switch yields - - @smallexample - e.adb:7:07: "V" is undefined - e.adb:8:07: "V" is undefined - e.adb:8:12: "V" is undefined - e.adb:8:16: "V" is undefined - e.adb:9:07: "V" is undefined - e.adb:9:12: "V" is undefined - @end smallexample - - @item -gnatq - @cindex @option{-gnatq} (@code{gcc}) - The @code{q} stands for quit (really "don't quit"). - In normal operation mode, the compiler first parses the program and - determines if there are any syntax errors. If there are, appropriate - error messages are generated and compilation is immediately terminated. - This switch tells - GNAT to continue with semantic analysis even if syntax errors have been - found. This may enable the detection of more errors in a single run. On - the other hand, the semantic analyzer is more likely to encounter some - internal fatal error when given a syntactically invalid tree. - - @item -gnatQ - In normal operation mode, the @file{ali} file is not generated if any - illegalities are detected in the program. The use of @option{-gnatQ} forces - generation of the @file{ali} file. This file is marked as being in - error, so it cannot be used for binding purposes, but it does contain - reasonably complete cross-reference information, and thus may be useful - for use by tools (e.g. semantic browsing tools or integrated development - environments) that are driven from the @file{ali} file. - - In addition, if @option{-gnatt} is also specified, then the tree file is - generated even if there are illegalities. It may be useful in this case - to also specify @option{-gnatq} to ensure that full semantic processing - occurs. The resulting tree file can be processed by ASIS, for the purpose - of providing partial information about illegal units, but if the error - causes the tree to be badly malformed, then ASIS may crash during the - analysis. - - @end table - - @noindent - In addition to error messages, which correspond to illegalities as defined - in the Ada 95 Reference Manual, the compiler detects two kinds of warning - situations. - - @cindex Warning messages - First, the compiler considers some constructs suspicious and generates a - warning message to alert you to a possible error. Second, if the - compiler detects a situation that is sure to raise an exception at - run time, it generates a warning message. The following shows an example - of warning messages: - @smallexample - @iftex - @leftskip=.2cm - @end iftex - e.adb:4:24: warning: creation of object may raise Storage_Error - e.adb:10:17: warning: static value out of range - e.adb:10:17: warning: "Constraint_Error" will be raised at run time - - @end smallexample - - @noindent - GNAT considers a large number of situations as appropriate - for the generation of warning messages. As always, warnings are not - definite indications of errors. For example, if you do an out-of-range - assignment with the deliberate intention of raising a - @code{Constraint_Error} exception, then the warning that may be - issued does not indicate an error. Some of the situations for which GNAT - issues warnings (at least some of the time) are given in the following - list, which is not necessarily complete. - - @itemize @bullet - @item - Possible infinitely recursive calls - - @item - Out-of-range values being assigned - - @item - Possible order of elaboration problems - - @item - Unreachable code - - @item - Fixed-point type declarations with a null range - - @item - Variables that are never assigned a value - - @item - Variables that are referenced before being initialized - - @item - Task entries with no corresponding accept statement - - @item - Duplicate accepts for the same task entry in a select - - @item - Objects that take too much storage - - @item - Unchecked conversion between types of differing sizes - - @item - Missing return statements along some execution paths in a function - - @item - Incorrect (unrecognized) pragmas - - @item - Incorrect external names - - @item - Allocation from empty storage pool - - @item - Potentially blocking operations in protected types - - @item - Suspicious parenthesization of expressions - - @item - Mismatching bounds in an aggregate - - @item - Attempt to return local value by reference - - @item - Unrecognized pragmas - - @item - Premature instantiation of a generic body - - @item - Attempt to pack aliased components - - @item - Out of bounds array subscripts - - @item - Wrong length on string assignment - - @item - Violations of style rules if style checking is enabled - - @item - Unused with clauses - - @item - Bit_Order usage that does not have any effect - - @item - Compile time biased rounding of floating-point constant - - @item - Standard.Duration used to resolve universal fixed expression - - @item - Dereference of possibly null value - - @item - Declaration that is likely to cause storage error - - @item - Internal GNAT unit with'ed by application unit - - @item - Values known to be out of range at compile time - - @item - Unreferenced labels and variables - - @item - Address overlays that could clobber memory - - @item - Unexpected initialization when address clause present - - @item - Bad alignment for address clause - - @item - Useless type conversions - - @item - Redundant assignment statements - - @item - Accidental hiding of name by child unit - - @item - Unreachable code - - @item - Access before elaboration detected at compile time - - @item - A range in a @code{for} loop that is known to be null or might be null - - @end itemize - - @noindent - The following switches are available to control the handling of - warning messages: - - @table @code - @item -gnatwa (activate all optional errors) - @cindex @option{-gnatwa} (@code{gcc}) - This switch activates most optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. The warnings that are not turned on by this - switch are @option{-gnatwb} (biased rounding), - @option{-gnatwd} (implicit dereferencing), - and @option{-gnatwh} (hiding). All other optional warnings are - turned on. - - @item -gnatwA (suppress all optional errors) - @cindex @option{-gnatwA} (@code{gcc}) - This switch suppresses all optional warning messages, see remaining list - in this section for details on optional warning messages that can be - individually controlled. - - @item -gnatwb (activate warnings on biased rounding) - @cindex @option{-gnatwb} (@code{gcc}) - @cindex Rounding, biased - @cindex Biased rounding - If a static floating-point expression has a value that is exactly half - way between two adjacent machine numbers, then the rules of Ada - (Ada Reference Manual, section 4.9(38)) require that this rounding - be done away from zero, even if the normal unbiased rounding rules - at run time would require rounding towards zero. This warning message - alerts you to such instances where compile-time rounding and run-time - rounding are not equivalent. If it is important to get proper run-time - rounding, then you can force this by making one of the operands into - a variable. The default is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwB (suppress warnings on biased rounding) - @cindex @option{-gnatwB} (@code{gcc}) - This switch disables warnings on biased rounding. - - @item -gnatwc (activate warnings on conditionals) - @cindex @option{-gnatwc} (@code{gcc}) - @cindex Conditionals, constant - This switch activates warnings for conditional expressions used in - tests that are known to be True or False at compile time. The default - is that such warnings are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwC (suppress warnings on conditionals) - @cindex @option{-gnatwC} (@code{gcc}) - This switch suppresses warnings for conditional expressions used in - tests that are known to be True or False at compile time. - - @item -gnatwd (activate warnings on implicit dereferencing) - @cindex @option{-gnatwd} (@code{gcc}) - If this switch is set, then the use of a prefix of an access type - in an indexed component, slice, or selected component without an - explicit @code{.all} will generate a warning. With this warning - enabled, access checks occur only at points where an explicit - @code{.all} appears in the source code (assuming no warnings are - generated as a result of this switch). The default is that such - warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of - this warning option. - - @item -gnatwD (suppress warnings on implicit dereferencing) - @cindex @option{-gnatwD} (@code{gcc}) - @cindex Implicit dereferencing - @cindex Dereferencing, implicit - This switch suppresses warnings for implicit deferences in - indexed components, slices, and selected components. - - @item -gnatwe (treat warnings as errors) - @cindex @option{-gnatwe} (@code{gcc}) - @cindex Warnings, treat as error - This switch causes warning messages to be treated as errors. - The warning string still appears, but the warning messages are counted - as errors, and prevent the generation of an object file. - - @item -gnatwf (activate warnings on unreferenced formals) - @cindex @option{-gnatwf} (@code{gcc}) - @cindex Formals, unreferenced - This switch causes a warning to be generated if a formal parameter - is not referenced in the body of the subprogram. This warning can - also be turned on using @option{-gnatwa} or @option{-gnatwu}. - - @item -gnatwF (suppress warnings on unreferenced formals) - @cindex @option{-gnatwF} (@code{gcc}) - This switch suppresses warnings for unreferenced formal - parameters. Note that the - combination @option{-gnatwu} followed by @option{-gnatwF} has the - effect of warning on unreferenced entities other than subprogram - formals. - - @item -gnatwh (activate warnings on hiding) - @cindex @option{-gnatwh} (@code{gcc}) - @cindex Hiding of Declarations - This switch activates warnings on hiding declarations. - A declaration is considered hiding - if it is for a non-overloadable entity, and it declares an entity with the - same name as some other entity that is directly or use-visible. The default - is that such warnings are not generated. - Note that @option{-gnatwa} does not affect the setting of this warning option. - - @item -gnatwH (suppress warnings on hiding) - @cindex @option{-gnatwH} (@code{gcc}) - This switch suppresses warnings on hiding declarations. - - @item -gnatwi (activate warnings on implementation units). - @cindex @option{-gnatwi} (@code{gcc}) - This switch activates warnings for a @code{with} of an internal GNAT - implementation unit, defined as any unit from the @code{Ada}, - @code{Interfaces}, @code{GNAT}, - or @code{System} - hierarchies that is not - documented in either the Ada Reference Manual or the GNAT - Programmer's Reference Manual. Such units are intended only - for internal implementation purposes and should not be @code{with}'ed - by user programs. The default is that such warnings are generated - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwI (disable warnings on implementation units). - @cindex @option{-gnatwI} (@code{gcc}) - This switch disables warnings for a @code{with} of an internal GNAT - implementation unit. - - @item -gnatwl (activate warnings on elaboration pragmas) - @cindex @option{-gnatwl} (@code{gcc}) - @cindex Elaboration, warnings - This switch activates warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. The default is that such warnings - are not generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwL (suppress warnings on elaboration pragmas) - @cindex @option{-gnatwL} (@code{gcc}) - This switch suppresses warnings on missing pragma Elaborate_All statements. - See the section in this guide on elaboration checking for details on - when such pragma should be used. - - @item -gnatwo (activate warnings on address clause overlays) - @cindex @option{-gnatwo} (@code{gcc}) - @cindex Address Clauses, warnings - This switch activates warnings for possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. The default is that such warnings are generated. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwO (suppress warnings on address clause overlays) - @cindex @option{-gnatwO} (@code{gcc}) - This switch suppresses warnings on possibly unintended initialization - effects of defining address clauses that cause one variable to overlap - another. - - @item -gnatwp (activate warnings on ineffective pragma Inlines) - @cindex @option{-gnatwp} (@code{gcc}) - @cindex Inlining, warnings - This switch activates warnings for failure of front end inlining - (activated by @option{-gnatN}) to inline a particular call. There are - many reasons for not being able to inline a call, including most - commonly that the call is too complex to inline. - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwP (suppress warnings on ineffective pragma Inlines) - @cindex @option{-gnatwP} (@code{gcc}) - This switch suppresses warnings on ineffective pragma Inlines. If the - inlining mechanism cannot inline a call, it will simply ignore the - request silently. - - @item -gnatwr (activate warnings on redundant constructs) - @cindex @option{-gnatwr} (@code{gcc}) - This switch activates warnings for redundant constructs. The following - is the current list of constructs regarded as redundant: - This warning can also be turned on using @option{-gnatwa}. - - @itemize @bullet - @item - Assignment of an item to itself. - @item - Type conversion that converts an expression to its own type. - @item - Use of the attribute @code{Base} where @code{typ'Base} is the same - as @code{typ}. - @item - Use of pragma @code{Pack} when all components are placed by a record - representation clause. - @end itemize - - @item -gnatwR (suppress warnings on redundant constructs) - @cindex @option{-gnatwR} (@code{gcc}) - This switch suppresses warnings for redundant constructs. - - @item -gnatws (suppress all warnings) - @cindex @option{-gnatws} (@code{gcc}) - This switch completely suppresses the - output of all warning messages from the GNAT front end. - Note that it does not suppress warnings from the @code{gcc} back end. - To suppress these back end warnings as well, use the switch @code{-w} - in addition to @option{-gnatws}. - - @item -gnatwu (activate warnings on unused entities) - @cindex @option{-gnatwu} (@code{gcc}) - This switch activates warnings to be generated for entities that - are defined but not referenced, and for units that are @code{with}'ed - and not - referenced. In the case of packages, a warning is also generated if - no entities in the package are referenced. This means that if the package - is referenced but the only references are in @code{use} - clauses or @code{renames} - declarations, a warning is still generated. A warning is also generated - for a generic package that is @code{with}'ed but never instantiated. - In the case where a package or subprogram body is compiled, and there - is a @code{with} on the corresponding spec - that is only referenced in the body, - a warning is also generated, noting that the - @code{with} can be moved to the body. The default is that - such warnings are not generated. - This switch also activates warnings on unreferenced formals - (it is includes the effect of @option{-gnatwf}). - This warning can also be turned on using @option{-gnatwa}. - - @item -gnatwU (suppress warnings on unused entities) - @cindex @option{-gnatwU} (@code{gcc}) - This switch suppresses warnings for unused entities and packages. - It also turns off warnings on unreferenced formals (and thus includes - the effect of @option{-gnatwF}). - - @noindent - A string of warning parameters can be used in the same parameter. For example: - - @smallexample - -gnatwaLe - @end smallexample - - @noindent - Would turn on all optional warnings except for elaboration pragma warnings, - and also specify that warnings should be treated as errors. - - @item -w - @cindex @code{-w} - This switch suppresses warnings from the @code{gcc} backend. It may be - used in conjunction with @option{-gnatws} to ensure that all warnings - are suppressed during the entire compilation process. - - @end table - - @node Debugging and Assertion Control - @subsection Debugging and Assertion Control - - @table @code - @item -gnata - @cindex @option{-gnata} (@code{gcc}) - @findex Assert - @findex Debug - @cindex Assertions - - @noindent - The pragmas @code{Assert} and @code{Debug} normally have no effect and - are ignored. This switch, where @samp{a} stands for assert, causes - @code{Assert} and @code{Debug} pragmas to be activated. - - The pragmas have the form: - - @smallexample - @group - @cartouche - @b{pragma} Assert (@var{Boolean-expression} [, - @var{static-string-expression}]) - @b{pragma} Debug (@var{procedure call}) - @end cartouche - @end group - @end smallexample - - @noindent - The @code{Assert} pragma causes @var{Boolean-expression} to be tested. - If the result is @code{True}, the pragma has no effect (other than - possible side effects from evaluating the expression). If the result is - @code{False}, the exception @code{Assert_Failure} declared in the package - @code{System.Assertions} is - raised (passing @var{static-string-expression}, if present, as the - message associated with the exception). If no string expression is - given the default is a string giving the file name and line number - of the pragma. - - The @code{Debug} pragma causes @var{procedure} to be called. Note that - @code{pragma Debug} may appear within a declaration sequence, allowing - debugging procedures to be called between declarations. - - @end table - - @node Validity Checking - @subsection Validity Checking - @findex Validity Checking - - @noindent - The Ada 95 Reference Manual has specific requirements for checking - for invalid values. In particular, RM 13.9.1 requires that the - evaluation of invalid values (for example from unchecked conversions), - not result in erroneous execution. In GNAT, the result of such an - evaluation in normal default mode is to either use the value - unmodified, or to raise Constraint_Error in those cases where use - of the unmodified value would cause erroneous execution. The cases - where unmodified values might lead to erroneous execution are case - statements (where a wild jump might result from an invalid value), - and subscripts on the left hand side (where memory corruption could - occur as a result of an invalid value). - - The @option{-gnatVx} switch allows more control over the validity checking - mode. The @code{x} argument here is a string of letters which control which - validity checks are performed in addition to the default checks described - above. - - @itemize @bullet - @item - @option{-gnatVc} Validity checks for copies - - The right hand side of assignments, and the initializing values of - object declarations are validity checked. - - @item - @option{-gnatVd} Default (RM) validity checks - - Some validity checks are done by default following normal Ada semantics - (RM 13.9.1 (9-11)). - A check is done in case statements that the expression is within the range - of the subtype. If it is not, Constraint_Error is raised. - For assignments to array components, a check is done that the expression used - as index is within the range. If it is not, Constraint_Error is raised. - Both these validity checks may be turned off using switch @option{-gnatVD}. - They are turned on by default. If @option{-gnatVD} is specified, a subsequent - switch @option{-gnatVd} will leave the checks turned on. - Switch @option{-gnatVD} should be used only if you are sure that all such - expressions have valid values. If you use this switch and invalid values - are present, then the program is erroneous, and wild jumps or memory - overwriting may occur. - - @item - @option{-gnatVi} Validity checks for @code{in} mode parameters - - Arguments for parameters of mode @code{in} are validity checked in function - and procedure calls at the point of call. - - @item - @option{-gnatVm} Validity checks for @code{in out} mode parameters - - Arguments for parameters of mode @code{in out} are validity checked in - procedure calls at the point of call. The @code{'m'} here stands for - modify, since this concerns parameters that can be modified by the call. - Note that there is no specific option to test @code{out} parameters, - but any reference within the subprogram will be tested in the usual - manner, and if an invalid value is copied back, any reference to it - will be subject to validity checking. - - @item - @option{-gnatVo} Validity checks for operator and attribute operands - - Arguments for predefined operators and attributes are validity checked. - This includes all operators in package @code{Standard}, - the shift operators defined as intrinsic in package @code{Interfaces} - and operands for attributes such as @code{Pos}. - - @item - @option{-gnatVr} Validity checks for function returns - - The expression in @code{return} statements in functions is validity - checked. - - @item - @option{-gnatVs} Validity checks for subscripts - - All subscripts expressions are checked for validity, whether they appear - on the right side or left side (in default mode only left side subscripts - are validity checked). - - @item - @option{-gnatVt} Validity checks for tests - - Expressions used as conditions in @code{if}, @code{while} or @code{exit} - statements are checked, as well as guard expressions in entry calls. - - @item - @option{-gnatVf} Validity checks for floating-point values - - In the absence of this switch, validity checking occurs only for discrete - values. If @option{-gnatVf} is specified, then validity checking also applies - for floating-point values, and NaN's and infinities are considered invalid, - as well as out of range values for constrained types. Note that this means - that standard @code{IEEE} infinity mode is not allowed. The exact contexts - in which floating-point values are checked depends on the setting of other - options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does - not matter) specifies that floating-point parameters of mode @code{in} should - be validity checked. - - @item - @option{-gnatVa} All validity checks - - All the above validity checks are turned on. That is @option{-gnatVa} is - equivalent to @code{gnatVcdfimorst}. - - @item - @option{-gnatVn} No validity checks - - This switch turns off all validity checking, including the default checking - for case statements and left hand side subscripts. Note that the use of - the switch @option{-gnatp} supresses all run-time checks, including - validity checks, and thus implies @option{-gnatVn}. - - @end itemize - - The @option{-gnatV} switch may be followed by a string of letters to turn on - a series of validity checking options. For example, @option{-gnatVcr} specifies - that in addition to the default validity checking, copies and function - return expressions be validity checked. In order to make it easier to specify - a set of options, the upper case letters @code{CDFIMORST} may be used to turn - off the corresponding lower case option, so for example @option{-gnatVaM} turns - on all validity checking options except for checking of @code{in out} - procedure arguments. - - The specification of additional validity checking generates extra code (and - in the case of @option{-gnatva} the code expansion can be substantial. However, - these additional checks can be very useful in smoking out cases of - uninitialized variables, incorrect use of unchecked conversion, and other - errors leading to invalid values. The use of pragma @code{Initialize_Scalars} - is useful in conjunction with the extra validity checking, since this - ensures that wherever possible uninitialized variables have invalid values. - - See also the pragma @code{Validity_Checks} which allows modification of - the validity checking mode at the program source level, and also allows for - temporary disabling of validity checks. - - @node Style Checking - @subsection Style Checking - @findex Style checking - - @noindent - The -gnaty@var{x} switch causes the compiler to - enforce specified style rules. A limited set of style rules has been used - in writing the GNAT sources themselves. This switch allows user programs - to activate all or some of these checks. If the source program fails a - specified style check, an appropriate warning message is given, preceded by - the character sequence "(style)". - The string @var{x} is a sequence of letters or digits - indicating the particular style - checks to be performed. The following checks are defined: - - @table @code - @item 1-9 (specify indentation level) - If a digit from 1-9 appears in the string after @option{-gnaty} then proper - indentation is checked, with the digit indicating the indentation level - required. The general style of required indentation is as specified by - the examples in the Ada Reference Manual. Full line comments must be - aligned with the @code{--} starting on a column that is a multiple of - the alignment level. - - @item a (check attribute casing) - If the letter a appears in the string after @option{-gnaty} then - attribute names, including the case of keywords such as @code{digits} - used as attributes names, must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item b (blanks not allowed at statement end) - If the letter b appears in the string after @option{-gnaty} then - trailing blanks are not allowed at the end of statements. The purpose of this - rule, together with h (no horizontal tabs), is to enforce a canonical format - for the use of blanks to separate source tokens. - - @item c (check comments) - If the letter c appears in the string after @option{-gnaty} then - comments must meet the following set of rules: - - @itemize @bullet - - @item - The "--" that starts the column must either start in column one, or else - at least one blank must precede this sequence. - - @item - Comments that follow other tokens on a line must have at least one blank - following the "--" at the start of the comment. - - @item - Full line comments must have two blanks following the "--" that starts - the comment, with the following exceptions. - - @item - A line consisting only of the "--" characters, possibly preceded by blanks - is permitted. - - @item - A comment starting with "--x" where x is a special character is permitted. - This alows proper processing of the output generated by specialized tools - including @code{gnatprep} (where --! is used) and the SPARK annnotation - language (where --# is used). For the purposes of this rule, a special - character is defined as being in one of the ASCII ranges - 16#21#..16#2F# or 16#3A#..16#3F#. - - @item - A line consisting entirely of minus signs, possibly preceded by blanks, is - permitted. This allows the construction of box comments where lines of minus - signs are used to form the top and bottom of the box. - - @item - If a comment starts and ends with "--" is permitted as long as at least - one blank follows the initial "--". Together with the preceding rule, - this allows the construction of box comments, as shown in the following - example: - @smallexample - --------------------------- - -- This is a box comment -- - -- with two text lines. -- - --------------------------- - @end smallexample - @end itemize - - @item e (check end/exit labels) - If the letter e appears in the string after @option{-gnaty} then - optional labels on @code{end} statements ending subprograms and on - @code{exit} statements exiting named loops, are required to be present. - - @item f (no form feeds or vertical tabs) - If the letter f appears in the string after @option{-gnaty} then - neither form feeds nor vertical tab characters are not permitted - in the source text. - - @item h (no horizontal tabs) - If the letter h appears in the string after @option{-gnaty} then - horizontal tab characters are not permitted in the source text. - Together with the b (no blanks at end of line) check, this - enforces a canonical form for the use of blanks to separate - source tokens. - - @item i (check if-then layout) - If the letter i appears in the string after @option{-gnaty}, - then the keyword @code{then} must appear either on the same - line as corresponding @code{if}, or on a line on its own, lined - up under the @code{if} with at least one non-blank line in between - containing all or part of the condition to be tested. - - @item k (check keyword casing) - If the letter k appears in the string after @option{-gnaty} then - all keywords must be in lower case (with the exception of keywords - such as @code{digits} used as attribute names to which this check - does not apply). - - @item l (check layout) - If the letter l appears in the string after @option{-gnaty} then - layout of statement and declaration constructs must follow the - recommendations in the Ada Reference Manual, as indicated by the - form of the syntax rules. For example an @code{else} keyword must - be lined up with the corresponding @code{if} keyword. - - There are two respects in which the style rule enforced by this check - option are more liberal than those in the Ada Reference Manual. First - in the case of record declarations, it is permissible to put the - @code{record} keyword on the same line as the @code{type} keyword, and - then the @code{end} in @code{end record} must line up under @code{type}. - For example, either of the following two layouts is acceptable: - - @smallexample - @group - @cartouche - @b{type} q @b{is record} - a : integer; - b : integer; - @b{end record}; - - @b{type} q @b{is} - @b{record} - a : integer; - b : integer; - @b{end record}; - @end cartouche - @end group - @end smallexample - - @noindent - Second, in the case of a block statement, a permitted alternative - is to put the block label on the same line as the @code{declare} or - @code{begin} keyword, and then line the @code{end} keyword up under - the block label. For example both the following are permitted: - - @smallexample - @group - @cartouche - Block : @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - - Block : - @b{declare} - A : Integer := 3; - @b{begin} - Proc (A, A); - @b{end} Block; - @end cartouche - @end group - @end smallexample - - @noindent - The same alternative format is allowed for loops. For example, both of - the following are permitted: - - @smallexample - @group - @cartouche - Clear : @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - - Clear : - @b{while} J < 10 @b{loop} - A (J) := 0; - @b{end loop} Clear; - @end cartouche - @end group - @end smallexample - - @item m (check maximum line length) - If the letter m appears in the string after @option{-gnaty} - then the length of source lines must not exceed 79 characters, including - any trailing blanks. The value of 79 allows convenient display on an - 80 character wide device or window, allowing for possible special - treatment of 80 character lines. - - @item Mnnn (set maximum line length) - If the sequence Mnnn, where nnn is a decimal number, appears in - the string after @option{-gnaty} then the length of lines must not exceed the - given value. - - @item n (check casing of entities in Standard) - If the letter n appears in the string - after @option{-gnaty} then any identifier from Standard must be cased - to match the presentation in the Ada Reference Manual (for example, - @code{Integer} and @code{ASCII.NUL}). - - @item o (check order of subprogram bodies) - If the letter o appears in the string - after @option{-gnaty} then all subprogram bodies in a given scope - (e.g. a package body) must be in alphabetical order. The ordering - rule uses normal Ada rules for comparing strings, ignoring casing - of letters, except that if there is a trailing numeric suffix, then - the value of this suffix is used in the ordering (e.g. Junk2 comes - before Junk10). - - @item p (check pragma casing) - If the letter p appears in the string after @option{-gnaty} then - pragma names must be written in mixed case, that is, the - initial letter and any letter following an underscore must be uppercase. - All other letters must be lowercase. - - @item r (check references) - If the letter r appears in the string after @option{-gnaty} - then all identifier references must be cased in the same way as the - corresponding declaration. No specific casing style is imposed on - identifiers. The only requirement is for consistency of references - with declarations. - - @item s (check separate specs) - If the letter s appears in the string after @option{-gnaty} then - separate declarations ("specs") are required for subprograms (a - body is not allowed to serve as its own declaration). The only - exception is that parameterless library level procedures are - not required to have a separate declaration. This exception covers - the most frequent form of main program procedures. - - @item t (check token spacing) - If the letter t appears in the string after @option{-gnaty} then - the following token spacing rules are enforced: - - @itemize @bullet - - @item - The keywords @code{abs} and @code{not} must be followed by a space. - - @item - The token @code{=>} must be surrounded by spaces. - - @item - The token @code{<>} must be preceded by a space or a left parenthesis. - - @item - Binary operators other than @code{**} must be surrounded by spaces. - There is no restriction on the layout of the @code{**} binary operator. - - @item - Colon must be surrounded by spaces. - - @item - Colon-equal (assignment) must be surrounded by spaces. - - @item - Comma must be the first non-blank character on the line, or be - immediately preceded by a non-blank character, and must be followed - by a space. - - @item - If the token preceding a left paren ends with a letter or digit, then - a space must separate the two tokens. - - @item - A right parenthesis must either be the first non-blank character on - a line, or it must be preceded by a non-blank character. - - @item - A semicolon must not be preceded by a space, and must not be followed by - a non-blank character. - - @item - A unary plus or minus may not be followed by a space. - - @item - A vertical bar must be surrounded by spaces. - @end itemize - - @noindent - In the above rules, appearing in column one is always permitted, that is, - counts as meeting either a requirement for a required preceding space, - or as meeting a requirement for no preceding space. - - Appearing at the end of a line is also always permitted, that is, counts - as meeting either a requirement for a following space, or as meeting - a requirement for no following space. - - @end table - - @noindent - If any of these style rules is violated, a message is generated giving - details on the violation. The initial characters of such messages are - always "(style)". Note that these messages are treated as warning - messages, so they normally do not prevent the generation of an object - file. The @option{-gnatwe} switch can be used to treat warning messages, - including style messages, as fatal errors. - - @noindent - The switch - @option{-gnaty} on its own (that is not followed by any letters or digits), - is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking - options are enabled with - the exception of -gnatyo, - with an indentation level of 3. This is the standard - checking option that is used for the GNAT sources. - - @node Run-Time Checks - @subsection Run-Time Checks - @cindex Division by zero - @cindex Access before elaboration - @cindex Checks, division by zero - @cindex Checks, access before elaboration - - @noindent - If you compile with the default options, GNAT will insert many run-time - checks into the compiled code, including code that performs range - checking against constraints, but not arithmetic overflow checking for - integer operations (including division by zero) or checks for access - before elaboration on subprogram calls. All other run-time checks, as - required by the Ada 95 Reference Manual, are generated by default. - The following @code{gcc} switches refine this default behavior: - - @table @code - @item -gnatp - @cindex @option{-gnatp} (@code{gcc}) - @cindex Suppressing checks - @cindex Checks, suppressing - @findex Suppress - Suppress all run-time checks as though @code{pragma Suppress (all_checks}) - had been present in the source. Validity checks are also suppressed (in - other words @option{-gnatp} also implies @option{-gnatVn}. - Use this switch to improve the performance - of the code at the expense of safety in the presence of invalid data or - program bugs. - - @item -gnato - @cindex @option{-gnato} (@code{gcc}) - @cindex Overflow checks - @cindex Check, overflow - Enables overflow checking for integer operations. - This causes GNAT to generate slower and larger executable - programs by adding code to check for overflow (resulting in raising - @code{Constraint_Error} as required by standard Ada - semantics). These overflow checks correspond to situations in which - the true value of the result of an operation may be outside the base - range of the result type. The following example shows the distinction: - - @smallexample - X1 : Integer := Integer'Last; - X2 : Integer range 1 .. 5 := 5; - ... - X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error - X2 := X2 + 1; -- range check, @option{-gnato} has no effect here - @end smallexample - - @noindent - Here the first addition results in a value that is outside the base range - of Integer, and hence requires an overflow check for detection of the - constraint error. The second increment operation results in a violation - of the explicit range constraint, and such range checks are always - performed. Basically the compiler can assume that in the absence of - the @option{-gnato} switch that any value of type @code{xxx} is - in range of the base type of @code{xxx}. - - @findex Machine_Overflows - Note that the @option{-gnato} switch does not affect the code generated - for any floating-point operations; it applies only to integer - semantics). - For floating-point, GNAT has the @code{Machine_Overflows} - attribute set to @code{False} and the normal mode of operation is to - generate IEEE NaN and infinite values on overflow or invalid operations - (such as dividing 0.0 by 0.0). - - The reason that we distinguish overflow checking from other kinds of - range constraint checking is that a failure of an overflow check can - generate an incorrect value, but cannot cause erroneous behavior. This - is unlike the situation with a constraint check on an array subscript, - where failure to perform the check can result in random memory description, - or the range check on a case statement, where failure to perform the check - can cause a wild jump. - - Note again that @option{-gnato} is off by default, so overflow checking is - not performed in default mode. This means that out of the box, with the - default settings, GNAT does not do all the checks expected from the - language description in the Ada Reference Manual. If you want all constraint - checks to be performed, as described in this Manual, then you must - explicitly use the -gnato switch either on the @code{gnatmake} or - @code{gcc} command. - - @item -gnatE - @cindex @option{-gnatE} (@code{gcc}) - @cindex Elaboration checks - @cindex Check, elaboration - Enables dynamic checks for access-before-elaboration - on subprogram calls and generic instantiations. - For full details of the effect and use of this switch, - @xref{Compiling Using gcc}. - @end table - - @findex Unsuppress - @noindent - The setting of these switches only controls the default setting of the - checks. You may modify them using either @code{Suppress} (to remove - checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in - the program source. - - @node Stack Overflow Checking - @subsection Stack Overflow Checking - @cindex Stack Overflow Checking - @cindex -fstack-check - - @noindent - For most operating systems, @code{gcc} does not perform stack overflow - checking by default. This means that if the main environment task or - some other task exceeds the available stack space, then unpredictable - behavior will occur. - - To activate stack checking, compile all units with the gcc option - @code{-fstack-check}. For example: - - @smallexample - gcc -c -fstack-check package1.adb - @end smallexample - - @noindent - Units compiled with this option will generate extra instructions to check - that any use of the stack (for procedure calls or for declaring local - variables in declare blocks) do not exceed the available stack space. - If the space is exceeded, then a @code{Storage_Error} exception is raised. - - For declared tasks, the stack size is always controlled by the size - given in an applicable @code{Storage_Size} pragma (or is set to - the default size if no pragma is used. - - For the environment task, the stack size depends on - system defaults and is unknown to the compiler. The stack - may even dynamically grow on some systems, precluding the - normal Ada semantics for stack overflow. In the worst case, - unbounded stack usage, causes unbounded stack expansion - resulting in the system running out of virtual memory. - - The stack checking may still work correctly if a fixed - size stack is allocated, but this cannot be guaranteed. - To ensure that a clean exception is signalled for stack - overflow, set the environment variable - @code{GNAT_STACK_LIMIT} to indicate the maximum - stack area that can be used, as in: - @cindex GNAT_STACK_LIMIT - - @smallexample - SET GNAT_STACK_LIMIT 1600 - @end smallexample - - @noindent - The limit is given in kilobytes, so the above declaration would - set the stack limit of the environment task to 1.6 megabytes. - Note that the only purpose of this usage is to limit the amount - of stack used by the environment task. If it is necessary to - increase the amount of stack for the environment task, then this - is an operating systems issue, and must be addressed with the - appropriate operating systems commands. - - @node Run-Time Control - @subsection Run-Time Control - - @table @code - @item -gnatT nnn - @cindex @option{-gnatT} (@code{gcc}) - @cindex Time Slicing - - @noindent - The @code{gnatT} switch can be used to specify the time-slicing value - to be used for task switching between equal priority tasks. The value - @code{nnn} is given in microseconds as a decimal integer. - - Setting the time-slicing value is only effective if the underlying thread - control system can accommodate time slicing. Check the documentation of - your operating system for details. Note that the time-slicing value can - also be set by use of pragma @code{Time_Slice} or by use of the - @code{t} switch in the gnatbind step. The pragma overrides a command - line argument if both are present, and the @code{t} switch for gnatbind - overrides both the pragma and the @code{gcc} command line switch. - @end table - - @node Using gcc for Syntax Checking - @subsection Using @code{gcc} for Syntax Checking - @table @code - @item -gnats - @cindex @option{-gnats} (@code{gcc}) - - @noindent - The @code{s} stands for syntax. - - Run GNAT in syntax checking only mode. For - example, the command - - @smallexample - $ gcc -c -gnats x.adb - @end smallexample - - @noindent - compiles file @file{x.adb} in syntax-check-only mode. You can check a - series of files in a single command - , and can use wild cards to specify such a group of files. - Note that you must specify the @code{-c} (compile - only) flag in addition to the @option{-gnats} flag. - . - - You may use other switches in conjunction with @option{-gnats}. In - particular, @option{-gnatl} and @option{-gnatv} are useful to control the - format of any generated error messages. - - The output is simply the error messages, if any. No object file or ALI - file is generated by a syntax-only compilation. Also, no units other - than the one specified are accessed. For example, if a unit @code{X} - @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax - check only mode does not access the source file containing unit - @code{Y}. - - @cindex Multiple units, syntax checking - Normally, GNAT allows only a single unit in a source file. However, this - restriction does not apply in syntax-check-only mode, and it is possible - to check a file containing multiple compilation units concatenated - together. This is primarily used by the @code{gnatchop} utility - (@pxref{Renaming Files Using gnatchop}). - @end table - - @node Using gcc for Semantic Checking - @subsection Using @code{gcc} for Semantic Checking - @table @code - @item -gnatc - @cindex @option{-gnatc} (@code{gcc}) - - @noindent - The @code{c} stands for check. - Causes the compiler to operate in semantic check mode, - with full checking for all illegalities specified in the - Ada 95 Reference Manual, but without generation of any object code - (no object file is generated). - - Because dependent files must be accessed, you must follow the GNAT - semantic restrictions on file structuring to operate in this mode: - - @itemize @bullet - @item - The needed source files must be accessible - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item - Each file must contain only one compilation unit. - - @item - The file name and unit name must match (@pxref{File Naming Rules}). - @end itemize - - The output consists of error messages as appropriate. No object file is - generated. An @file{ALI} file is generated for use in the context of - cross-reference tools, but this file is marked as not being suitable - for binding (since no object file is generated). - The checking corresponds exactly to the notion of - legality in the Ada 95 Reference Manual. - - Any unit can be compiled in semantics-checking-only mode, including - units that would not normally be compiled (subunits, - and specifications where a separate body is present). - @end table - - @node Compiling Ada 83 Programs - @subsection Compiling Ada 83 Programs - @table @code - @cindex Ada 83 compatibility - @item -gnat83 - @cindex @option{-gnat83} (@code{gcc}) - @cindex ACVC, Ada 83 tests - - @noindent - Although GNAT is primarily an Ada 95 compiler, it accepts this switch to - specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify - this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics - where this can be done easily. - It is not possible to guarantee this switch does a perfect - job; for example, some subtle tests, such as are - found in earlier ACVC tests (that have been removed from the ACVC suite for Ada - 95), may not compile correctly. However, for most purposes, using - this switch should help to ensure that programs that compile correctly - under the @option{-gnat83} switch can be ported easily to an Ada 83 - compiler. This is the main use of the switch. - - With few exceptions (most notably the need to use @code{<>} on - @cindex Generic formal parameters - unconstrained generic formal parameters, the use of the new Ada 95 - keywords, and the use of packages - with optional bodies), it is not necessary to use the - @option{-gnat83} switch when compiling Ada 83 programs, because, with rare - exceptions, Ada 95 is upwardly compatible with Ada 83. This - means that a correct Ada 83 program is usually also a correct Ada 95 - program. - - @end table - - @node Character Set Control - @subsection Character Set Control - @table @code - @item -gnati@var{c} - @cindex @code{-gnati} (@code{gcc}) - - @noindent - Normally GNAT recognizes the Latin-1 character set in source program - identifiers, as described in the Ada 95 Reference Manual. - This switch causes - GNAT to recognize alternate character sets in identifiers. @var{c} is a - single character indicating the character set, as follows: - - @table @code - @item 1 - Latin-1 identifiers - - @item 2 - Latin-2 letters allowed in identifiers - - @item 3 - Latin-3 letters allowed in identifiers - - @item 4 - Latin-4 letters allowed in identifiers - - @item 5 - Latin-5 (Cyrillic) letters allowed in identifiers - - @item 9 - Latin-9 letters allowed in identifiers - - @item p - IBM PC letters (code page 437) allowed in identifiers - - @item 8 - IBM PC letters (code page 850) allowed in identifiers - - @item f - Full upper-half codes allowed in identifiers - - @item n - No upper-half codes allowed in identifiers - - @item w - Wide-character codes (that is, codes greater than 255) - allowed in identifiers - @end table - - @xref{Foreign Language Representation}, for full details on the - implementation of these character sets. - - @item -gnatW@var{e} - @cindex @code{-gnatW} (@code{gcc}) - Specify the method of encoding for wide characters. - @var{e} is one of the following: - - @table @code - - @item h - Hex encoding (brackets coding also recognized) - - @item u - Upper half encoding (brackets encoding also recognized) - - @item s - Shift/JIS encoding (brackets encoding also recognized) - - @item e - EUC encoding (brackets encoding also recognized) - - @item 8 - UTF-8 encoding (brackets encoding also recognized) - - @item b - Brackets encoding only (default value) - @end table - For full details on the these encoding - methods see @xref{Wide Character Encodings}. - Note that brackets coding is always accepted, even if one of the other - options is specified, so for example @option{-gnatW8} specifies that both - brackets and @code{UTF-8} encodings will be recognized. The units that are - with'ed directly or indirectly will be scanned using the specified - representation scheme, and so if one of the non-brackets scheme is - used, it must be used consistently throughout the program. However, - since brackets encoding is always recognized, it may be conveniently - used in standard libraries, allowing these libraries to be used with - any of the available coding schemes. - scheme. If no @option{-gnatW?} parameter is present, then the default - representation is Brackets encoding only. - - Note that the wide character representation that is specified (explicitly - or by default) for the main program also acts as the default encoding used - for Wide_Text_IO files if not specifically overridden by a WCEM form - parameter. - - @end table - @node File Naming Control - @subsection File Naming Control - - @table @code - @item -gnatk@var{n} - @cindex @option{-gnatk} (@code{gcc}) - Activates file name "krunching". @var{n}, a decimal integer in the range - 1-999, indicates the maximum allowable length of a file name (not - including the @file{.ads} or @file{.adb} extension). The default is not - to enable file name krunching. - - For the source file naming rules, @xref{File Naming Rules}. - @end table - - @node Subprogram Inlining Control - @subsection Subprogram Inlining Control - - @table @code - @item -gnatn - @cindex @option{-gnatn} (@code{gcc}) - The @code{n} here is intended to suggest the first syllable of the - word "inline". - GNAT recognizes and processes @code{Inline} pragmas. However, for the - inlining to actually occur, optimization must be enabled. To enable - inlining across unit boundaries, this is, inlining a call in one unit of - a subprogram declared in a @code{with}'ed unit, you must also specify - this switch. - In the absence of this switch, GNAT does not attempt - inlining across units and does not need to access the bodies of - subprograms for which @code{pragma Inline} is specified if they are not - in the current unit. - - If you specify this switch the compiler will access these bodies, - creating an extra source dependency for the resulting object file, and - where possible, the call will be inlined. - For further details on when inlining is possible - see @xref{Inlining of Subprograms}. - - @item -gnatN - @cindex @option{-gnatN} (@code{gcc}) - The front end inlining activated by this switch is generally more extensive, - and quite often more effective than the standard @option{-gnatn} inlining mode. - It will also generate additional dependencies. - - @end table - - @node Auxiliary Output Control - @subsection Auxiliary Output Control - - @table @code - @item -gnatt - @cindex @option{-gnatt} (@code{gcc}) - @cindex Writing internal trees - @cindex Internal trees, writing to file - Causes GNAT to write the internal tree for a unit to a file (with the - extension @file{.adt}. - This not normally required, but is used by separate analysis tools. - Typically - these tools do the necessary compilations automatically, so you should - not have to specify this switch in normal operation. - - @item -gnatu - @cindex @option{-gnatu} (@code{gcc}) - Print a list of units required by this compilation on @file{stdout}. - The listing includes all units on which the unit being compiled depends - either directly or indirectly. - - @item -pass-exit-codes - @cindex @code{-pass-exit-codes} (@code{gcc}) - If this switch is not used, the exit code returned by @code{gcc} when - compiling multiple files indicates whether all source files have - been successfully used to generate object files or not. - - When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended - exit status and allows an integrated development environment to better - react to a compilation failure. Those exit status are: - - @table @asis - @item 5 - There was an error in at least one source file. - @item 3 - At least one source file did not generate an object file. - @item 2 - The compiler died unexpectedly (internal error for example). - @item 0 - An object file has been generated for every source file. - @end table - @end table - - @node Debugging Control - @subsection Debugging Control - - @table @code - @cindex Debugging options - @item -gnatd@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - outputs desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Debug} unit in the compiler source - file @file{debug.adb}. - - @item -gnatG - @cindex @option{-gnatG} (@code{gcc}) - This switch causes the compiler to generate auxiliary output containing - a pseudo-source listing of the generated expanded code. Like most Ada - compilers, GNAT works by first transforming the high level Ada code into - lower level constructs. For example, tasking operations are transformed - into calls to the tasking run-time routines. A unique capability of GNAT - is to list this expanded code in a form very close to normal Ada source. - This is very useful in understanding the implications of various Ada - usage on the efficiency of the generated code. There are many cases in - Ada (e.g. the use of controlled types), where simple Ada statements can - generate a lot of run-time code. By using @option{-gnatG} you can identify - these cases, and consider whether it may be desirable to modify the coding - approach to improve efficiency. - - The format of the output is very similar to standard Ada source, and is - easily understood by an Ada programmer. The following special syntactic - additions correspond to low level features used in the generated code that - do not have any exact analogies in pure Ada source form. The following - is a partial list of these special constructions. See the specification - of package @code{Sprint} in file @file{sprint.ads} for a full list. - - @table @code - @item new @var{xxx} [storage_pool = @var{yyy}] - Shows the storage pool being used for an allocator. - - @item at end @var{procedure-name}; - Shows the finalization (cleanup) procedure for a scope. - - @item (if @var{expr} then @var{expr} else @var{expr}) - Conditional expression equivalent to the @code{x?y:z} construction in C. - - @item @var{target}^(@var{source}) - A conversion with floating-point truncation instead of rounding. - - @item @var{target}?(@var{source}) - A conversion that bypasses normal Ada semantic checking. In particular - enumeration types and fixed-point types are treated simply as integers. - - @item @var{target}?^(@var{source}) - Combines the above two cases. - - @item @var{x} #/ @var{y} - @itemx @var{x} #mod @var{y} - @itemx @var{x} #* @var{y} - @itemx @var{x} #rem @var{y} - A division or multiplication of fixed-point values which are treated as - integers without any kind of scaling. - - @item free @var{expr} [storage_pool = @var{xxx}] - Shows the storage pool associated with a @code{free} statement. - - @item freeze @var{typename} [@var{actions}] - Shows the point at which @var{typename} is frozen, with possible - associated actions to be performed at the freeze point. - - @item reference @var{itype} - Reference (and hence definition) to internal type @var{itype}. - - @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) - Intrinsic function call. - - @item @var{labelname} : label - Declaration of label @var{labelname}. - - @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr} - A multiple concatenation (same effect as @var{expr} & @var{expr} & - @var{expr}, but handled more efficiently). - - @item [constraint_error] - Raise the @code{Constraint_Error} exception. - - @item @var{expression}'reference - A pointer to the result of evaluating @var{expression}. - - @item @var{target-type}!(@var{source-expression}) - An unchecked conversion of @var{source-expression} to @var{target-type}. - - @item [@var{numerator}/@var{denominator}] - Used to represent internal real literals (that) have no exact - representation in base 2-16 (for example, the result of compile time - evaluation of the expression 1.0/27.0). - - @item -gnatD - @cindex @option{-gnatD} (@code{gcc}) - This switch is used in conjunction with @option{-gnatG} to cause the expanded - source, as described above to be written to files with names - @file{xxx.dg}, where @file{xxx} is the normal file name, - for example, if the source file name is @file{hello.adb}, - then a file @file{hello.adb.dg} will be written. - The debugging information generated - by the @code{gcc} @code{-g} switch will refer to the generated - @file{xxx.dg} file. This allows you to do source level debugging using - the generated code which is sometimes useful for complex code, for example - to find out exactly which part of a complex construction raised an - exception. This switch also suppress generation of cross-reference - information (see -gnatx). - - @item -gnatC - @cindex @option{-gnatE} (@code{gcc}) - In the generated debugging information, and also in the case of long external - names, the compiler uses a compression mechanism if the name is very long. - This compression method uses a checksum, and avoids trouble on some operating - systems which have difficulty with very long names. The @option{-gnatC} switch - forces this compression approach to be used on all external names and names - in the debugging information tables. This reduces the size of the generated - executable, at the expense of making the naming scheme more complex. The - compression only affects the qualification of the name. Thus a name in - the source: - - @smallexample - Very_Long_Package.Very_Long_Inner_Package.Var - @end smallexample - - @noindent - would normally appear in these tables as: - - @smallexample - very_long_package__very_long_inner_package__var - @end smallexample - - @noindent - but if the @option{-gnatC} switch is used, then the name appears as - - @smallexample - XCb7e0c705__var - @end smallexample - - @noindent - Here b7e0c705 is a compressed encoding of the qualification prefix. - The GNAT Ada aware version of GDB understands these encoded prefixes, so if this - debugger is used, the encoding is largely hidden from the user of the compiler. - - @end table - - @item -gnatR[0|1|2|3][s] - @cindex @option{-gnatR} (@code{gcc}) - This switch controls output from the compiler of a listing showing - representation information for declared types and objects. For - @option{-gnatR0}, no information is output (equivalent to omitting - the @option{-gnatR} switch). For @option{-gnatR1} (which is the default, - so @option{-gnatR} with no parameter has the same effect), size and alignment - information is listed for declared array and record types. For - @option{-gnatR2}, size and alignment information is listed for all - expression information for values that are computed at run time for - variant records. These symbolic expressions have a mostly obvious - format with #n being used to represent the value of the n'th - discriminant. See source files @file{repinfo.ads/adb} in the - @code{GNAT} sources for full detalis on the format of @option{-gnatR3} - output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then - the output is to a file with the name @file{file.rep} where - file is the name of the corresponding source file. - - @item -gnatx - @cindex @option{-gnatx} (@code{gcc}) - Normally the compiler generates full cross-referencing information in - the @file{ALI} file. This information is used by a number of tools, - including @code{gnatfind} and @code{gnatxref}. The -gnatx switch - suppresses this information. This saves some space and may slightly - speed up compilation, but means that these tools cannot be used. - @end table - - @node Units to Sources Mapping Files - @subsection Units to Sources Mapping Files - - @table @code - - @item -gnatem@var{path} - @cindex @option{-gnatem} (@code{gcc}) - A mapping file is a way to communicate to the compiler two mappings: - from unit names to file names (without any directory information) and from - file names to path names (with full directory information). These mappings - are used by the compiler to short-circuit the path search. - - A mapping file is a sequence of sets of three lines. In each set, - the first line is the unit name, in lower case, with "%s" appended for - specifications and "%b" appended for bodies; the second line is the file - name; and the third line is the path name. - - Example: - @smallexample - main%b - main.2.ada - /gnat/project1/sources/main.2.ada - @end smallexample - - When the switch @option{-gnatem} is specified, the compiler will create - in memory the two mappings from the specified file. If there is any problem - (non existent file, truncated file or duplicate entries), no mapping - will be created. - - Several @option{-gnatem} switches may be specified; however, only the last - one on the command line will be taken into account. - - When using a project file, @code{gnatmake} create a temporary mapping file - and communicates it to the compiler using this switch. - - @end table - - @node Search Paths and the Run-Time Library (RTL) - @section Search Paths and the Run-Time Library (RTL) - - @noindent - With the GNAT source-based library system, the compiler must be able to - find source files for units that are needed by the unit being compiled. - Search paths are used to guide this process. - - The compiler compiles one source file whose name must be given - explicitly on the command line. In other words, no searching is done - for this file. To find all other source files that are needed (the most - common being the specs of units), the compiler examines the following - directories, in the following order: - - @enumerate - @item - The directory containing the source file of the main unit being compiled - (the file name on the command line). - - @item - Each directory named by an @code{-I} switch given on the @code{gcc} - command line, in the order given. - - @item - @findex ADA_INCLUDE_PATH - Each of the directories listed in the value of the - @code{ADA_INCLUDE_PATH} environment variable. - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version). - @item - The content of the "ada_source_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) source files. - @ref{Installing an Ada Library} - @end enumerate - - @noindent - Specifying the switch @code{-I-} - inhibits the use of the directory - containing the source file named in the command line. You can still - have this directory on your search path, but in this case it must be - explicitly requested with a @code{-I} switch. - - Specifying the switch @code{-nostdinc} - inhibits the search of the default location for the GNAT Run Time - Library (RTL) source files. - - The compiler outputs its object files and ALI files in the current - working directory. - Caution: The object file can be redirected with the @code{-o} switch; - however, @code{gcc} and @code{gnat1} have not been coordinated on this - so the ALI file will not go to the right place. Therefore, you should - avoid using the @code{-o} switch. - - @findex System.IO - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT RTL, together with the simple @code{System.IO} - package used in the "Hello World" example. The sources for these units - are needed by the compiler and are kept together in one directory. Not - all of the bodies are needed, but all of the sources are kept together - anyway. In a normal installation, you need not specify these directory - names when compiling or binding. Either the environment variables or - the built-in defaults cause these files to be found. - - In addition to the language-defined hierarchies (System, Ada and - Interfaces), the GNAT distribution provides a fourth hierarchy, - consisting of child units of GNAT. This is a collection of generally - useful routines. See the GNAT Reference Manual for further details. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Order of Compilation Issues - @section Order of Compilation Issues - - @noindent - If, in our earlier example, there was a spec for the @code{hello} - procedure, it would be contained in the file @file{hello.ads}; yet this - file would not have to be explicitly compiled. This is the result of the - model we chose to implement library management. Some of the consequences - of this model are as follows: - - @itemize @bullet - @item - There is no point in compiling specs (except for package - specs with no bodies) because these are compiled as needed by clients. If - you attempt a useless compilation, you will receive an error message. - It is also useless to compile subunits because they are compiled as needed - by the parent. - - @item - There are no order of compilation requirements: performing a - compilation never obsoletes anything. The only way you can obsolete - something and require recompilations is to modify one of the - source files on which it depends. - - @item - There is no library as such, apart from the ALI files - (@pxref{The Ada Library Information Files}, for information on the format of these - files). For now we find it convenient to create separate ALI files, but - eventually the information therein may be incorporated into the object - file directly. - - @item - When you compile a unit, the source files for the specs of all units - that it @code{with}'s, all its subunits, and the bodies of any generics it - instantiates must be available (reachable by the search-paths mechanism - described above), or you will receive a fatal error message. - @end itemize - - @node Examples - @section Examples - - @noindent - The following are some typical Ada compilation command line examples: - - @table @code - @item $ gcc -c xyz.adb - Compile body in file @file{xyz.adb} with all default options. - - @item $ gcc -c -O2 -gnata xyz-def.adb - - Compile the child unit package in file @file{xyz-def.adb} with extensive - optimizations, and pragma @code{Assert}/@code{Debug} statements - enabled. - - @item $ gcc -c -gnatc abc-def.adb - Compile the subunit in file @file{abc-def.adb} in semantic-checking-only - mode. - @end table - - @node Binding Using gnatbind - @chapter Binding Using @code{gnatbind} - @findex gnatbind - - @menu - * Running gnatbind:: - * Generating the Binder Program in C:: - * Consistency-Checking Modes:: - * Binder Error Message Control:: - * Elaboration Control:: - * Output Control:: - * Binding with Non-Ada Main Programs:: - * Binding Programs with No Main Subprogram:: - * Summary of Binder Switches:: - * Command-Line Access:: - * Search Paths for gnatbind:: - * Examples of gnatbind Usage:: - @end menu - - @noindent - This chapter describes the GNAT binder, @code{gnatbind}, which is used - to bind compiled GNAT objects. The @code{gnatbind} program performs - four separate functions: - - @enumerate - @item - Checks that a program is consistent, in accordance with the rules in - Chapter 10 of the Ada 95 Reference Manual. In particular, error - messages are generated if a program uses inconsistent versions of a - given unit. - - @item - Checks that an acceptable order of elaboration exists for the program - and issues an error message if it cannot find an order of elaboration - that satisfies the rules in Chapter 10 of the Ada 95 Language Manual. - - @item - Generates a main program incorporating the given elaboration order. - This program is a small Ada package (body and spec) that - must be subsequently compiled - using the GNAT compiler. The necessary compilation step is usually - performed automatically by @code{gnatlink}. The two most important - functions of this program - are to call the elaboration routines of units in an appropriate order - and to call the main program. - - @item - Determines the set of object files required by the given main program. - This information is output in the forms of comments in the generated program, - to be read by the @code{gnatlink} utility used to link the Ada application. - @end enumerate - - @node Running gnatbind - @section Running @code{gnatbind} - - @noindent - The form of the @code{gnatbind} command is - - @smallexample - $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}] - @end smallexample - - @noindent - where @var{mainprog}.adb is the Ada file containing the main program - unit body. If no switches are specified, @code{gnatbind} constructs an Ada - package in two files which names are - @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}. - For example, if given the - parameter @samp{hello.ali}, for a main program contained in file - @file{hello.adb}, the binder output files would be @file{b~hello.ads} - and @file{b~hello.adb}. - - When doing consistency checking, the binder takes into consideration - any source files it can locate. For example, if the binder determines - that the given main program requires the package @code{Pack}, whose - @file{.ali} - file is @file{pack.ali} and whose corresponding source spec file is - @file{pack.ads}, it attempts to locate the source file @file{pack.ads} - (using the same search path conventions as previously described for the - @code{gcc} command). If it can locate this source file, it checks that - the time stamps - or source checksums of the source and its references to in @file{ali} files - match. In other words, any @file{ali} files that mentions this spec must have - resulted from compiling this version of the source file (or in the case - where the source checksums match, a version close enough that the - difference does not matter). - - @cindex Source files, use by binder - The effect of this consistency checking, which includes source files, is - that the binder ensures that the program is consistent with the latest - version of the source files that can be located at bind time. Editing a - source file without compiling files that depend on the source file cause - error messages to be generated by the binder. - - For example, suppose you have a main program @file{hello.adb} and a - package @code{P}, from file @file{p.ads} and you perform the following - steps: - - @enumerate - @item - Enter @code{gcc -c hello.adb} to compile the main program. - - @item - Enter @code{gcc -c p.ads} to compile package @code{P}. - - @item - Edit file @file{p.ads}. - - @item - Enter @code{gnatbind hello}. - @end enumerate - - At this point, the file @file{p.ali} contains an out-of-date time stamp - because the file @file{p.ads} has been edited. The attempt at binding - fails, and the binder generates the following error messages: - - @smallexample - error: "hello.adb" must be recompiled ("p.ads" has been modified) - error: "p.ads" has been modified and must be recompiled - @end smallexample - - @noindent - Now both files must be recompiled as indicated, and then the bind can - succeed, generating a main program. You need not normally be concerned - with the contents of this file, but it is similar to the following which - is the binder file generated for a simple "hello world" program. - - @smallexample - @iftex - @leftskip=0cm - @end iftex - -- The package is called Ada_Main unless this name is actually used - -- as a unit name in the partition, in which case some other unique - -- name is used. - - with System; - package ada_main is - - Elab_Final_Code : Integer; - pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); - - -- The main program saves the parameters (argument count, - -- argument values, environment pointer) in global variables - -- for later access by other units including - -- Ada.Command_Line. - - gnat_argc : Integer; - gnat_argv : System.Address; - gnat_envp : System.Address; - - -- The actual variables are stored in a library routine. This - -- is useful for some shared library situations, where there - -- are problems if variables are not in the library. - - pragma Import (C, gnat_argc); - pragma Import (C, gnat_argv); - pragma Import (C, gnat_envp); - - -- The exit status is similarly an external location - - gnat_exit_status : Integer; - pragma Import (C, gnat_exit_status); - - GNAT_Version : constant String := - "GNAT Version: 3.15w (20010315)"; - pragma Export (C, GNAT_Version, "__gnat_version"); - - -- This is the generated adafinal routine that performs - -- finalization at the end of execution. In the case where - -- Ada is the main program, this main program makes a call - -- to adafinal at program termination. - - procedure adafinal; - pragma Export (C, adafinal, "adafinal"); - - -- This is the generated adainit routine that performs - -- initialization at the start of execution. In the case - -- where Ada is the main program, this main program makes - -- a call to adainit at program startup. - - procedure adainit; - pragma Export (C, adainit, "adainit"); - - -- This routine is called at the start of execution. It is - -- a dummy routine that is used by the debugger to breakpoint - -- at the start of execution. - - procedure Break_Start; - pragma Import (C, Break_Start, "__gnat_break_start"); - - -- This is the actual generated main program (it would be - -- suppressed if the no main program switch were used). As - -- required by standard system conventions, this program has - -- the external name main. - - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer; - pragma Export (C, main, "main"); - - -- The following set of constants give the version - -- identification values for every unit in the bound - -- partition. This identification is computed from all - -- dependent semantic units, and corresponds to the - -- string that would be returned by use of the - -- Body_Version or Version attributes. - - type Version_32 is mod 2 ** 32; - u00001 : constant Version_32 := 16#7880BEB3#; - u00002 : constant Version_32 := 16#0D24CBD0#; - u00003 : constant Version_32 := 16#3283DBEB#; - u00004 : constant Version_32 := 16#2359F9ED#; - u00005 : constant Version_32 := 16#664FB847#; - u00006 : constant Version_32 := 16#68E803DF#; - u00007 : constant Version_32 := 16#5572E604#; - u00008 : constant Version_32 := 16#46B173D8#; - u00009 : constant Version_32 := 16#156A40CF#; - u00010 : constant Version_32 := 16#033DABE0#; - u00011 : constant Version_32 := 16#6AB38FEA#; - u00012 : constant Version_32 := 16#22B6217D#; - u00013 : constant Version_32 := 16#68A22947#; - u00014 : constant Version_32 := 16#18CC4A56#; - u00015 : constant Version_32 := 16#08258E1B#; - u00016 : constant Version_32 := 16#367D5222#; - u00017 : constant Version_32 := 16#20C9ECA4#; - u00018 : constant Version_32 := 16#50D32CB6#; - u00019 : constant Version_32 := 16#39A8BB77#; - u00020 : constant Version_32 := 16#5CF8FA2B#; - u00021 : constant Version_32 := 16#2F1EB794#; - u00022 : constant Version_32 := 16#31AB6444#; - u00023 : constant Version_32 := 16#1574B6E9#; - u00024 : constant Version_32 := 16#5109C189#; - u00025 : constant Version_32 := 16#56D770CD#; - u00026 : constant Version_32 := 16#02F9DE3D#; - u00027 : constant Version_32 := 16#08AB6B2C#; - u00028 : constant Version_32 := 16#3FA37670#; - u00029 : constant Version_32 := 16#476457A0#; - u00030 : constant Version_32 := 16#731E1B6E#; - u00031 : constant Version_32 := 16#23C2E789#; - u00032 : constant Version_32 := 16#0F1BD6A1#; - u00033 : constant Version_32 := 16#7C25DE96#; - u00034 : constant Version_32 := 16#39ADFFA2#; - u00035 : constant Version_32 := 16#571DE3E7#; - u00036 : constant Version_32 := 16#5EB646AB#; - u00037 : constant Version_32 := 16#4249379B#; - u00038 : constant Version_32 := 16#0357E00A#; - u00039 : constant Version_32 := 16#3784FB72#; - u00040 : constant Version_32 := 16#2E723019#; - u00041 : constant Version_32 := 16#623358EA#; - u00042 : constant Version_32 := 16#107F9465#; - u00043 : constant Version_32 := 16#6843F68A#; - u00044 : constant Version_32 := 16#63305874#; - u00045 : constant Version_32 := 16#31E56CE1#; - u00046 : constant Version_32 := 16#02917970#; - u00047 : constant Version_32 := 16#6CCBA70E#; - u00048 : constant Version_32 := 16#41CD4204#; - u00049 : constant Version_32 := 16#572E3F58#; - u00050 : constant Version_32 := 16#20729FF5#; - u00051 : constant Version_32 := 16#1D4F93E8#; - u00052 : constant Version_32 := 16#30B2EC3D#; - u00053 : constant Version_32 := 16#34054F96#; - u00054 : constant Version_32 := 16#5A199860#; - u00055 : constant Version_32 := 16#0E7F912B#; - u00056 : constant Version_32 := 16#5760634A#; - u00057 : constant Version_32 := 16#5D851835#; - - -- The following Export pragmas export the version numbers - -- with symbolic names ending in B (for body) or S - -- (for spec) so that they can be located in a link. The - -- information provided here is sufficient to track down - -- the exact versions of units used in a given build. - - pragma Export (C, u00001, "helloB"); - pragma Export (C, u00002, "system__standard_libraryB"); - pragma Export (C, u00003, "system__standard_libraryS"); - pragma Export (C, u00004, "adaS"); - pragma Export (C, u00005, "ada__text_ioB"); - pragma Export (C, u00006, "ada__text_ioS"); - pragma Export (C, u00007, "ada__exceptionsB"); - pragma Export (C, u00008, "ada__exceptionsS"); - pragma Export (C, u00009, "gnatS"); - pragma Export (C, u00010, "gnat__heap_sort_aB"); - pragma Export (C, u00011, "gnat__heap_sort_aS"); - pragma Export (C, u00012, "systemS"); - pragma Export (C, u00013, "system__exception_tableB"); - pragma Export (C, u00014, "system__exception_tableS"); - pragma Export (C, u00015, "gnat__htableB"); - pragma Export (C, u00016, "gnat__htableS"); - pragma Export (C, u00017, "system__exceptionsS"); - pragma Export (C, u00018, "system__machine_state_operationsB"); - pragma Export (C, u00019, "system__machine_state_operationsS"); - pragma Export (C, u00020, "system__machine_codeS"); - pragma Export (C, u00021, "system__storage_elementsB"); - pragma Export (C, u00022, "system__storage_elementsS"); - pragma Export (C, u00023, "system__secondary_stackB"); - pragma Export (C, u00024, "system__secondary_stackS"); - pragma Export (C, u00025, "system__parametersB"); - pragma Export (C, u00026, "system__parametersS"); - pragma Export (C, u00027, "system__soft_linksB"); - pragma Export (C, u00028, "system__soft_linksS"); - pragma Export (C, u00029, "system__stack_checkingB"); - pragma Export (C, u00030, "system__stack_checkingS"); - pragma Export (C, u00031, "system__tracebackB"); - pragma Export (C, u00032, "system__tracebackS"); - pragma Export (C, u00033, "ada__streamsS"); - pragma Export (C, u00034, "ada__tagsB"); - pragma Export (C, u00035, "ada__tagsS"); - pragma Export (C, u00036, "system__string_opsB"); - pragma Export (C, u00037, "system__string_opsS"); - pragma Export (C, u00038, "interfacesS"); - pragma Export (C, u00039, "interfaces__c_streamsB"); - pragma Export (C, u00040, "interfaces__c_streamsS"); - pragma Export (C, u00041, "system__file_ioB"); - pragma Export (C, u00042, "system__file_ioS"); - pragma Export (C, u00043, "ada__finalizationB"); - pragma Export (C, u00044, "ada__finalizationS"); - pragma Export (C, u00045, "system__finalization_rootB"); - pragma Export (C, u00046, "system__finalization_rootS"); - pragma Export (C, u00047, "system__finalization_implementationB"); - pragma Export (C, u00048, "system__finalization_implementationS"); - pragma Export (C, u00049, "system__string_ops_concat_3B"); - pragma Export (C, u00050, "system__string_ops_concat_3S"); - pragma Export (C, u00051, "system__stream_attributesB"); - pragma Export (C, u00052, "system__stream_attributesS"); - pragma Export (C, u00053, "ada__io_exceptionsS"); - pragma Export (C, u00054, "system__unsigned_typesS"); - pragma Export (C, u00055, "system__file_control_blockS"); - pragma Export (C, u00056, "ada__finalization__list_controllerB"); - pragma Export (C, u00057, "ada__finalization__list_controllerS"); - - -- BEGIN ELABORATION ORDER - -- ada (spec) - -- gnat (spec) - -- gnat.heap_sort_a (spec) - -- gnat.heap_sort_a (body) - -- gnat.htable (spec) - -- gnat.htable (body) - -- interfaces (spec) - -- system (spec) - -- system.machine_code (spec) - -- system.parameters (spec) - -- system.parameters (body) - -- interfaces.c_streams (spec) - -- interfaces.c_streams (body) - -- system.standard_library (spec) - -- ada.exceptions (spec) - -- system.exception_table (spec) - -- system.exception_table (body) - -- ada.io_exceptions (spec) - -- system.exceptions (spec) - -- system.storage_elements (spec) - -- system.storage_elements (body) - -- system.machine_state_operations (spec) - -- system.machine_state_operations (body) - -- system.secondary_stack (spec) - -- system.stack_checking (spec) - -- system.soft_links (spec) - -- system.soft_links (body) - -- system.stack_checking (body) - -- system.secondary_stack (body) - -- system.standard_library (body) - -- system.string_ops (spec) - -- system.string_ops (body) - -- ada.tags (spec) - -- ada.tags (body) - -- ada.streams (spec) - -- system.finalization_root (spec) - -- system.finalization_root (body) - -- system.string_ops_concat_3 (spec) - -- system.string_ops_concat_3 (body) - -- system.traceback (spec) - -- system.traceback (body) - -- ada.exceptions (body) - -- system.unsigned_types (spec) - -- system.stream_attributes (spec) - -- system.stream_attributes (body) - -- system.finalization_implementation (spec) - -- system.finalization_implementation (body) - -- ada.finalization (spec) - -- ada.finalization (body) - -- ada.finalization.list_controller (spec) - -- ada.finalization.list_controller (body) - -- system.file_control_block (spec) - -- system.file_io (spec) - -- system.file_io (body) - -- ada.text_io (spec) - -- ada.text_io (body) - -- hello (body) - -- END ELABORATION ORDER - - end ada_main; - - -- The following source file name pragmas allow the generated file - -- names to be unique for different main programs. They are needed - -- since the package name will always be Ada_Main. - - pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads"); - pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb"); - - -- Generated package body for Ada_Main starts here - - package body ada_main is - - -- The actual finalization is performed by calling the - -- library routine in System.Standard_Library.Adafinal - - procedure Do_Finalize; - pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); - - ------------- - -- adainit -- - ------------- - - @findex adainit - procedure adainit is - - -- These booleans are set to True once the associated unit has - -- been elaborated. It is also used to avoid elaborating the - -- same unit twice. - - E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E"); - E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E"); - E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E"); - E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E"); - E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E"); - E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E"); - E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E"); - E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E"); - E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E"); - E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E"); - E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E"); - E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E"); - E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E"); - E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E"); - E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E"); - E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E"); - E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E"); - - -- Set_Globals is a library routine that stores away the - -- value of the indicated set of global values in global - -- variables within the library. - - procedure Set_Globals - (Main_Priority : Integer; - Time_Slice_Value : Integer; - WC_Encoding : Character; - Locking_Policy : Character; - Queuing_Policy : Character; - Task_Dispatching_Policy : Character; - Adafinal : System.Address; - Unreserve_All_Interrupts : Integer; - Exception_Tracebacks : Integer); - @findex __gnat_set_globals - pragma Import (C, Set_Globals, "__gnat_set_globals"); - - -- SDP_Table_Build is a library routine used to build the - -- exception tables. See unit Ada.Exceptions in files - -- a-except.ads/adb for full details of how zero cost - -- exception handling works. This procedure, the call to - -- it, and the two following tables are all omitted if the - -- build is in longjmp/setjump exception mode. - - @findex SDP_Table_Build - @findex Zero Cost Exceptions - procedure SDP_Table_Build - (SDP_Addresses : System.Address; - SDP_Count : Natural; - Elab_Addresses : System.Address; - Elab_Addr_Count : Natural); - pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); - - -- Table of Unit_Exception_Table addresses. Used for zero - -- cost exception handling to build the top level table. - - ST : aliased constant array (1 .. 23) of System.Address := ( - Hello'UET_Address, - Ada.Text_Io'UET_Address, - Ada.Exceptions'UET_Address, - Gnat.Heap_Sort_A'UET_Address, - System.Exception_Table'UET_Address, - System.Machine_State_Operations'UET_Address, - System.Secondary_Stack'UET_Address, - System.Parameters'UET_Address, - System.Soft_Links'UET_Address, - System.Stack_Checking'UET_Address, - System.Traceback'UET_Address, - Ada.Streams'UET_Address, - Ada.Tags'UET_Address, - System.String_Ops'UET_Address, - Interfaces.C_Streams'UET_Address, - System.File_Io'UET_Address, - Ada.Finalization'UET_Address, - System.Finalization_Root'UET_Address, - System.Finalization_Implementation'UET_Address, - System.String_Ops_Concat_3'UET_Address, - System.Stream_Attributes'UET_Address, - System.File_Control_Block'UET_Address, - Ada.Finalization.List_Controller'UET_Address); - - -- Table of addresses of elaboration routines. Used for - -- zero cost exception handling to make sure these - -- addresses are included in the top level procedure - -- address table. - - EA : aliased constant array (1 .. 23) of System.Address := ( - adainit'Code_Address, - Do_Finalize'Code_Address, - Ada.Exceptions'Elab_Spec'Address, - System.Exceptions'Elab_Spec'Address, - Interfaces.C_Streams'Elab_Spec'Address, - System.Exception_Table'Elab_Body'Address, - Ada.Io_Exceptions'Elab_Spec'Address, - System.Stack_Checking'Elab_Spec'Address, - System.Soft_Links'Elab_Body'Address, - System.Secondary_Stack'Elab_Body'Address, - Ada.Tags'Elab_Spec'Address, - Ada.Tags'Elab_Body'Address, - Ada.Streams'Elab_Spec'Address, - System.Finalization_Root'Elab_Spec'Address, - Ada.Exceptions'Elab_Body'Address, - System.Finalization_Implementation'Elab_Spec'Address, - System.Finalization_Implementation'Elab_Body'Address, - Ada.Finalization'Elab_Spec'Address, - Ada.Finalization.List_Controller'Elab_Spec'Address, - System.File_Control_Block'Elab_Spec'Address, - System.File_Io'Elab_Body'Address, - Ada.Text_Io'Elab_Spec'Address, - Ada.Text_Io'Elab_Body'Address); - - -- Start of processing for adainit - - begin - - -- Call SDP_Table_Build to build the top level procedure - -- table for zero cost exception handling (omitted in - -- longjmp/setjump mode). - - SDP_Table_Build (ST'Address, 23, EA'Address, 23); - - -- Call Set_Globals to record various information for - -- this partition. The values are derived by the binder - -- from information stored in the ali files by the compiler. - - @findex __gnat_set_globals - Set_Globals - (Main_Priority => -1, - -- Priority of main program, -1 if no pragma Priority used - - Time_Slice_Value => -1, - -- Time slice from Time_Slice pragma, -1 if none used - - WC_Encoding => 'b', - -- Wide_Character encoding used, default is brackets - - Locking_Policy => ' ', - -- Locking_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Queuing_Policy => ' ', - -- Queuing_Policy used, default of space means not - -- specified, otherwise it is the first character of - -- the policy name. - - Task_Dispatching_Policy => ' ', - -- Task_Dispatching_Policy used, default of space means - -- not specified, otherwise first character of the - -- policy name. - - Adafinal => System.Null_Address, - -- Address of Adafinal routine, not used anymore - - Unreserve_All_Interrupts => 0, - -- Set true if pragma Unreserve_All_Interrupts was used - - Exception_Tracebacks => 0); - -- Indicates if exception tracebacks are enabled - - Elab_Final_Code := 1; - - -- Now we have the elaboration calls for all units in the partition. - -- The Elab_Spec and Elab_Body attributes generate references to the - -- implicit elaboration procedures generated by the compiler for - -- each unit that requires elaboration. - - if not E040 then - Interfaces.C_Streams'Elab_Spec; - end if; - E040 := True; - if not E008 then - Ada.Exceptions'Elab_Spec; - end if; - if not E014 then - System.Exception_Table'Elab_Body; - E014 := True; - end if; - if not E053 then - Ada.Io_Exceptions'Elab_Spec; - E053 := True; - end if; - if not E017 then - System.Exceptions'Elab_Spec; - E017 := True; - end if; - if not E030 then - System.Stack_Checking'Elab_Spec; - end if; - if not E028 then - System.Soft_Links'Elab_Body; - E028 := True; - end if; - E030 := True; - if not E024 then - System.Secondary_Stack'Elab_Body; - E024 := True; - end if; - if not E035 then - Ada.Tags'Elab_Spec; - end if; - if not E035 then - Ada.Tags'Elab_Body; - E035 := True; - end if; - if not E033 then - Ada.Streams'Elab_Spec; - E033 := True; - end if; - if not E046 then - System.Finalization_Root'Elab_Spec; - end if; - E046 := True; - if not E008 then - Ada.Exceptions'Elab_Body; - E008 := True; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Spec; - end if; - if not E048 then - System.Finalization_Implementation'Elab_Body; - E048 := True; - end if; - if not E044 then - Ada.Finalization'Elab_Spec; - end if; - E044 := True; - if not E057 then - Ada.Finalization.List_Controller'Elab_Spec; - end if; - E057 := True; - if not E055 then - System.File_Control_Block'Elab_Spec; - E055 := True; - end if; - if not E042 then - System.File_Io'Elab_Body; - E042 := True; - end if; - if not E006 then - Ada.Text_Io'Elab_Spec; - end if; - if not E006 then - Ada.Text_Io'Elab_Body; - E006 := True; - end if; - - Elab_Final_Code := 0; - end adainit; - - -------------- - -- adafinal -- - -------------- - - @findex adafinal - procedure adafinal is - begin - Do_Finalize; - end adafinal; - - ---------- - -- main -- - ---------- - - -- main is actually a function, as in the ANSI C standard, - -- defined to return the exit status. The three parameters - -- are the argument count, argument values and environment - -- pointer. - - @findex Main Program - function main - (argc : Integer; - argv : System.Address; - envp : System.Address) - return Integer - is - -- The initialize routine performs low level system - -- initialization using a standard library routine which - -- sets up signal handling and performs any other - -- required setup. The routine can be found in file - -- a-init.c. - - @findex __gnat_initialize - procedure initialize; - pragma Import (C, initialize, "__gnat_initialize"); - - -- The finalize routine performs low level system - -- finalization using a standard library routine. The - -- routine is found in file a-final.c and in the standard - -- distribution is a dummy routine that does nothing, so - -- really this is a hook for special user finalization. - - @findex __gnat_finalize - procedure finalize; - pragma Import (C, finalize, "__gnat_finalize"); - - -- We get to the main program of the partition by using - -- pragma Import because if we try to with the unit and - -- call it Ada style, then not only do we waste time - -- recompiling it, but also, we don't really know the right - -- switches (e.g. identifier character set) to be used - -- to compile it. - - procedure Ada_Main_Program; - pragma Import (Ada, Ada_Main_Program, "_ada_hello"); - - -- Start of processing for main - - begin - -- Save global variables - - gnat_argc := argc; - gnat_argv := argv; - gnat_envp := envp; - - -- Call low level system initialization - - Initialize; - - -- Call our generated Ada initialization routine - - adainit; - - -- This is the point at which we want the debugger to get - -- control - - Break_Start; - - -- Now we call the main program of the partition - - Ada_Main_Program; - - -- Perform Ada finalization - - adafinal; - - -- Perform low level system finalization - - Finalize; - - -- Return the proper exit status - return (gnat_exit_status); - end; - - -- This section is entirely comments, so it has no effect on the - -- compilation of the Ada_Main package. It provides the list of - -- object files and linker options, as well as some standard - -- libraries needed for the link. The gnatlink utility parses - -- this b~hello.adb file to read these comment lines to generate - -- the appropriate command line arguments for the call to the - -- system linker. The BEGIN/END lines are used for sentinels for - -- this parsing operation. - - -- The exact file names will of course depend on the environment, - -- host/target and location of files on the host system. - - @findex Object file list - -- BEGIN Object file/option list - -- ./hello.o - -- -L./ - -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ - -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a - -- END Object file/option list - - end ada_main; - - @end smallexample - - @noindent - The Ada code in the above example is exactly what is generated by the - binder. We have added comments to more clearly indicate the function - of each part of the generated @code{Ada_Main} package. - - The code is standard Ada in all respects, and can be processed by any - tools that handle Ada. In particular, it is possible to use the debugger - in Ada mode to debug the generated Ada_Main package. For example, suppose - that for reasons that you do not understand, your program is blowing up - during elaboration of the body of @code{Ada.Text_IO}. To chase this bug - down, you can place a breakpoint on the call: - - @smallexample - Ada.Text_Io'Elab_Body; - @end smallexample - - @noindent - and trace the elaboration routine for this package to find out where - the problem might be (more usually of course you would be debugging - elaboration code in your own application). - - @node Generating the Binder Program in C - @section Generating the Binder Program in C - @noindent - In most normal usage, the default mode of @code{gnatbind} which is to - generate the main package in Ada, as described in the previous section. - In particular, this means that any Ada programmer can read and understand - the generated main program. It can also be debugged just like any other - Ada code provided the @code{-g} switch is used for @code{gnatbind} - and @code{gnatlink}. - - However for some purposes it may be convenient to generate the main - program in C rather than Ada. This may for example be helpful when you - are generating a mixed language program with the main program in C. The - GNAT compiler itself is an example. The use of the @code{-C} switch - for both @code{gnatbind} and @code{gnatlink} will cause the program to - be generated in C (and compiled using the gnu C compiler). The - following shows the C code generated for the same "Hello World" - program: - - @smallexample - - #ifdef __STDC__ - #define PARAMS(paramlist) paramlist - #else - #define PARAMS(paramlist) () - #endif - - extern void __gnat_set_globals - PARAMS ((int, int, int, int, int, int, - void (*) PARAMS ((void)), int, int)); - extern void adafinal PARAMS ((void)); - extern void adainit PARAMS ((void)); - extern void system__standard_library__adafinal PARAMS ((void)); - extern int main PARAMS ((int, char **, char **)); - extern void exit PARAMS ((int)); - extern void __gnat_break_start PARAMS ((void)); - extern void _ada_hello PARAMS ((void)); - extern void __gnat_initialize PARAMS ((void)); - extern void __gnat_finalize PARAMS ((void)); - - extern void ada__exceptions___elabs PARAMS ((void)); - extern void system__exceptions___elabs PARAMS ((void)); - extern void interfaces__c_streams___elabs PARAMS ((void)); - extern void system__exception_table___elabb PARAMS ((void)); - extern void ada__io_exceptions___elabs PARAMS ((void)); - extern void system__stack_checking___elabs PARAMS ((void)); - extern void system__soft_links___elabb PARAMS ((void)); - extern void system__secondary_stack___elabb PARAMS ((void)); - extern void ada__tags___elabs PARAMS ((void)); - extern void ada__tags___elabb PARAMS ((void)); - extern void ada__streams___elabs PARAMS ((void)); - extern void system__finalization_root___elabs PARAMS ((void)); - extern void ada__exceptions___elabb PARAMS ((void)); - extern void system__finalization_implementation___elabs PARAMS ((void)); - extern void system__finalization_implementation___elabb PARAMS ((void)); - extern void ada__finalization___elabs PARAMS ((void)); - extern void ada__finalization__list_controller___elabs PARAMS ((void)); - extern void system__file_control_block___elabs PARAMS ((void)); - extern void system__file_io___elabb PARAMS ((void)); - extern void ada__text_io___elabs PARAMS ((void)); - extern void ada__text_io___elabb PARAMS ((void)); - - extern int __gnat_inside_elab_final_code; - - extern int gnat_argc; - extern char **gnat_argv; - extern char **gnat_envp; - extern int gnat_exit_status; - - char __gnat_version[] = "GNAT Version: 3.15w (20010315)"; - void adafinal () @{ - system__standard_library__adafinal (); - @} - - void adainit () - @{ - extern char ada__exceptions_E; - extern char system__exceptions_E; - extern char interfaces__c_streams_E; - extern char system__exception_table_E; - extern char ada__io_exceptions_E; - extern char system__secondary_stack_E; - extern char system__stack_checking_E; - extern char system__soft_links_E; - extern char ada__tags_E; - extern char ada__streams_E; - extern char system__finalization_root_E; - extern char system__finalization_implementation_E; - extern char ada__finalization_E; - extern char ada__finalization__list_controller_E; - extern char system__file_control_block_E; - extern char system__file_io_E; - extern char ada__text_io_E; - - extern void *__gnat_hello__SDP; - extern void *__gnat_ada__text_io__SDP; - extern void *__gnat_ada__exceptions__SDP; - extern void *__gnat_gnat__heap_sort_a__SDP; - extern void *__gnat_system__exception_table__SDP; - extern void *__gnat_system__machine_state_operations__SDP; - extern void *__gnat_system__secondary_stack__SDP; - extern void *__gnat_system__parameters__SDP; - extern void *__gnat_system__soft_links__SDP; - extern void *__gnat_system__stack_checking__SDP; - extern void *__gnat_system__traceback__SDP; - extern void *__gnat_ada__streams__SDP; - extern void *__gnat_ada__tags__SDP; - extern void *__gnat_system__string_ops__SDP; - extern void *__gnat_interfaces__c_streams__SDP; - extern void *__gnat_system__file_io__SDP; - extern void *__gnat_ada__finalization__SDP; - extern void *__gnat_system__finalization_root__SDP; - extern void *__gnat_system__finalization_implementation__SDP; - extern void *__gnat_system__string_ops_concat_3__SDP; - extern void *__gnat_system__stream_attributes__SDP; - extern void *__gnat_system__file_control_block__SDP; - extern void *__gnat_ada__finalization__list_controller__SDP; - - void **st[23] = @{ - &__gnat_hello__SDP, - &__gnat_ada__text_io__SDP, - &__gnat_ada__exceptions__SDP, - &__gnat_gnat__heap_sort_a__SDP, - &__gnat_system__exception_table__SDP, - &__gnat_system__machine_state_operations__SDP, - &__gnat_system__secondary_stack__SDP, - &__gnat_system__parameters__SDP, - &__gnat_system__soft_links__SDP, - &__gnat_system__stack_checking__SDP, - &__gnat_system__traceback__SDP, - &__gnat_ada__streams__SDP, - &__gnat_ada__tags__SDP, - &__gnat_system__string_ops__SDP, - &__gnat_interfaces__c_streams__SDP, - &__gnat_system__file_io__SDP, - &__gnat_ada__finalization__SDP, - &__gnat_system__finalization_root__SDP, - &__gnat_system__finalization_implementation__SDP, - &__gnat_system__string_ops_concat_3__SDP, - &__gnat_system__stream_attributes__SDP, - &__gnat_system__file_control_block__SDP, - &__gnat_ada__finalization__list_controller__SDP@}; - - extern void ada__exceptions___elabs (); - extern void system__exceptions___elabs (); - extern void interfaces__c_streams___elabs (); - extern void system__exception_table___elabb (); - extern void ada__io_exceptions___elabs (); - extern void system__stack_checking___elabs (); - extern void system__soft_links___elabb (); - extern void system__secondary_stack___elabb (); - extern void ada__tags___elabs (); - extern void ada__tags___elabb (); - extern void ada__streams___elabs (); - extern void system__finalization_root___elabs (); - extern void ada__exceptions___elabb (); - extern void system__finalization_implementation___elabs (); - extern void system__finalization_implementation___elabb (); - extern void ada__finalization___elabs (); - extern void ada__finalization__list_controller___elabs (); - extern void system__file_control_block___elabs (); - extern void system__file_io___elabb (); - extern void ada__text_io___elabs (); - extern void ada__text_io___elabb (); - - void (*ea[23]) () = @{ - adainit, - system__standard_library__adafinal, - ada__exceptions___elabs, - system__exceptions___elabs, - interfaces__c_streams___elabs, - system__exception_table___elabb, - ada__io_exceptions___elabs, - system__stack_checking___elabs, - system__soft_links___elabb, - system__secondary_stack___elabb, - ada__tags___elabs, - ada__tags___elabb, - ada__streams___elabs, - system__finalization_root___elabs, - ada__exceptions___elabb, - system__finalization_implementation___elabs, - system__finalization_implementation___elabb, - ada__finalization___elabs, - ada__finalization__list_controller___elabs, - system__file_control_block___elabs, - system__file_io___elabb, - ada__text_io___elabs, - ada__text_io___elabb@}; - - __gnat_SDP_Table_Build (&st, 23, ea, 23); - __gnat_set_globals ( - -1, /* Main_Priority */ - -1, /* Time_Slice_Value */ - 'b', /* WC_Encoding */ - ' ', /* Locking_Policy */ - ' ', /* Queuing_Policy */ - ' ', /* Tasking_Dispatching_Policy */ - 0, /* Finalization routine address, not used anymore */ - 0, /* Unreserve_All_Interrupts */ - 0); /* Exception_Tracebacks */ - - __gnat_inside_elab_final_code = 1; - - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabs (); - @} - if (system__exceptions_E == 0) @{ - system__exceptions___elabs (); - system__exceptions_E++; - @} - if (interfaces__c_streams_E == 0) @{ - interfaces__c_streams___elabs (); - @} - interfaces__c_streams_E = 1; - if (system__exception_table_E == 0) @{ - system__exception_table___elabb (); - system__exception_table_E++; - @} - if (ada__io_exceptions_E == 0) @{ - ada__io_exceptions___elabs (); - ada__io_exceptions_E++; - @} - if (system__stack_checking_E == 0) @{ - system__stack_checking___elabs (); - @} - if (system__soft_links_E == 0) @{ - system__soft_links___elabb (); - system__soft_links_E++; - @} - system__stack_checking_E = 1; - if (system__secondary_stack_E == 0) @{ - system__secondary_stack___elabb (); - system__secondary_stack_E++; - @} - if (ada__tags_E == 0) @{ - ada__tags___elabs (); - @} - if (ada__tags_E == 0) @{ - ada__tags___elabb (); - ada__tags_E++; - @} - if (ada__streams_E == 0) @{ - ada__streams___elabs (); - ada__streams_E++; - @} - if (system__finalization_root_E == 0) @{ - system__finalization_root___elabs (); - @} - system__finalization_root_E = 1; - if (ada__exceptions_E == 0) @{ - ada__exceptions___elabb (); - ada__exceptions_E++; - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabs (); - @} - if (system__finalization_implementation_E == 0) @{ - system__finalization_implementation___elabb (); - system__finalization_implementation_E++; - @} - if (ada__finalization_E == 0) @{ - ada__finalization___elabs (); - @} - ada__finalization_E = 1; - if (ada__finalization__list_controller_E == 0) @{ - ada__finalization__list_controller___elabs (); - @} - ada__finalization__list_controller_E = 1; - if (system__file_control_block_E == 0) @{ - system__file_control_block___elabs (); - system__file_control_block_E++; - @} - if (system__file_io_E == 0) @{ - system__file_io___elabb (); - system__file_io_E++; - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabs (); - @} - if (ada__text_io_E == 0) @{ - ada__text_io___elabb (); - ada__text_io_E++; - @} - - __gnat_inside_elab_final_code = 0; - @} - int main (argc, argv, envp) - int argc; - char **argv; - char **envp; - @{ - gnat_argc = argc; - gnat_argv = argv; - gnat_envp = envp; - - __gnat_initialize (); - adainit (); - __gnat_break_start (); - - _ada_hello (); - - system__standard_library__adafinal (); - __gnat_finalize (); - exit (gnat_exit_status); - @} - unsigned helloB = 0x7880BEB3; - unsigned system__standard_libraryB = 0x0D24CBD0; - unsigned system__standard_libraryS = 0x3283DBEB; - unsigned adaS = 0x2359F9ED; - unsigned ada__text_ioB = 0x47C85FC4; - unsigned ada__text_ioS = 0x496FE45C; - unsigned ada__exceptionsB = 0x74F50187; - unsigned ada__exceptionsS = 0x6736945B; - unsigned gnatS = 0x156A40CF; - unsigned gnat__heap_sort_aB = 0x033DABE0; - unsigned gnat__heap_sort_aS = 0x6AB38FEA; - unsigned systemS = 0x0331C6FE; - unsigned system__exceptionsS = 0x20C9ECA4; - unsigned system__exception_tableB = 0x68A22947; - unsigned system__exception_tableS = 0x394BADD5; - unsigned gnat__htableB = 0x08258E1B; - unsigned gnat__htableS = 0x367D5222; - unsigned system__machine_state_operationsB = 0x4F3B7492; - unsigned system__machine_state_operationsS = 0x182F5CF4; - unsigned system__storage_elementsB = 0x2F1EB794; - unsigned system__storage_elementsS = 0x102C83C7; - unsigned system__secondary_stackB = 0x1574B6E9; - unsigned system__secondary_stackS = 0x708E260A; - unsigned system__parametersB = 0x56D770CD; - unsigned system__parametersS = 0x237E39BE; - unsigned system__soft_linksB = 0x08AB6B2C; - unsigned system__soft_linksS = 0x1E2491F3; - unsigned system__stack_checkingB = 0x476457A0; - unsigned system__stack_checkingS = 0x5299FCED; - unsigned system__tracebackB = 0x2971EBDE; - unsigned system__tracebackS = 0x2E9C3122; - unsigned ada__streamsS = 0x7C25DE96; - unsigned ada__tagsB = 0x39ADFFA2; - unsigned ada__tagsS = 0x769A0464; - unsigned system__string_opsB = 0x5EB646AB; - unsigned system__string_opsS = 0x63CED018; - unsigned interfacesS = 0x0357E00A; - unsigned interfaces__c_streamsB = 0x3784FB72; - unsigned interfaces__c_streamsS = 0x2E723019; - unsigned system__file_ioB = 0x623358EA; - unsigned system__file_ioS = 0x31F873E6; - unsigned ada__finalizationB = 0x6843F68A; - unsigned ada__finalizationS = 0x63305874; - unsigned system__finalization_rootB = 0x31E56CE1; - unsigned system__finalization_rootS = 0x23169EF3; - unsigned system__finalization_implementationB = 0x6CCBA70E; - unsigned system__finalization_implementationS = 0x604AA587; - unsigned system__string_ops_concat_3B = 0x572E3F58; - unsigned system__string_ops_concat_3S = 0x01F57876; - unsigned system__stream_attributesB = 0x1D4F93E8; - unsigned system__stream_attributesS = 0x30B2EC3D; - unsigned ada__io_exceptionsS = 0x34054F96; - unsigned system__unsigned_typesS = 0x7B9E7FE3; - unsigned system__file_control_blockS = 0x2FF876A8; - unsigned ada__finalization__list_controllerB = 0x5760634A; - unsigned ada__finalization__list_controllerS = 0x5D851835; - - /* BEGIN ELABORATION ORDER - ada (spec) - gnat (spec) - gnat.heap_sort_a (spec) - gnat.htable (spec) - gnat.htable (body) - interfaces (spec) - system (spec) - system.parameters (spec) - system.standard_library (spec) - ada.exceptions (spec) - system.exceptions (spec) - system.parameters (body) - gnat.heap_sort_a (body) - interfaces.c_streams (spec) - interfaces.c_streams (body) - system.exception_table (spec) - system.exception_table (body) - ada.io_exceptions (spec) - system.storage_elements (spec) - system.storage_elements (body) - system.machine_state_operations (spec) - system.machine_state_operations (body) - system.secondary_stack (spec) - system.stack_checking (spec) - system.soft_links (spec) - system.soft_links (body) - system.stack_checking (body) - system.secondary_stack (body) - system.standard_library (body) - system.string_ops (spec) - system.string_ops (body) - ada.tags (spec) - ada.tags (body) - ada.streams (spec) - system.finalization_root (spec) - system.finalization_root (body) - system.string_ops_concat_3 (spec) - system.string_ops_concat_3 (body) - system.traceback (spec) - system.traceback (body) - ada.exceptions (body) - system.unsigned_types (spec) - system.stream_attributes (spec) - system.stream_attributes (body) - system.finalization_implementation (spec) - system.finalization_implementation (body) - ada.finalization (spec) - ada.finalization (body) - ada.finalization.list_controller (spec) - ada.finalization.list_controller (body) - system.file_control_block (spec) - system.file_io (spec) - system.file_io (body) - ada.text_io (spec) - ada.text_io (body) - hello (body) - END ELABORATION ORDER */ - - /* BEGIN Object file/option list - ./hello.o - -L./ - -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/ - /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a - -lexc - END Object file/option list */ - - @end smallexample - - @noindent - Here again, the C code is exactly what is generated by the binder. The - functions of the various parts of this code correspond in an obvious - manner with the commented Ada code shown in the example in the previous - section. - - @node Consistency-Checking Modes - @section Consistency-Checking Modes - - @noindent - As described in the previous section, by default @code{gnatbind} checks - that object files are consistent with one another and are consistent - with any source files it can locate. The following switches control binder - access to sources. - - @table @code - @item -s - @cindex @code{-s} (@code{gnatbind}) - Require source files to be present. In this mode, the binder must be - able to locate all source files that are referenced, in order to check - their consistency. In normal mode, if a source file cannot be located it - is simply ignored. If you specify this switch, a missing source - file is an error. - - @item -x - @cindex @code{-x} (@code{gnatbind}) - Exclude source files. In this mode, the binder only checks that ALI - files are consistent with one another. Source files are not accessed. - The binder runs faster in this mode, and there is still a guarantee that - the resulting program is self-consistent. - If a source file has been edited since it was last compiled, and you - specify this switch, the binder will not detect that the object - file is out of date with respect to the source file. Note that this is the - mode that is automatically used by @code{gnatmake} because in this - case the checking against sources has already been performed by - @code{gnatmake} in the course of compilation (i.e. before binding). - - @end table - - @node Binder Error Message Control - @section Binder Error Message Control - - @noindent - The following switches provide control over the generation of error - messages from the binder: - - @table @code - @item -v - @cindex @code{-v} (@code{gnatbind}) - Verbose mode. In the normal mode, brief error messages are generated to - @file{stderr}. If this switch is present, a header is written - to @file{stdout} and any error messages are directed to @file{stdout}. - All that is written to @file{stderr} is a brief summary message. - - @item -b - @cindex @code{-b} (@code{gnatbind}) - Generate brief error messages to @file{stderr} even if verbose mode is - specified. This is relevant only when used with the - @code{-v} switch. - - @item -m@var{n} - @cindex @code{-m} (@code{gnatbind}) - Limits the number of error messages to @var{n}, a decimal integer in the - range 1-999. The binder terminates immediately if this limit is reached. - - @item -M@var{xxx} - @cindex @code{-M} (@code{gnatbind}) - Renames the generated main program from @code{main} to @code{xxx}. - This is useful in the case of some cross-building environments, where - the actual main program is separate from the one generated - by @code{gnatbind}. - - @item -ws - @cindex @code{-ws} (@code{gnatbind}) - @cindex Warnings - Suppress all warning messages. - - @item -we - @cindex @code{-we} (@code{gnatbind}) - Treat any warning messages as fatal errors. - - - @item -t - @cindex @code{-t} (@code{gnatbind}) - @cindex Time stamp checks, in binder - @cindex Binder consistency checks - @cindex Consistency checks, in binder - The binder performs a number of consistency checks including: - - @itemize @bullet - @item - Check that time stamps of a given source unit are consistent - @item - Check that checksums of a given source unit are consistent - @item - Check that consistent versions of @code{GNAT} were used for compilation - @item - Check consistency of configuration pragmas as required - @end itemize - - @noindent - Normally failure of such checks, in accordance with the consistency - requirements of the Ada Reference Manual, causes error messages to be - generated which abort the binder and prevent the output of a binder - file and subsequent link to obtain an executable. - - The @code{-t} switch converts these error messages - into warnings, so that - binding and linking can continue to completion even in the presence of such - errors. The result may be a failed link (due to missing symbols), or a - non-functional executable which has undefined semantics. - @emph{This means that - @code{-t} should be used only in unusual situations, - with extreme care.} - @end table - - @node Elaboration Control - @section Elaboration Control - - @noindent - The following switches provide additional control over the elaboration - order. For full details see @xref{Elaboration Order Handling in GNAT}. - - @table @code - @item -p - @cindex @code{-h} (@code{gnatbind}) - Normally the binder attempts to choose an elaboration order that is - likely to minimize the likelihood of an elaboration order error resulting - in raising a @code{Program_Error} exception. This switch reverses the - action of the binder, and requests that it deliberately choose an order - that is likely to maximize the likelihood of an elaboration error. - This is useful in ensuring portability and avoiding dependence on - accidental fortuitous elaboration ordering. - - Normally it only makes sense to use the @code{-p} switch if dynamic - elaboration checking is used (@option{-gnatE} switch used for compilation). - This is because in the default static elaboration mode, all necessary - @code{Elaborate_All} pragmas are implicitly inserted. These implicit - pragmas are still respected by the binder in @code{-p} mode, so a - safe elaboration order is assured. - @end table - - @node Output Control - @section Output Control - - @noindent - The following switches allow additional control over the output - generated by the binder. - - @table @code - - @item -A - @cindex @code{-A} (@code{gnatbind}) - Generate binder program in Ada (default). The binder program is named - @file{b~@var{mainprog}.adb} by default. This can be changed with - @code{-o} @code{gnatbind} option. - - @item -c - @cindex @code{-c} (@code{gnatbind}) - Check only. Do not generate the binder output file. In this mode the - binder performs all error checks but does not generate an output file. - - @item -C - @cindex @code{-C} (@code{gnatbind}) - Generate binder program in C. The binder program is named - @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind} - option. - - @item -e - @cindex @code{-e} (@code{gnatbind}) - Output complete list of elaboration-order dependencies, showing the - reason for each dependency. This output can be rather extensive but may - be useful in diagnosing problems with elaboration order. The output is - written to @file{stdout}. - - @item -h - @cindex @code{-h} (@code{gnatbind}) - Output usage information. The output is written to @file{stdout}. - - @item -K - @cindex @code{-K} (@code{gnatbind}) - Output linker options to @file{stdout}. Includes library search paths, - contents of pragmas Ident and Linker_Options, and libraries added - by @code{gnatbind}. - - @item -l - @cindex @code{-l} (@code{gnatbind}) - Output chosen elaboration order. The output is written to @file{stdout}. - - @item -O - @cindex @code{-O} (@code{gnatbind}) - Output full names of all the object files that must be linked to provide - the Ada component of the program. The output is written to @file{stdout}. - This list includes the files explicitly supplied and referenced by the user - as well as implicitly referenced run-time unit files. The latter are - omitted if the corresponding units reside in shared libraries. The - directory names for the run-time units depend on the system configuration. - - @item -o @var{file} - @cindex @code{-o} (@code{gnatbind}) - Set name of output file to @var{file} instead of the normal - @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada - binder generated body filename. In C mode you would normally give - @var{file} an extension of @file{.c} because it will be a C source program. - Note that if this option is used, then linking must be done manually. - It is not possible to use gnatlink in this case, since it cannot locate - the binder file. - - @item -r - @cindex @code{-r} (@code{gnatbind}) - Generate list of @code{pragma Rerstrictions} that could be applied to - the current unit. This is useful for code audit purposes, and also may - be used to improve code generation in some cases. - - @end table - - @node Binding with Non-Ada Main Programs - @section Binding with Non-Ada Main Programs - - @noindent - In our description so far we have assumed that the main - program is in Ada, and that the task of the binder is to generate a - corresponding function @code{main} that invokes this Ada main - program. GNAT also supports the building of executable programs where - the main program is not in Ada, but some of the called routines are - written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). - The following switch is used in this situation: - - @table @code - @item -n - @cindex @code{-n} (@code{gnatbind}) - No main program. The main program is not in Ada. - @end table - - @noindent - In this case, most of the functions of the binder are still required, - but instead of generating a main program, the binder generates a file - containing the following callable routines: - - @table @code - @item adainit - @findex adainit - You must call this routine to initialize the Ada part of the program by - calling the necessary elaboration routines. A call to @code{adainit} is - required before the first call to an Ada subprogram. - - Note that it is assumed that the basic execution environment must be setup - to be appropriate for Ada execution at the point where the first Ada - subprogram is called. In particular, if the Ada code will do any - floating-point operations, then the FPU must be setup in an appropriate - manner. For the case of the x86, for example, full precision mode is - required. The procedure GNAT.Float_Control.Reset may be used to ensure - that the FPU is in the right state. - - @item adafinal - @findex adafinal - You must call this routine to perform any library-level finalization - required by the Ada subprograms. A call to @code{adafinal} is required - after the last call to an Ada subprogram, and before the program - terminates. - @end table - - @noindent - If the @code{-n} switch - @cindex Binder, multiple input files - is given, more than one ALI file may appear on - the command line for @code{gnatbind}. The normal @dfn{closure} - calculation is performed for each of the specified units. Calculating - the closure means finding out the set of units involved by tracing - @code{with} references. The reason it is necessary to be able to - specify more than one ALI file is that a given program may invoke two or - more quite separate groups of Ada units. - - The binder takes the name of its output file from the last specified ALI - file, unless overridden by the use of the @code{-o file}. - The output is an Ada unit in source form that can - be compiled with GNAT unless the -C switch is used in which case the - output is a C source file, which must be compiled using the C compiler. - This compilation occurs automatically as part of the @code{gnatlink} - processing. - - Currently the GNAT run time requires a FPU using 80 bits mode - precision. Under targets where this is not the default it is required to - call GNAT.Float_Control.Reset before using floating point numbers (this - include float computation, float input and output) in the Ada code. A - side effect is that this could be the wrong mode for the foreign code - where floating point computation could be broken after this call. - - @node Binding Programs with No Main Subprogram - @section Binding Programs with No Main Subprogram - - @noindent - It is possible to have an Ada program which does not have a main - subprogram. This program will call the elaboration routines of all the - packages, then the finalization routines. - - The following switch is used to bind programs organized in this manner: - - @table @code - @item -z - @cindex @code{-z} (@code{gnatbind}) - Normally the binder checks that the unit name given on the command line - corresponds to a suitable main subprogram. When this switch is used, - a list of ALI files can be given, and the execution of the program - consists of elaboration of these units in an appropriate order. - @end table - - @node Summary of Binder Switches - @section Summary of Binder Switches - - @noindent - The following are the switches available with @code{gnatbind}: - - @table @code - @item -aO - Specify directory to be searched for ALI files. - - @item -aI - Specify directory to be searched for source file. - - @item -A - Generate binder program in Ada (default) - - @item -b - Generate brief messages to @file{stderr} even if verbose mode set. - - @item -c - Check only, no generation of binder output file. - - @item -C - Generate binder program in C - - @item -e - Output complete list of elaboration-order dependencies. - - @item -E - Store tracebacks in exception occurrences when the target supports it. - This is the default with the zero cost exception mechanism. - This option is currently supported on the following targets: - all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. - See also the packages @code{GNAT.Traceback} and - @code{GNAT.Traceback.Symbolic} for more information. - Note that on x86 ports, you must not use @code{-fomit-frame-pointer} - @code{gcc} option. - - @item -h - Output usage (help) information - - @item -I - Specify directory to be searched for source and ALI files. - - @item -I- - Do not look for sources in the current directory where @code{gnatbind} was - invoked, and do not look for ALI files in the directory containing the - ALI file named in the @code{gnatbind} command line. - - @item -l - Output chosen elaboration order. - - @item -Lxxx - Binds the units for library building. In this case the adainit and - adafinal procedures (See @pxref{Binding with Non-Ada Main Programs}) - are renamed to xxxinit and xxxfinal. Implies -n. - See @pxref{GNAT and Libraries} for more details. - - @item -Mxyz - Rename generated main program from main to xyz - - @item -m@var{n} - Limit number of detected errors to @var{n} (1-999). - Furthermore, under Windows, the sources pointed to by the libraries path - set in the registry are not searched for. - - @item -n - No main program. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatbind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -o @var{file} - Name the output file @var{file} (default is @file{b~@var{xxx}.adb}). - Note that if this option is used, then linking must be done manually, - gnatlink cannot be used. - - @item -O - Output object list. - - @item -p - Pessimistic (worst-case) elaboration order - - @item -s - Require all source files to be present. - - @item -static - Link against a static GNAT run time. - - @item -shared - Link against a shared GNAT run time when available. - - @item -t - Tolerate time stamp and other consistency errors - - @item -T@var{n} - Set the time slice value to n microseconds. A value of zero means no time - slicing and also indicates to the tasking run time to match as close as - possible to the annex D requirements of the RM. - - @item -v - Verbose mode. Write error messages, header, summary output to - @file{stdout}. - - @item -w@var{x} - Warning mode (@var{x}=s/e for suppress/treat as error) - - - @item -x - Exclude source files (check object consistency only). - - - @item -z - No main subprogram. - - @end table - - You may obtain this listing by running the program @code{gnatbind} with - no arguments. - - @node Command-Line Access - @section Command-Line Access - - @noindent - The package @code{Ada.Command_Line} provides access to the command-line - arguments and program name. In order for this interface to operate - correctly, the two variables - - @smallexample - @group - @cartouche - int gnat_argc; - char **gnat_argv; - @end cartouche - @end group - @end smallexample - - @noindent - @findex gnat_argv - @findex gnat_argc - are declared in one of the GNAT library routines. These variables must - be set from the actual @code{argc} and @code{argv} values passed to the - main program. With no @code{n} present, @code{gnatbind} - generates the C main program to automatically set these variables. - If the @code{n} switch is used, there is no automatic way to - set these variables. If they are not set, the procedures in - @code{Ada.Command_Line} will not be available, and any attempt to use - them will raise @code{Constraint_Error}. If command line access is - required, your main program must set @code{gnat_argc} and - @code{gnat_argv} from the @code{argc} and @code{argv} values passed to - it. - - @node Search Paths for gnatbind - @section Search Paths for @code{gnatbind} - - @noindent - The binder takes the name of an ALI file as its argument and needs to - locate source files as well as other ALI files to verify object consistency. - - For source files, it follows exactly the same search rules as @code{gcc} - (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the - directories searched are: - - @enumerate - @item - The directory containing the ALI file named in the command line, unless - the switch @code{-I-} is specified. - - @item - All directories specified by @code{-I} - switches on the @code{gnatbind} - command line, in the order given. - - @item - @findex ADA_OBJECTS_PATH - Each of the directories listed in the value of the - @code{ADA_OBJECTS_PATH} environment variable. - Construct this value - exactly as the @code{PATH} environment variable: a list of directory - names separated by colons (semicolons when working with the NT version - of GNAT). - - @item - The content of the "ada_object_path" file which is part of the GNAT - installation tree and is used to store standard libraries such as the - GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is - specified. - @ref{Installing an Ada Library} - @end enumerate - - @noindent - In the binder the switch @code{-I} - is used to specify both source and - library file paths. Use @code{-aI} - instead if you want to specify - source paths only, and @code{-aO} - if you want to specify library paths - only. This means that for the binder - @code{-I}@var{dir} is equivalent to - @code{-aI}@var{dir} - @code{-aO}@var{dir}. - The binder generates the bind file (a C language source file) in the - current working directory. - - @findex Ada - @findex System - @findex Interfaces - @findex GNAT - The packages @code{Ada}, @code{System}, and @code{Interfaces} and their - children make up the GNAT Run-Time Library, together with the package - GNAT and its children, which contain a set of useful additional - library functions provided by GNAT. The sources for these units are - needed by the compiler and are kept together in one directory. The ALI - files and object files generated by compiling the RTL are needed by the - binder and the linker and are kept together in one directory, typically - different from the directory containing the sources. In a normal - installation, you need not specify these directory names when compiling - or binding. Either the environment variables or the built-in defaults - cause these files to be found. - - Besides simplifying access to the RTL, a major use of search paths is - in compiling sources from multiple directories. This can make - development environments much more flexible. - - @node Examples of gnatbind Usage - @section Examples of @code{gnatbind} Usage - - @noindent - This section contains a number of examples of using the GNAT binding - utility @code{gnatbind}. - - @table @code - @item gnatbind hello - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{b~hello.adb}. This is the normal, default use of the binder. - - @item gnatbind hello -o mainprog.adb - The main program @code{Hello} (source program in @file{hello.adb}) is - bound using the standard switch settings. The generated main program is - @file{mainprog.adb} with the associated spec in - @file{mainprog.ads}. Note that you must specify the body here not the - spec, in the case where the output is in Ada. Note that if this option - is used, then linking must be done manually, since gnatlink will not - be able to find the generated file. - - @item gnatbind main -C -o mainprog.c -x - The main program @code{Main} (source program in - @file{main.adb}) is bound, excluding source files from the - consistency checking, generating - the file @file{mainprog.c}. - - @item gnatbind -x main_program -C -o mainprog.c - This command is exactly the same as the previous example. Switches may - appear anywhere in the command line, and single letter switches may be - combined into a single switch. - - @item gnatbind -n math dbase -C -o ada-control.c - The main program is in a language other than Ada, but calls to - subprograms in packages @code{Math} and @code{Dbase} appear. This call - to @code{gnatbind} generates the file @file{ada-control.c} containing - the @code{adainit} and @code{adafinal} routines to be called before and - after accessing the Ada units. - @end table - - @node Linking Using gnatlink - @chapter Linking Using @code{gnatlink} - @findex gnatlink - - @noindent - This chapter discusses @code{gnatlink}, a utility program used to link - Ada programs and build an executable file. This is a simple program - that invokes the Unix linker (via the @code{gcc} - command) with a correct list of object files and library references. - @code{gnatlink} automatically determines the list of files and - references for the Ada part of a program. It uses the binder file - generated by the binder to determine this list. - - @menu - * Running gnatlink:: - * Switches for gnatlink:: - * Setting Stack Size from gnatlink:: - * Setting Heap Size from gnatlink:: - @end menu - - @node Running gnatlink - @section Running @code{gnatlink} - - @noindent - The form of the @code{gnatlink} command is - - @smallexample - $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}] - [@var{linker options}] - @end smallexample - - @noindent - @file{@var{mainprog}.ali} references the ALI file of the main program. - The @file{.ali} extension of this file can be omitted. From this - reference, @code{gnatlink} locates the corresponding binder file - @file{b~@var{mainprog}.adb} and, using the information in this file along - with the list of non-Ada objects and linker options, constructs a Unix - linker command file to create the executable. - - The arguments following @file{@var{mainprog}.ali} are passed to the - linker uninterpreted. They typically include the names of object files - for units written in other languages than Ada and any library references - required to resolve references in any of these foreign language units, - or in @code{pragma Import} statements in any Ada units. - - @var{linker options} is an optional list of linker specific - switches. The default linker called by gnatlink is @var{gcc} which in - turn calls the appropriate system linker usually called - @var{ld}. Standard options for the linker such as @code{-lmy_lib} or - @code{-Ldir} can be added as is. For options that are not recognized by - @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or - @code{-Wl,} shall be used. Refer to the GCC documentation for - details. Here is an example showing how to generate a linker map - assuming that the underlying linker is GNU ld: - - @smallexample - $ gnatlink my_prog -Wl,-Map,MAPFILE - @end smallexample - - Using @var{linker options} it is possible to set the program stack and - heap size. See @pxref{Setting Stack Size from gnatlink} and - @pxref{Setting Heap Size from gnatlink}. - - @code{gnatlink} determines the list of objects required by the Ada - program and prepends them to the list of objects passed to the linker. - @code{gnatlink} also gathers any arguments set by the use of - @code{pragma Linker_Options} and adds them to the list of arguments - presented to the linker. - - - @node Switches for gnatlink - @section Switches for @code{gnatlink} - - @noindent - The following switches are available with the @code{gnatlink} utility: - - @table @code - - @item -A - @cindex @code{-A} (@code{gnatlink}) - The binder has generated code in Ada. This is the default. - - @item -C - @cindex @code{-C} (@code{gnatlink}) - If instead of generating a file in Ada, the binder has generated one in - C, then the linker needs to know about it. Use this switch to signal - to @code{gnatlink} that the binder has generated C code rather than - Ada code. - - @item -f - @cindex Command line length - @cindex @code{-f} (@code{gnatlink}) - On some targets, the command line length is limited, and @code{gnatlink} - will generate a separate file for the linker if the list of object files - is too long. The @code{-f} flag forces this file to be generated even if - the limit is not exceeded. This is useful in some cases to deal with - special situations where the command line length is exceeded. - - @item -g - @cindex Debugging information, including - @cindex @code{-g} (@code{gnatlink}) - The option to include debugging information causes the Ada bind file (in - other words, @file{b~@var{mainprog}.adb}) to be compiled with - @code{-g}. - In addition, the binder does not delete the @file{b~@var{mainprog}.adb}, - @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files. - Without @code{-g}, the binder removes these files by - default. The same procedure apply if a C bind file was generated using - @code{-C} @code{gnatbind} option, in this case the filenames are - @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}. - - @item -n - @cindex @code{-n} (@code{gnatlink}) - Do not compile the file generated by the binder. This may be used when - a link is rerun with different options, but there is no need to recompile - the binder file. - - @item -v - @cindex @code{-v} (@code{gnatlink}) - Causes additional information to be output, including a full list of the - included object files. This switch option is most useful when you want - to see what set of object files are being used in the link step. - - @item -v -v - @cindex @code{-v -v} (@code{gnatlink}) - Very verbose mode. Requests that the compiler operate in verbose mode when - it compiles the binder file, and that the system linker run in verbose mode. - - @item -o @var{exec-name} - @cindex @code{-o} (@code{gnatlink}) - @var{exec-name} specifies an alternate name for the generated - executable program. If this switch is omitted, the executable has the same - name as the main unit. For example, @code{gnatlink try.ali} creates - an executable called @file{try}. - - @item -b @var{target} - @cindex @code{-b} (@code{gnatlink}) - Compile your program to run on @var{target}, which is the name of a - system configuration. You must have a GNAT cross-compiler built if - @var{target} is not the same as your host system. - - @item -B@var{dir} - @cindex @code{-B} (@code{gnatlink}) - Load compiler executables (for example, @code{gnat1}, the Ada compiler) - from @var{dir} instead of the default location. Only use this switch - when multiple versions of the GNAT compiler are available. See the - @code{gcc} manual page for further details. You would normally use the - @code{-b} or @code{-V} switch instead. - - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatlink}) - Program used for compiling the binder file. The default is - `@code{gcc}'. You need to use quotes around @var{compiler_name} if - @code{compiler_name} contains spaces or other separator characters. As - an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use - @code{foo -x -y} as your compiler. Note that switch @code{-c} is always - inserted after your command name. Thus in the above example the compiler - command that will be used by @code{gnatlink} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --LINK=@var{name} - @cindex @code{--LINK=} (@code{gnatlink}) - @var{name} is the name of the linker to be invoked. This is especially - useful in mixed language programs since languages such as c++ require - their own linker to be used. When this switch is omitted, the default - name for the linker is (@file{gcc}). When this switch is used, the - specified linker is called instead of (@file{gcc}) with exactly the same - parameters that would have been passed to (@file{gcc}) so if the desired - linker requires different parameters it is necessary to use a wrapper - script that massages the parameters before invoking the real linker. It - may be useful to control the exact invocation by using the verbose - switch. - - - - @end table - - @node Setting Stack Size from gnatlink - @section Setting Stack Size from @code{gnatlink} - - @noindent - It is possible to specify the program stack size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --stack=0x10000,0x1000 - @end smallexample - - This set the stack reserve size to 0x10000 bytes and the stack commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--stack=0x1000000 - @end smallexample - - This set the stack reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the stack commit size - because the coma is a separator for this option. - - @end itemize - - @node Setting Heap Size from gnatlink - @section Setting Heap Size from @code{gnatlink} - - @noindent - It is possible to specify the program heap size from @code{gnatlink}. - Assuming that the underlying linker is GNU ld there is two ways to do so: - - @itemize @bullet - - @item using @code{-Xlinker} linker option - - @smallexample - $ gnatlink hello -Xlinker --heap=0x10000,0x1000 - @end smallexample - - This set the heap reserve size to 0x10000 bytes and the heap commit - size to 0x1000 bytes. - - @item using @code{-Wl} linker option - - @smallexample - $ gnatlink hello -Wl,--heap=0x1000000 - @end smallexample - - This set the heap reserve size to 0x1000000 bytes. Note that with - @code{-Wl} option it is not possible to set the heap commit size - because the coma is a separator for this option. - - @end itemize - - @node The GNAT Make Program gnatmake - @chapter The GNAT Make Program @code{gnatmake} - @findex gnatmake - - @menu - * Running gnatmake:: - * Switches for gnatmake:: - * Mode Switches for gnatmake:: - * Notes on the Command Line:: - * How gnatmake Works:: - * Examples of gnatmake Usage:: - @end menu - @noindent - A typical development cycle when working on an Ada program consists of - the following steps: - - @enumerate - @item - Edit some sources to fix bugs. - - @item - Add enhancements. - - @item - Compile all sources affected. - - @item - Rebind and relink. - - @item - Test. - @end enumerate - - @noindent - The third step can be tricky, because not only do the modified files - @cindex Dependency rules - have to be compiled, but any files depending on these files must also be - recompiled. The dependency rules in Ada can be quite complex, especially - in the presence of overloading, @code{use} clauses, generics and inlined - subprograms. - - @code{gnatmake} automatically takes care of the third and fourth steps - of this process. It determines which sources need to be compiled, - compiles them, and binds and links the resulting object files. - - Unlike some other Ada make programs, the dependencies are always - accurately recomputed from the new sources. The source based approach of - the GNAT compilation model makes this possible. This means that if - changes to the source program cause corresponding changes in - dependencies, they will always be tracked exactly correctly by - @code{gnatmake}. - - @node Running gnatmake - @section Running @code{gnatmake} - - @noindent - The usual form of the @code{gnatmake} command is - - @smallexample - $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}] - @end smallexample - - @noindent - The only required argument is one @var{file_name}, which specifies - a compilation unit that is a main program. Several @var{file_names} can be - specified: this will result in several executables being built. - If @code{switches} are present, they can be placed before the first - @var{file_name}, between @var{file_names} or after the last @var{file_name}. - If @var{mode_switches} are present, they must always be placed after - the last @var{file_name} and all @code{switches}. - - If you are using standard file extensions (.adb and .ads), then the - extension may be omitted from the @var{file_name} arguments. However, if - you are using non-standard extensions, then it is required that the - extension be given. A relative or absolute directory path can be - specified in a @var{file_name}, in which case, the input source file will - be searched for in the specified directory only. Otherwise, the input - source file will first be searched in the directory where - @code{gnatmake} was invoked and if it is not found, it will be search on - the source path of the compiler as described in - @ref{Search Paths and the Run-Time Library (RTL)}. - - When several @var{file_names} are specified, if an executable needs to be - rebuilt and relinked, all subsequent executables will be rebuilt and - relinked, even if this would not be absolutely necessary. - - All @code{gnatmake} output (except when you specify - @code{-M}) is to - @file{stderr}. The output produced by the - @code{-M} switch is send to - @file{stdout}. - - @node Switches for gnatmake - @section Switches for @code{gnatmake} - - @noindent - You may specify any of the following switches to @code{gnatmake}: - - @table @code - @item --GCC=@var{compiler_name} - @cindex @code{--GCC=compiler_name} (@code{gnatmake}) - Program used for compiling. The default is `@code{gcc}'. You need to use - quotes around @var{compiler_name} if @code{compiler_name} contains - spaces or other separator characters. As an example @code{--GCC="foo -x - -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your - compiler. Note that switch @code{-c} is always inserted after your - command name. Thus in the above example the compiler command that will - be used by @code{gnatmake} will be @code{foo -c -x -y}. - If several @code{--GCC=compiler_name} are used, only the last - @var{compiler_name} is taken into account. However, all the additional - switches are also taken into account. Thus, - @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to - @code{--GCC="bar -x -y -z -t"}. - - @item --GNATBIND=@var{binder_name} - @cindex @code{--GNATBIND=binder_name} (@code{gnatmake}) - Program used for binding. The default is `@code{gnatbind}'. You need to - use quotes around @var{binder_name} if @var{binder_name} contains spaces - or other separator characters. As an example @code{--GNATBIND="bar -x - -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your - binder. Binder switches that are normally appended by @code{gnatmake} to - `@code{gnatbind}' are now appended to the end of @code{bar -x -y}. - - @item --GNATLINK=@var{linker_name} - @cindex @code{--GNATLINK=linker_name} (@code{gnatmake}) - Program used for linking. The default is `@code{gnatlink}'. You need to - use quotes around @var{linker_name} if @var{linker_name} contains spaces - or other separator characters. As an example @code{--GNATLINK="lan -x - -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your - linker. Linker switches that are normally appended by @code{gnatmake} to - `@code{gnatlink}' are now appended to the end of @code{lan -x -y}. - - - @item -a - @cindex @code{-a} (@code{gnatmake}) - Consider all files in the make process, even the GNAT internal system - files (for example, the predefined Ada library files), as well as any - locked files. Locked files are files whose ALI file is write-protected. - By default, - @code{gnatmake} does not check these files, - because the assumption is that the GNAT internal files are properly up - to date, and also that any write protected ALI files have been properly - installed. Note that if there is an installation problem, such that one - of these files is not up to date, it will be properly caught by the - binder. - You may have to specify this switch if you are working on GNAT - itself. @code{-a} is also useful in conjunction with - @code{-f} - if you need to recompile an entire application, - including run-time files, using special configuration pragma settings, - such as a non-standard @code{Float_Representation} pragma. - By default - @code{gnatmake -a} compiles all GNAT - internal files with - @code{gcc -c -gnatpg} rather than @code{gcc -c}. - - @item -b - @cindex @code{-b} (@code{gnatmake}) - Bind only. Can be combined with @code{-c} to do compilation - and binding, but no link. Can be combined with @code{-l} - to do binding and linking. When not combined with @code{-c} - all the units in the closure of the main program must have been previously - compiled and must be up to date. The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item -c - @cindex @code{-c} (@code{gnatmake}) - Compile only. Do not perform binding, except when @code{-b} - is also specified. Do not perform linking, except if both - @code{-b} and - @code{-l} are also specified. - If the root unit specified by @var{file_name} is not a main unit, this is the - default. Otherwise @code{gnatmake} will attempt binding and linking - unless all objects are up to date and the executable is more recent than - the objects. - - @item -C - @cindex @code{-C} (@code{gnatmake}) - Use a mapping file. A mapping file is a way to communicate to the compiler - two mappings: from unit names to file names (without any directory information) - and from file names to path names (with full directory information). - These mappings are used by the compiler to short-circuit the path search. - When @code{gnatmake} is invoked with this switch, it will create a mapping - file, initially populated by the project manager, if @code{-P} is used, - otherwise initially empty. Each invocation of the compiler will add the newly - accessed sources to the mapping file. This will improve the source search - during the next invocation of the compiler. - - @item -f - @cindex @code{-f} (@code{gnatmake}) - Force recompilations. Recompile all sources, even though some object - files may be up to date, but don't recompile predefined or GNAT internal - files or locked files (files with a write-protected ALI file), - unless the @code{-a} switch is also specified. - - @item - @item -i - @cindex @code{-i} (@code{gnatmake}) - In normal mode, @code{gnatmake} compiles all object files and ALI files - into the current directory. If the @code{-i} switch is used, - then instead object files and ALI files that already exist are overwritten - in place. This means that once a large project is organized into separate - directories in the desired manner, then @code{gnatmake} will automatically - maintain and update this organization. If no ALI files are found on the - Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), - the new object and ALI files are created in the - directory containing the source being compiled. If another organization - is desired, where objects and sources are kept in different directories, - a useful technique is to create dummy ALI files in the desired directories. - When detecting such a dummy file, @code{gnatmake} will be forced to recompile - the corresponding source file, and it will be put the resulting object - and ALI files in the directory where it found the dummy file. - - @item -j@var{n} - @cindex @code{-j} (@code{gnatmake}) - @cindex Parallel make - Use @var{n} processes to carry out the (re)compilations. On a - multiprocessor machine compilations will occur in parallel. In the - event of compilation errors, messages from various compilations might - get interspersed (but @code{gnatmake} will give you the full ordered - list of failing compiles at the end). If this is problematic, rerun - the make process with n set to 1 to get a clean list of messages. - - @item -k - @cindex @code{-k} (@code{gnatmake}) - Keep going. Continue as much as possible after a compilation error. To - ease the programmer's task in case of compilation errors, the list of - sources for which the compile fails is given when @code{gnatmake} - terminates. - - If @code{gnatmake} is invoked with several @file{file_names} and with this - switch, if there are compilation errors when building an executable, - @code{gnatmake} will not attempt to build the following executables. - - @item -l - @cindex @code{-l} (@code{gnatmake}) - Link only. Can be combined with @code{-b} to binding - and linking. Linking will not be performed if combined with - @code{-c} - but not with @code{-b}. - When not combined with @code{-b} - all the units in the closure of the main program must have been previously - compiled and must be up to date, and the main program need to have been bound. - The root unit specified by @var{file_name} - may be given without extension, with the source extension or, if no GNAT - Project File is specified, with the ALI file extension. - - @item -m - @cindex @code{-m} (@code{gnatmake}) - Specifies that the minimum necessary amount of recompilations - be performed. In this mode @code{gnatmake} ignores time - stamp differences when the only - modifications to a source file consist in adding/removing comments, - empty lines, spaces or tabs. This means that if you have changed the - comments in a source file or have simply reformatted it, using this - switch will tell gnatmake not to recompile files that depend on it - (provided other sources on which these files depend have undergone no - semantic modifications). Note that the debugging information may be - out of date with respect to the sources if the @code{-m} switch causes - a compilation to be switched, so the use of this switch represents a - trade-off between compilation time and accurate debugging information. - - @item -M - @cindex Dependencies, producing list - @cindex @code{-M} (@code{gnatmake}) - Check if all objects are up to date. If they are, output the object - dependences to @file{stdout} in a form that can be directly exploited in - a @file{Makefile}. By default, each source file is prefixed with its - (relative or absolute) directory name. This name is whatever you - specified in the various @code{-aI} - and @code{-I} switches. If you use - @code{gnatmake -M} - @code{-q} - (see below), only the source file names, - without relative paths, are output. If you just specify the - @code{-M} - switch, dependencies of the GNAT internal system files are omitted. This - is typically what you want. If you also specify - the @code{-a} switch, - dependencies of the GNAT internal files are also listed. Note that - dependencies of the objects in external Ada libraries (see switch - @code{-aL}@var{dir} in the following list) are never reported. - - @item -n - @cindex @code{-n} (@code{gnatmake}) - Don't compile, bind, or link. Checks if all objects are up to date. - If they are not, the full name of the first file that needs to be - recompiled is printed. - Repeated use of this option, followed by compiling the indicated source - file, will eventually result in recompiling all required units. - - @item -o @var{exec_name} - @cindex @code{-o} (@code{gnatmake}) - Output executable name. The name of the final executable program will be - @var{exec_name}. If the @code{-o} switch is omitted the default - name for the executable will be the name of the input file in appropriate form - for an executable file on the host system. - - This switch cannot be used when invoking @code{gnatmake} with several - @file{file_names}. - - @item -q - @cindex @code{-q} (@code{gnatmake}) - Quiet. When this flag is not set, the commands carried out by - @code{gnatmake} are displayed. - - @item -s - @cindex @code{-s} (@code{gnatmake}) - Recompile if compiler switches have changed since last compilation. - All compiler switches but -I and -o are taken into account in the - following way: - orders between different ``first letter'' switches are ignored, but - orders between same switches are taken into account. For example, - @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent - to @code{-O -g}. - - @item -u - @cindex @code{-u} (@code{gnatmake}) - Unique. Recompile at most the main file. It implies -c. Combined with - -f, it is equivalent to calling the compiler directly. - - @item -v - @cindex @code{-v} (@code{gnatmake}) - Verbose. Displays the reason for all recompilations @code{gnatmake} - decides are necessary. - - @item -z - @cindex @code{-z} (@code{gnatmake}) - No main subprogram. Bind and link the program even if the unit name - given on the command line is a package name. The resulting executable - will execute the elaboration routines of the package and its closure, - then the finalization routines. - - @item @code{gcc} @asis{switches} - The switch @code{-g} or any uppercase switch (other than @code{-A}, - @code{-L} or - @code{-S}) or any switch that is more than one character is passed to - @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.) - @end table - - @noindent - Source and library search path switches: - - @table @code - @item -aI@var{dir} - @cindex @code{-aI} (@code{gnatmake}) - When looking for source files also look in directory @var{dir}. - The order in which source files search is undertaken is - described in @ref{Search Paths and the Run-Time Library (RTL)}. - - @item -aL@var{dir} - @cindex @code{-aL} (@code{gnatmake}) - Consider @var{dir} as being an externally provided Ada library. - Instructs @code{gnatmake} to skip compilation units whose @file{.ali} - files have been located in directory @var{dir}. This allows you to have - missing bodies for the units in @var{dir} and to ignore out of date bodies - for the same units. You still need to specify - the location of the specs for these units by using the switches - @code{-aI@var{dir}} - or @code{-I@var{dir}}. - Note: this switch is provided for compatibility with previous versions - of @code{gnatmake}. The easier method of causing standard libraries - to be excluded from consideration is to write-protect the corresponding - ALI files. - - @item -aO@var{dir} - @cindex @code{-aO} (@code{gnatmake}) - When searching for library and object files, look in directory - @var{dir}. The order in which library files are searched is described in - @ref{Search Paths for gnatbind}. - - @item -A@var{dir} - @cindex Search paths, for @code{gnatmake} - @cindex @code{-A} (@code{gnatmake}) - Equivalent to @code{-aL@var{dir} - -aI@var{dir}}. - - @item -I@var{dir} - @cindex @code{-I} (@code{gnatmake}) - Equivalent to @code{-aO@var{dir} - -aI@var{dir}}. - - @item -I- - @cindex @code{-I-} (@code{gnatmake}) - @cindex Source files, suppressing search - Do not look for source files in the directory containing the source - file named in the command line. - Do not look for ALI or object files in the directory - where @code{gnatmake} was invoked. - - @item -L@var{dir} - @cindex @code{-L} (@code{gnatmake}) - @cindex Linker libraries - Add directory @var{dir} to the list of directories in which the linker - Furthermore, under Windows, the sources pointed to by the libraries path - set in the registry are not searched for. - will search for libraries. This is equivalent to - @code{-largs -L}@var{dir}. - - @item -nostdinc - @cindex @code{-nostdinc} (@code{gnatmake}) - Do not look for source files in the system default directory. - - @item -nostdlib - @cindex @code{-nostdlib} (@code{gnatmake}) - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatmake}) - Specifies the default location of the runtime library. We look for the runtime - in the following directories, and stop as soon as a valid runtime is found - ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present): - - @itemize @bullet - @item /$rts_path - - @item /$rts_path - - @item /rts-$rts_path - @end itemize - - @noindent - The selected path is handled like a normal RTS path. - - @end table - - @node Mode Switches for gnatmake - @section Mode Switches for @code{gnatmake} - - @noindent - The mode switches (referred to as @code{mode_switches}) allow the - inclusion of switches that are to be passed to the compiler itself, the - binder or the linker. The effect of a mode switch is to cause all - subsequent switches up to the end of the switch list, or up to the next - mode switch, to be interpreted as switches to be passed on to the - designated component of GNAT. - - @table @code - @item -cargs @var{switches} - @cindex @code{-cargs} (@code{gnatmake}) - Compiler switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all compile steps performed by @code{gnatmake}. - - @item -bargs @var{switches} - @cindex @code{-bargs} (@code{gnatmake}) - Binder switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all bind steps performed by @code{gnatmake}. - - @item -largs @var{switches} - @cindex @code{-largs} (@code{gnatmake}) - Linker switches. Here @var{switches} is a list of switches - that are valid switches for @code{gcc}. They will be passed on to - all link steps performed by @code{gnatmake}. - @end table - - @node Notes on the Command Line - @section Notes on the Command Line - - @noindent - This section contains some additional useful notes on the operation - of the @code{gnatmake} command. - - @itemize @bullet - @item - @cindex Recompilation, by @code{gnatmake} - If @code{gnatmake} finds no ALI files, it recompiles the main program - and all other units required by the main program. - This means that @code{gnatmake} - can be used for the initial compile, as well as during subsequent steps of - the development cycle. - - @item - If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb} - is a subunit or body of a generic unit, @code{gnatmake} recompiles - @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a - warning. - - @item - In @code{gnatmake} the switch @code{-I} - is used to specify both source and - library file paths. Use @code{-aI} - instead if you just want to specify - source paths only and @code{-aO} - if you want to specify library paths - only. - - @item - @code{gnatmake} examines both an ALI file and its corresponding object file - for consistency. If an ALI is more recent than its corresponding object, - or if the object file is missing, the corresponding source will be recompiled. - Note that @code{gnatmake} expects an ALI and the corresponding object file - to be in the same directory. - - @item - @code{gnatmake} will ignore any files whose ALI file is write-protected. - This may conveniently be used to exclude standard libraries from - consideration and in particular it means that the use of the - @code{-f} switch will not recompile these files - unless @code{-a} is also specified. - - @item - @code{gnatmake} has been designed to make the use of Ada libraries - particularly convenient. Assume you have an Ada library organized - as follows: @var{obj-dir} contains the objects and ALI files for - of your Ada compilation units, - whereas @var{include-dir} contains the - specs of these units, but no bodies. Then to compile a unit - stored in @code{main.adb}, which uses this Ada library you would just type - - @smallexample - $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main - @end smallexample - - @item - Using @code{gnatmake} along with the - @code{-m (minimal recompilation)} - switch provides a mechanism for avoiding unnecessary rcompilations. Using - this switch, - you can update the comments/format of your - source files without having to recompile everything. Note, however, that - adding or deleting lines in a source files may render its debugging - info obsolete. If the file in question is a spec, the impact is rather - limited, as that debugging info will only be useful during the - elaboration phase of your program. For bodies the impact can be more - significant. In all events, your debugger will warn you if a source file - is more recent than the corresponding object, and alert you to the fact - that the debugging information may be out of date. - @end itemize - - @node How gnatmake Works - @section How @code{gnatmake} Works - - @noindent - Generally @code{gnatmake} automatically performs all necessary - recompilations and you don't need to worry about how it works. However, - it may be useful to have some basic understanding of the @code{gnatmake} - approach and in particular to understand how it uses the results of - previous compilations without incorrectly depending on them. - - First a definition: an object file is considered @dfn{up to date} if the - corresponding ALI file exists and its time stamp predates that of the - object file and if all the source files listed in the - dependency section of this ALI file have time stamps matching those in - the ALI file. This means that neither the source file itself nor any - files that it depends on have been modified, and hence there is no need - to recompile this file. - - @code{gnatmake} works by first checking if the specified main unit is up - to date. If so, no compilations are required for the main unit. If not, - @code{gnatmake} compiles the main program to build a new ALI file that - reflects the latest sources. Then the ALI file of the main unit is - examined to find all the source files on which the main program depends, - and @code{gnatmake} recursively applies the above procedure on all these files. - - This process ensures that @code{gnatmake} only trusts the dependencies - in an existing ALI file if they are known to be correct. Otherwise it - always recompiles to determine a new, guaranteed accurate set of - dependencies. As a result the program is compiled "upside down" from what may - be more familiar as the required order of compilation in some other Ada - systems. In particular, clients are compiled before the units on which - they depend. The ability of GNAT to compile in any order is critical in - allowing an order of compilation to be chosen that guarantees that - @code{gnatmake} will recompute a correct set of new dependencies if - necessary. - - When invoking @code{gnatmake} with several @var{file_names}, if a unit is - imported by several of the executables, it will be recompiled at most once. - - @node Examples of gnatmake Usage - @section Examples of @code{gnatmake} Usage - - @table @code - @item gnatmake hello.adb - Compile all files necessary to bind and link the main program - @file{hello.adb} (containing unit @code{Hello}) and bind and link the - resulting object files to generate an executable file @file{hello}. - - @item gnatmake main1 main2 main3 - Compile all files necessary to bind and link the main programs - @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb} - (containing unit @code{Main2}) and @file{main3.adb} - (containing unit @code{Main3}) and bind and link the resulting object files - to generate three executable files @file{main1}, - @file{main2} - and @file{main3}. - - @item gnatmake -q Main_Unit -cargs -O2 -bargs -l - - Compile all files necessary to bind and link the main program unit - @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will - be done with optimization level 2 and the order of elaboration will be - listed by the binder. @code{gnatmake} will operate in quiet mode, not - displaying commands it is executing. - @end table - - @node Renaming Files Using gnatchop - @chapter Renaming Files Using @code{gnatchop} - @findex gnatchop - - @noindent - This chapter discusses how to handle files with multiple units by using - the @code{gnatchop} utility. This utility is also useful in renaming - files to meet the standard GNAT default file naming conventions. - - @menu - * Handling Files with Multiple Units:: - * Operating gnatchop in Compilation Mode:: - * Command Line for gnatchop:: - * Switches for gnatchop:: - * Examples of gnatchop Usage:: - @end menu - - @node Handling Files with Multiple Units - @section Handling Files with Multiple Units - - @noindent - The basic compilation model of GNAT requires that a file submitted to the - compiler have only one unit and there be a strict correspondence - between the file name and the unit name. - - The @code{gnatchop} utility allows both of these rules to be relaxed, - allowing GNAT to process files which contain multiple compilation units - and files with arbitrary file names. @code{gnatchop} - reads the specified file and generates one or more output files, - containing one unit per file. The unit and the file name correspond, - as required by GNAT. - - If you want to permanently restructure a set of "foreign" files so that - they match the GNAT rules, and do the remaining development using the - GNAT structure, you can simply use @code{gnatchop} once, generate the - new set of files and work with them from that point on. - - Alternatively, if you want to keep your files in the "foreign" format, - perhaps to maintain compatibility with some other Ada compilation - system, you can set up a procedure where you use @code{gnatchop} each - time you compile, regarding the source files that it writes as temporary - files that you throw away. - - @node Operating gnatchop in Compilation Mode - @section Operating gnatchop in Compilation Mode - - @noindent - The basic function of @code{gnatchop} is to take a file with multiple units - and split it into separate files. The boundary between files is reasonably - clear, except for the issue of comments and pragmas. In default mode, the - rule is that any pragmas between units belong to the previous unit, except - that configuration pragmas always belong to the following unit. Any comments - belong to the following unit. These rules - almost always result in the right choice of - the split point without needing to mark it explicitly and most users will - find this default to be what they want. In this default mode it is incorrect to - submit a file containing only configuration pragmas, or one that ends in - configuration pragmas, to @code{gnatchop}. - - However, using a special option to activate "compilation mode", - @code{gnatchop} - can perform another function, which is to provide exactly the semantics - required by the RM for handling of configuration pragmas in a compilation. - In the absence of configuration pragmas (at the main file level), this - option has no effect, but it causes such configuration pragmas to be handled - in a quite different manner. - - First, in compilation mode, if @code{gnatchop} is given a file that consists of - only configuration pragmas, then this file is appended to the - @file{gnat.adc} file in the current directory. This behavior provides - the required behavior described in the RM for the actions to be taken - on submitting such a file to the compiler, namely that these pragmas - should apply to all subsequent compilations in the same compilation - environment. Using GNAT, the current directory, possibly containing a - @file{gnat.adc} file is the representation - of a compilation environment. For more information on the - @file{gnat.adc} file, see the section on handling of configuration - pragmas @pxref{Handling of Configuration Pragmas}. - - Second, in compilation mode, if @code{gnatchop} - is given a file that starts with - configuration pragmas, and contains one or more units, then these - configuration pragmas are prepended to each of the chopped files. This - behavior provides the required behavior described in the RM for the - actions to be taken on compiling such a file, namely that the pragmas - apply to all units in the compilation, but not to subsequently compiled - units. - - Finally, if configuration pragmas appear between units, they are appended - to the previous unit. This results in the previous unit being illegal, - since the compiler does not accept configuration pragmas that follow - a unit. This provides the required RM behavior that forbids configuration - pragmas other than those preceding the first compilation unit of a - compilation. - - For most purposes, @code{gnatchop} will be used in default mode. The - compilation mode described above is used only if you need exactly - accurate behavior with respect to compilations, and you have files - that contain multiple units and configuration pragmas. In this - circumstance the use of @code{gnatchop} with the compilation mode - switch provides the required behavior, and is for example the mode - in which GNAT processes the ACVC tests. - - @node Command Line for gnatchop - @section Command Line for @code{gnatchop} - - @noindent - The @code{gnatchop} command has the form: - - @smallexample - $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...] - [@var{directory}] - @end smallexample - - @noindent - The only required argument is the file name of the file to be chopped. - There are no restrictions on the form of this file name. The file itself - contains one or more Ada units, in normal GNAT format, concatenated - together. As shown, more than one file may be presented to be chopped. - - When run in default mode, @code{gnatchop} generates one output file in - the current directory for each unit in each of the files. - - @var{directory}, if specified, gives the name of the directory to which - the output files will be written. If it is not specified, all files are - written to the current directory. - - For example, given a - file called @file{hellofiles} containing - - @smallexample - @group - @cartouche - @b{procedure} hello; - - @b{with} Text_IO; @b{use} Text_IO; - @b{procedure} hello @b{is} - @b{begin} - Put_Line ("Hello"); - @b{end} hello; - @end cartouche - @end group - @end smallexample - - @noindent - the command - - @smallexample - $ gnatchop hellofiles - @end smallexample - - @noindent - generates two files in the current directory, one called - @file{hello.ads} containing the single line that is the procedure spec, - and the other called @file{hello.adb} containing the remaining text. The - original file is not affected. The generated files can be compiled in - the normal manner. - - @node Switches for gnatchop - @section Switches for @code{gnatchop} - - @noindent - @code{gnatchop} recognizes the following switches: - - @table @code - - @item -c - @cindex @code{-c} (@code{gnatchop}) - Causes @code{gnatchop} to operate in compilation mode, in which - configuration pragmas are handled according to strict RM rules. See - previous section for a full description of this mode. - - @item -gnatxxx - This passes the given @option{-gnatxxx} switch to @code{gnat} which is - used to parse the given file. Not all @code{xxx} options make sense, - but for example, the use of @option{-gnati2} allows @code{gnatchop} to - process a source file that uses Latin-2 coding for identifiers. - - @item -h - Causes @code{gnatchop} to generate a brief help summary to the standard - output file showing usage information. - - @item -k@var{mm} - @cindex @code{-k} (@code{gnatchop}) - Limit generated file names to the specified number @code{mm} - of characters. - This is useful if the - resulting set of files is required to be interoperable with systems - which limit the length of file names. - No space is allowed between the @code{-k} and the numeric value. The numeric - value may be omitted in which case a default of @code{-k8}, - suitable for use - with DOS-like file systems, is used. If no @code{-k} switch - is present then - there is no limit on the length of file names. - - @item -p - @cindex @code{-p} (@code{gnatchop}) - Causes the file modification time stamp of the input file to be - preserved and used for the time stamp of the output file(s). This may be - useful for preserving coherency of time stamps in an enviroment where - @code{gnatchop} is used as part of a standard build process. - - @item -q - @cindex @code{-q} (@code{gnatchop}) - Causes output of informational messages indicating the set of generated - files to be suppressed. Warnings and error messages are unaffected. - - @item -r - @cindex @code{-r} (@code{gnatchop}) - @findex Source_Reference - Generate @code{Source_Reference} pragmas. Use this switch if the output - files are regarded as temporary and development is to be done in terms - of the original unchopped file. This switch causes - @code{Source_Reference} pragmas to be inserted into each of the - generated files to refers back to the original file name and line number. - The result is that all error messages refer back to the original - unchopped file. - In addition, the debugging information placed into the object file (when - the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also - refers back to this original file so that tools like profilers and - debuggers will give information in terms of the original unchopped file. - - If the original file to be chopped itself contains - a @code{Source_Reference} - pragma referencing a third file, then gnatchop respects - this pragma, and the generated @code{Source_Reference} pragmas - in the chopped file refer to the original file, with appropriate - line numbers. This is particularly useful when @code{gnatchop} - is used in conjunction with @code{gnatprep} to compile files that - contain preprocessing statements and multiple units. - - @item -v - @cindex @code{-v} (@code{gnatchop}) - Causes @code{gnatchop} to operate in verbose mode. The version - number and copyright notice are output, as well as exact copies of - the gnat1 commands spawned to obtain the chop control information. - - @item -w - @cindex @code{-w} (@code{gnatchop}) - Overwrite existing file names. Normally @code{gnatchop} regards it as a - fatal error if there is already a file with the same name as a - file it would otherwise output, in other words if the files to be - chopped contain duplicated units. This switch bypasses this - check, and causes all but the last instance of such duplicated - units to be skipped. - - @item --GCC=xxxx - @cindex @code{--GCC=} (@code{gnatchop}) - Specify the path of the GNAT parser to be used. When this switch is used, - no attempt is made to add the prefix to the GNAT parser executable. - @end table - - @node Examples of gnatchop Usage - @section Examples of @code{gnatchop} Usage - - @table @code - @item gnatchop -w hello_s.ada ichbiah/files - - Chops the source file @file{hello_s.ada}. The output files will be - placed in the directory @file{ichbiah/files}, - overwriting any - files with matching names in that directory (no files in the current - directory are modified). - - @item gnatchop archive - Chops the source file @file{archive} - into the current directory. One - useful application of @code{gnatchop} is in sending sets of sources - around, for example in email messages. The required sources are simply - concatenated (for example, using a Unix @code{cat} - command), and then - @code{gnatchop} is used at the other end to reconstitute the original - file names. - - @item gnatchop file1 file2 file3 direc - Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing - the resulting files in the directory @file{direc}. Note that if any units - occur more than once anywhere within this set of files, an error message - is generated, and no files are written. To override this check, use the - @code{-w} switch, - in which case the last occurrence in the last file will - be the one that is output, and earlier duplicate occurrences for a given - unit will be skipped. - @end table - - @node Configuration Pragmas - @chapter Configuration Pragmas - @cindex Configuration pragmas - @cindex Pragmas, configuration - - @noindent - In Ada 95, configuration pragmas include those pragmas described as - such in the Ada 95 Reference Manual, as well as - implementation-dependent pragmas that are configuration pragmas. See the - individual descriptions of pragmas in the GNAT Reference Manual for - details on these additional GNAT-specific configuration pragmas. Most - notably, the pragma @code{Source_File_Name}, which allows - specifying non-default names for source files, is a configuration - pragma. The following is a complete list of configuration pragmas - recognized by @code{GNAT}: - - @smallexample - Ada_83 - Ada_95 - C_Pass_By_Copy - Component_Alignment - Discard_Names - Elaboration_Checks - Eliminate - Extend_System - Extensions_Allowed - External_Name_Casing - Float_Representation - Initialize_Scalars - License - Locking_Policy - Long_Float - No_Run_Time - Normalize_Scalars - Polling - Propagate_Exceptions - Queuing_Policy - Ravenscar - Restricted_Run_Time - Restrictions - Reviewable - Source_File_Name - Style_Checks - Suppress - Task_Dispatching_Policy - Unsuppress - Use_VADS_Size - Warnings - Validity_Checks - @end smallexample - - @menu - * Handling of Configuration Pragmas:: - * The Configuration Pragmas Files:: - @end menu - - @node Handling of Configuration Pragmas - @section Handling of Configuration Pragmas - - Configuration pragmas may either appear at the start of a compilation - unit, in which case they apply only to that unit, or they may apply to - all compilations performed in a given compilation environment. - - GNAT also provides the @code{gnatchop} utility to provide an automatic - way to handle configuration pragmas following the semantics for - compilations (that is, files with multiple units), described in the RM. - See section @pxref{Operating gnatchop in Compilation Mode} for details. - However, for most purposes, it will be more convenient to edit the - @file{gnat.adc} file that contains configuration pragmas directly, - as described in the following section. - - @node The Configuration Pragmas Files - @section The Configuration Pragmas Files - @cindex @file{gnat.adc} - - @noindent - In GNAT a compilation environment is defined by the current - directory at the time that a compile command is given. This current - directory is searched for a file whose name is @file{gnat.adc}. If - this file is present, it is expected to contain one or more - configuration pragmas that will be applied to the current compilation. - However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not - considered. - - Configuration pragmas may be entered into the @file{gnat.adc} file - either by running @code{gnatchop} on a source file that consists only of - configuration pragmas, or more conveniently by - direct editing of the @file{gnat.adc} file, which is a standard format - source file. - - In addition to @file{gnat.adc}, one additional file containing configuration - pragmas may be applied to the current compilation using the switch - @option{-gnatec}@var{path}. @var{path} must designate an existing file that - contains only configuration pragmas. These configuration pragmas are - in addition to those found in @file{gnat.adc} (provided @file{gnat.adc} - is present and switch @option{-gnatA} is not used). - - It is allowed to specify several switches @option{-gnatec}, however only - the last one on the command line will be taken into account. - - - @node Handling Arbitrary File Naming Conventions Using gnatname - @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} - @cindex Arbitrary File Naming Conventions - - @menu - * Arbitrary File Naming Conventions:: - * Running gnatname:: - * Switches for gnatname:: - * Examples of gnatname Usage:: - @end menu - - @node Arbitrary File Naming Conventions - @section Arbitrary File Naming Conventions - - @noindent - The GNAT compiler must be able to know the source file name of a compilation unit. - When using the standard GNAT default file naming conventions (@code{.ads} for specs, - @code{.adb} for bodies), the GNAT compiler does not need additional information. - - @noindent - When the source file names do not follow the standard GNAT default file naming - conventions, the GNAT compiler must be given additional information through - a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file. - When the non standard file naming conventions are well-defined, a small number of - pragmas @code{Source_File_Name} specifying a naming pattern - (see @ref{Alternative File Naming Schemes}) may be sufficient. However, - if the file naming conventions are irregular or arbitrary, a number - of pragma @code{Source_File_Name} for individual compilation units must be defined. - To help maintain the correspondence between compilation unit names and - source file names within the compiler, - GNAT provides a tool @code{gnatname} to generate the required pragmas for a - set of files. - - @node Running gnatname - @section Running @code{gnatname} - - @noindent - The usual form of the @code{gnatname} command is - - @smallexample - $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}] - @end smallexample - - @noindent - All of the arguments are optional. If invoked without any argument, - @code{gnatname} will display its usage. - - @noindent - When used with at least one naming pattern, @code{gnatname} will attempt to - find all the compilation units in files that follow at least one of the - naming patterns. To find these compilation units, - @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all - regular files. - - @noindent - One or several Naming Patterns may be given as arguments to @code{gnatname}. - Each Naming Pattern is enclosed between double quotes. - A Naming Pattern is a regular expression similar to the wildcard patterns - used in file names by the Unix shells or the DOS prompt. - - @noindent - Examples of Naming Patterns are - - @smallexample - "*.[12].ada" - "*.ad[sb]*" - "body_*" "spec_*" - @end smallexample - - @noindent - For a more complete description of the syntax of Naming Patterns, see the second kind - of regular expressions described in @file{g-regexp.ads} (the "Glob" regular - expressions). - - @noindent - When invoked with no switches, @code{gnatname} will create a configuration - pragmas file @file{gnat.adc} in the current working directory, with pragmas - @code{Source_File_Name} for each file that contains a valid Ada unit. - - @node Switches for gnatname - @section Switches for @code{gnatname} - - @noindent - Switches for @code{gnatname} must precede any specified Naming Pattern. - - @noindent - You may specify any of the following switches to @code{gnatname}: - - @table @code - - @item -c@file{file} - @cindex @code{-c} (@code{gnatname}) - Create a configuration pragmas file @file{file} (instead of the default - @file{gnat.adc}). There may be zero, one or more space between @code{-c} and - @file{file}. @file{file} may include directory information. @file{file} must be - writeable. There may be only one switch @code{-c}. When a switch @code{-c} is - specified, no switch @code{-P} may be specified (see below). - - @item -d@file{dir} - @cindex @code{-d} (@code{gnatname}) - Look for source files in directory @file{dir}. There may be zero, one or more spaces - between @code{-d} and @file{dir}. When a switch @code{-d} is specified, - the current working directory will not be searched for source files, unless it - is explictly - specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be - specified. If @file{dir} is a relative path, it is relative to the directory of - the configuration pragmas file specified with switch @code{-c}, or to the directory - of the project file specified with switch @code{-P} or, if neither switch @code{-c} - nor switch @code{-P} are specified, it is relative to the current working - directory. The directory - specified with switch @code{-c} must exist and be readable. - - @item -D@file{file} - @cindex @code{-D} (@code{gnatname}) - Look for source files in all directories listed in text file @file{file}. There may be - zero, one or more spaces between @code{-d} and @file{dir}. @file{file} - must be an existing, readable text file. Each non empty line in @file{file} must be - a directory. Specifying switch @code{-D} is equivalent to specifying as many switches - @code{-d} as there are non empty lines in @file{file}. - - @item -h - @cindex @code{-h} (@code{gnatname}) - Output usage (help) information. The output is written to @file{stdout}. - - @item -P@file{proj} - @cindex @code{-P} (@code{gnatname}) - Create or update project file @file{proj}. There may be zero, one or more space - between @code{-P} and @file{proj}. @file{proj} may include directory information. - @file{proj} must be writeable. There may be only one switch @code{-P}. - When a switch @code{-P} is specified, no switch @code{-c} may be specified. - - @item -v - @cindex @code{-v} (@code{gnatname}) - Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes - name of the file written, the name of the directories to search and, for each file - in those directories whose name matches at least one of the Naming Patterns, an - indication of whether the file contains a unit, and if so the name of the unit. - - @item -v -v - Very Verbose mode. In addition to the output produced in verbose mode, for each file - in the searched directories whose name matches none of the Naming Patterns, an - indication is given that there is no match. - - @item -x@file{pattern} - Excluded patterns. Using this switch, it is possible to exclude some files - that would match the name patterns. For example, - @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files - with the @file{.ada} extension, except those whose names end with - @file{_nt.ada}. - - @end table - - @node Examples of gnatname Usage - @section Examples of @code{gnatname} Usage - - @smallexample - $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" - @end smallexample - - In this example, the directory @file{/home/me} must already exist and be - writeable. In addition, the directory @file{/home/me/sources} (specified by - @code{-d sources}) must exist and be readable. Note the optional spaces after - @code{-c} and @code{-d}. - - @smallexample - $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" - @end smallexample - - Note that several switches @code{-d} may be used, even in conjunction with one - or several switches @code{-D}. Several Naming Patterns and one excluded pattern - are used in this example. - - - @c ***************************************** - @c * G N A T P r o j e c t M a n a g e r * - @c ***************************************** - @node GNAT Project Manager - @chapter GNAT Project Manager - - @menu - * Introduction:: - * Examples of Project Files:: - * Project File Syntax:: - * Objects and Sources in Project Files:: - * Importing Projects:: - * Project Extension:: - * External References in Project Files:: - * Packages in Project Files:: - * Variables from Imported Projects:: - * Naming Schemes:: - * Library Projects:: - * Switches Related to Project Files:: - * Tools Supporting Project Files:: - * An Extended Example:: - * Project File Complete Syntax:: - @end menu - - - @c **************** - @c * Introduction * - @c **************** - - @node Introduction - @section Introduction - - @noindent - This chapter describes GNAT's @emph{Project Manager}, a facility that - lets you configure various properties for a collection of source files. In - particular, you can specify: - @itemize @bullet - @item - The directory or set of directories containing the source files, and/or the - names of the specific source files themselves - @item - The directory in which the compiler's output - (@file{ALI} files, object files, tree files) will be placed - @item - The directory in which the executable programs will be placed - @item - Switch settings for any of the project-enabled tools (@command{gnatmake}, - compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind}); - you can apply these settings either globally or to individual units - @item - The source files containing the main subprogram(s) to be built - @item - The source programming language(s) (currently Ada and/or C) - @item - Source file naming conventions; you can specify these either globally or for - individual units - @end itemize - - @menu - * Project Files:: - @end menu - - @node Project Files - @subsection Project Files - - @noindent - A @dfn{project} is a specific set of values for these properties. You can - define a project's settings in a @dfn{project file}, a text file with an - Ada-like syntax; a property value is either a string or a list of strings. - Properties that are not explicitly set receive default values. A project - file may interrogate the values of @dfn{external variables} (user-defined - command-line switches or environment variables), and it may specify property - settings conditionally, based on the value of such variables. - - In simple cases, a project's source files depend only on other source files - in the same project, or on the predefined libraries. ("Dependence" is in - the technical sense; for example, one Ada unit "with"ing another.) However, - the Project Manager also allows much more sophisticated arrangements, - with the source files in one project depending on source files in other - projects: - @itemize @bullet - @item - One project can @emph{import} other projects containing needed source files. - @item - You can organize GNAT projects in a hierarchy: a @emph{child} project - can extend a @emph{parent} project, inheriting the parent's source files and - optionally overriding any of them with alternative versions - @end itemize - - @noindent - More generally, the Project Manager lets you structure large development - efforts into hierarchical subsystems, with build decisions deferred to the - subsystem level and thus different compilation environments (switch settings) - used for different subsystems. - - The Project Manager is invoked through the @option{-P@emph{projectfile}} - switch to @command{gnatmake} or to the @command{gnat} front driver. - If you want to define (on the command line) an external variable that is - queried by the project file, additionally use the - @option{-X@emph{vbl}=@emph{value}} switch. - The Project Manager parses and interprets the project file, and drives the - invoked tool based on the project settings. - - The Project Manager supports a wide range of development strategies, - for systems of all sizes. Some typical practices that are easily handled: - @itemize @bullet - @item - Using a common set of source files, but generating object files in different - directories via different switch settings - @item - Using a mostly-shared set of source files, but with different versions of - some unit or units - @end itemize - - @noindent - The destination of an executable can be controlled inside a project file - using the @option{-o} switch. In the absence of such a switch either inside - the project file or on the command line, any executable files generated by - @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified - in the project file. If no @code{Exec_Dir} is specified, they will be placed - in the object directory of the project. - - You can use project files to achieve some of the effects of a source - versioning system (for example, defining separate projects for - the different sets of sources that comprise different releases) but the - Project Manager is independent of any source configuration management tools - that might be used by the developers. - - The next section introduces the main features of GNAT's project facility - through a sequence of examples; subsequent sections will present the syntax - and semantics in more detail. - - - @c ***************************** - @c * Examples of Project Files * - @c ***************************** - - @node Examples of Project Files - @section Examples of Project Files - @noindent - This section illustrates some of the typical uses of project files and - explains their basic structure and behavior. - - @menu - * Common Sources with Different Switches and Different Output Directories:: - * Using External Variables:: - * Importing Other Projects:: - * Extending a Project:: - @end menu - - @node Common Sources with Different Switches and Different Output Directories - @subsection Common Sources with Different Switches and Different Output Directories - - @menu - * Source Files:: - * Specifying the Object Directory:: - * Specifying the Exec Directory:: - * Project File Packages:: - * Specifying Switch Settings:: - * Main Subprograms:: - * Source File Naming Conventions:: - * Source Language(s):: - @end menu - - @noindent - Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and - @file{proc.adb} are in the @file{/common} directory. The file - @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s - package @code{Pack}. We want to compile these source files under two sets - of switches: - @itemize @bullet - @item - When debugging, we want to pass the @option{-g} switch to @command{gnatmake}, - and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the - compiler; the compiler's output is to appear in @file{/common/debug} - @item - When preparing a release version, we want to pass the @option{-O2} switch to - the compiler; the compiler's output is to appear in @file{/common/release} - @end itemize - - @noindent - The GNAT project files shown below, respectively @file{debug.gpr} and - @file{release.gpr} in the @file{/common} directory, achieve these effects. - - Diagrammatically: - @smallexample - @group - /common - debug.gpr - release.gpr - pack.ads - pack.adb - proc.adb - @end group - @group - /common/debug @{-g, -gnata, -gnato, -gnatE@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @group - /common/release @{-O2@} - proc.ali, proc.o - pack.ali, pack.o - @end group - @end smallexample - Here are the project files: - @smallexample - @group - project Debug is - for Object_Dir use "debug"; - for Main use ("proc"); - - package Builder is - for Default_Switches ("Ada") use ("-g"); - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") - use ("-fstack-check", "-gnata", "-gnato", "-gnatE"); - end Compiler; - end Debug; - @end group - @end smallexample - - @smallexample - @group - project Release is - for Object_Dir use "release"; - for Exec_Dir use "."; - for Main use ("proc"); - - package Compiler is - for Default_Switches ("Ada") use ("-O2"); - end Compiler; - end Release; - @end group - @end smallexample - - @noindent - The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case - insensitive), and analogously the project defined by @file{release.gpr} is - @code{"Release"}. For consistency the file should have the same name as the - project, and the project file's extension should be @code{"gpr"}. These - conventions are not required, but a warning is issued if they are not followed. - - If the current directory is @file{/temp}, then the command - @smallexample - gnatmake -P/common/debug.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/debug}, and the @code{proc} - executable also in @file{/common/debug}, using the switch settings defined in - the project file. - - Likewise, the command - @smallexample - gnatmake -P/common/release.gpr - @end smallexample - - @noindent - generates object and ALI files in @file{/common/release}, and the @code{proc} - executable in @file{/common}, using the switch settings from the project file. - - @node Source Files - @unnumberedsubsubsec Source Files - - @noindent - If a project file does not explicitly specify a set of source directories or - a set of source files, then by default the project's source files are the - Ada source files in the project file directory. Thus @file{pack.ads}, - @file{pack.adb}, and @file{proc.adb} are the source files for both projects. - - @node Specifying the Object Directory - @unnumberedsubsubsec Specifying the Object Directory - - @noindent - Several project properties are modeled by Ada-style @emph{attributes}; - you define the property by supplying the equivalent of an Ada attribute - definition clause in the project file. - A project's object directory is such a property; the corresponding - attribute is @code{Object_Dir}, and its value is a string expression. A - directory may be specified either as absolute or as relative; in the latter - case, it is relative to the project file directory. Thus the compiler's - output is directed to @file{/common/debug} (for the @code{Debug} project) - and to @file{/common/release} (for the @code{Release} project). If - @code{Object_Dir} is not specified, then the default is the project file - directory. - - @node Specifying the Exec Directory - @unnumberedsubsubsec Specifying the Exec Directory - - @noindent - A project's exec directory is another property; the corresponding - attribute is @code{Exec_Dir}, and its value is also a string expression, - either specified as relative or absolute. If @code{Exec_Dir} is not specified, - then the default is the object directory (which may also be the project file - directory if attribute @code{Object_Dir} is not specified). Thus the executable - is placed in @file{/common/debug} for the @code{Debug} project (attribute - @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release} - project. - - @node Project File Packages - @unnumberedsubsubsec Project File Packages - - @noindent - A GNAT tool integrated with the Project Manager is modeled by a - corresponding package in the project file. - The @code{Debug} project defines the packages @code{Builder} - (for @command{gnatmake}) and @code{Compiler}; - the @code{Release} project defines only the @code{Compiler} package. - - The Ada package syntax is not to be taken literally. Although packages in - project files bear a surface resemblance to packages in Ada source code, the - notation is simply a way to convey a grouping of properties for a named - entity. Indeed, the package names permitted in project files are restricted - to a predefined set, corresponding to the project-aware tools, and the contents - of packages are limited to a small set of constructs. - The packages in the example above contain attribute definitions. - - - @node Specifying Switch Settings - @unnumberedsubsubsec Specifying Switch Settings - - @noindent - Switch settings for a project-aware tool can be specified through attributes - in the package corresponding to the tool. - The example above illustrates one of the relevant attributes, - @code{Default_Switches}, defined in the packages in both project files. - Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is - known as an @emph{associative array}. When you define this attribute, you must - supply an "index" (a literal string), and the effect of the attribute - definition is to set the value of the "array" at the specified "index". - For the @code{Default_Switches} attribute, the index is a programming - language (in our case, Ada) , and the value specified (after @code{use}) - must be a list of string expressions. - - The attributes permitted in project files are restricted to a predefined set. - Some may appear at project level, others in packages. - For any attribute that is an associate array, the index must always be a - literal string, but the restrictions on this string (e.g., a file name or a - language name) depend on the individual attribute. - Also depending on the attribute, its specified value will need to be either a - string or a string list. - - In the @code{Debug} project, we set the switches for two tools, - @command{gnatmake} and the compiler, and thus we include corresponding - packages, with each package defining the @code{Default_Switches} attribute - with index @code{"Ada"}. - Note that the package corresponding to - @command{gnatmake} is named @code{Builder}. The @code{Release} project is - similar, but with just the @code{Compiler} package. - - In project @code{Debug} above the switches starting with @option{-gnat} that - are specified in package @code{Compiler} could have been placed in package - @code{Builder}, since @command{gnatmake} transmits all such switches to the - compiler. - - @node Main Subprograms - @unnumberedsubsubsec Main Subprograms - - @noindent - One of the properties of a project is its list of main subprograms (actually - a list of names of source files containing main subprograms, with the file - extension optional. This property is captured in the @code{Main} attribute, - whose value is a list of strings. If a project defines the @code{Main} - attribute, then you do not need to identify the main subprogram(s) when - invoking @command{gnatmake} (see @ref{gnatmake and Project Files}). - - @node Source File Naming Conventions - @unnumberedsubsubsec Source File Naming Conventions - - @noindent - Since the project files do not specify any source file naming conventions, - the GNAT defaults are used. The mechanism for defining source file naming - conventions -- a package named @code{Naming} -- will be described below - (@pxref{Naming Schemes}). - - @node Source Language(s) - @unnumberedsubsubsec Source Language(s) - - @noindent - Since the project files do not specify a @code{Languages} attribute, by - default the GNAT tools assume that the language of the project file is Ada. - More generally, a project can comprise source files - in Ada, C, and/or other languages. - - @node Using External Variables - @subsection Using External Variables - - @noindent - Instead of supplying different project files for debug and release, we can - define a single project file that queries an external variable (set either - on the command line or via an environment variable) in order to - conditionally define the appropriate settings. Again, assume that the - source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are - located in directory @file{/common}. The following project file, - @file{build.gpr}, queries the external variable named @code{STYLE} and - defines an object directory and switch settings based on whether the value - is @code{"deb"} (debug) or @code{"rel"} (release), where the default is - @code{"deb"}. - - @smallexample - @group - project Build is - for Main use ("proc"); - - type Style_Type is ("deb", "rel"); - Style : Style_Type := external ("STYLE", "deb"); - - case Style is - when "deb" => - for Object_Dir use "debug"; - - when "rel" => - for Object_Dir use "release"; - for Exec_Dir use "."; - end case; - @end group - - @group - package Builder is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-g"); - end case; - - end Builder; - @end group - - @group - package Compiler is - - case Style is - when "deb" => - for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE"); - - when "rel" => - for Default_Switches ("Ada") use ("-O2"); - end case; - - end Compiler; - - end Build; - @end group - @end smallexample - - @noindent - @code{Style_Type} is an example of a @emph{string type}, which is the project - file analog of an Ada enumeration type but containing string literals rather - than identifiers. @code{Style} is declared as a variable of this type. - - The form @code{external("STYLE", "deb")} is known as an - @emph{external reference}; its first argument is the name of an - @emph{external variable}, and the second argument is a default value to be - used if the external variable doesn't exist. You can define an external - variable on the command line via the @option{-X} switch, or you can use an - environment variable as an external variable. - - Each @code{case} construct is expanded by the Project Manager based on the - value of @code{Style}. Thus the command - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=deb - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{debug.gpr} in the earlier example. So is the command - @smallexample - gnatmake -P/common/build.gpr - @end smallexample - - @noindent - since @code{"deb"} is the default for @code{STYLE}. - - Analogously, - @smallexample - gnatmake -P/common/build.gpr -XSTYLE=rel - @end smallexample - - @noindent - is equivalent to the @command{gnatmake} invocation using the project file - @file{release.gpr} in the earlier example. - - - @node Importing Other Projects - @subsection Importing Other Projects - - @noindent - A compilation unit in a source file in one project may depend on compilation - units in source files in other projects. To obtain this behavior, the - dependent project must @emph{import} the projects containing the needed source - files. This effect is embodied in syntax similar to an Ada @code{with} clause, - but the "with"ed entities are strings denoting project files. - - As an example, suppose that the two projects @code{GUI_Proj} and - @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and - @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm}, - respectively. Assume that the source files for @code{GUI_Proj} are - @file{gui.ads} and @file{gui.adb}, and that the source files for - @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of - files located in its respective project file directory. Diagrammatically: - - @smallexample - @group - /gui - gui_proj.gpr - gui.ads - gui.adb - @end group - - @group - /comm - comm_proj.gpr - comm.ads - comm.adb - @end group - @end smallexample - - @noindent - We want to develop an application in directory @file{/app} that "with"s the - packages @code{GUI} and @code{Comm}, using the properties of the - corresponding project files (e.g. the switch settings and object directory). - Skeletal code for a main procedure might be something like the following: - - @smallexample - @group - with GUI, Comm; - procedure App_Main is - ... - begin - ... - end App_Main; - @end group - @end smallexample - - @noindent - Here is a project file, @file{app_proj.gpr}, that achieves the desired - effect: - - @smallexample - @group - with "/gui/gui_proj", "/comm/comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Building an executable is achieved through the command: - @smallexample - gnatmake -P/app/app_proj - @end smallexample - @noindent - which will generate the @code{app_main} executable in the directory where - @file{app_proj.gpr} resides. - - If an imported project file uses the standard extension (@code{gpr}) then - (as illustrated above) the @code{with} clause can omit the extension. - - Our example specified an absolute path for each imported project file. - Alternatively, you can omit the directory if either - @itemize @bullet - @item - The imported project file is in the same directory as the importing project - file, or - @item - You have defined an environment variable @code{ADA_PROJECT_PATH} that - includes the directory containing the needed project file. - @end itemize - - @noindent - Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and - @file{/comm}, then our project file @file{app_proj.gpr} could be written as - follows: - - @smallexample - @group - with "gui_proj", "comm_proj"; - project App_Proj is - for Main use ("app_main"); - end App_Proj; - @end group - @end smallexample - - @noindent - Importing other projects raises the possibility of ambiguities. For - example, the same unit might be present in different imported projects, or - it might be present in both the importing project and an imported project. - Both of these conditions are errors. Note that in the current version of - the Project Manager, it is illegal to have an ambiguous unit even if the - unit is never referenced by the importing project. This restriction may be - relaxed in a future release. - - @node Extending a Project - @subsection Extending a Project - - @noindent - A common situation in large software systems is to have multiple - implementations for a common interface; in Ada terms, multiple versions of a - package body for the same specification. For example, one implementation - might be safe for use in tasking programs, while another might only be used - in sequential applications. This can be modeled in GNAT using the concept - of @emph{project extension}. If one project (the "child") @emph{extends} - another project (the "parent") then by default all source files of the - parent project are inherited by the child, but the child project can - override any of the parent's source files with new versions, and can also - add new files. This facility is the project analog of extension in - Object-Oriented Programming. Project hierarchies are permitted (a child - project may be the parent of yet another project), and a project that - inherits one project can also import other projects. - - As an example, suppose that directory @file{/seq} contains the project file - @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb}, - and @file{proc.adb}: - - @smallexample - @group - /seq - pack.ads - pack.adb - proc.adb - seq_proj.gpr - @end group - @end smallexample - - @noindent - Note that the project file can simply be empty (that is, no attribute or - package is defined): - - @smallexample - @group - project Seq_Proj is - end Seq_Proj; - @end group - @end smallexample - - @noindent - implying that its source files are all the Ada source files in the project - directory. - - Suppose we want to supply an alternate version of @file{pack.adb}, in - directory @file{/tasking}, but use the existing versions of @file{pack.ads} - and @file{proc.adb}. We can define a project @code{Tasking_Proj} that - inherits @code{Seq_Proj}: - - @smallexample - @group - /tasking - pack.adb - tasking_proj.gpr - @end group - - @group - project Tasking_Proj extends "/seq/seq_proj" is - end Tasking_Proj; - @end group - @end smallexample - - @noindent - The version of @file{pack.adb} used in a build depends on which project file - is specified. - - Note that we could have designed this using project import rather than - project inheritance; a @code{base} project would contain the sources for - @file{pack.ads} and @file{proc.adb}, a sequential project would import - @code{base} and add @file{pack.adb}, and likewise a tasking project would - import @code{base} and add a different version of @file{pack.adb}. The - choice depends on whether other sources in the original project need to be - overridden. If they do, then project extension is necessary, otherwise, - importing is sufficient. - - - @c *********************** - @c * Project File Syntax * - @c *********************** - - @node Project File Syntax - @section Project File Syntax - - @menu - * Basic Syntax:: - * Packages:: - * Expressions:: - * String Types:: - * Variables:: - * Attributes:: - * Associative Array Attributes:: - * case Constructions:: - @end menu - - @noindent - This section describes the structure of project files. - - A project may be an @emph{independent project}, entirely defined by a single - project file. Any Ada source file in an independent project depends only - on the predefined library and other Ada source files in the same project. - - @noindent - A project may also @dfn{depend on} other projects, in either or both of the following ways: - @itemize @bullet - @item It may import any number of projects - @item It may extend at most one other project - @end itemize - - @noindent - The dependence relation is a directed acyclic graph (the subgraph reflecting - the "extends" relation is a tree). - - A project's @dfn{immediate sources} are the source files directly defined by - that project, either implicitly by residing in the project file's directory, - or explicitly through any of the source-related attributes described below. - More generally, a project @var{proj}'s @dfn{sources} are the immediate sources - of @var{proj} together with the immediate sources (unless overridden) of any - project on which @var{proj} depends (either directly or indirectly). - - @node Basic Syntax - @subsection Basic Syntax - - @noindent - As seen in the earlier examples, project files have an Ada-like syntax. - The minimal project file is: - @smallexample - @group - project Empty is - - end Empty; - @end group - @end smallexample - - @noindent - The identifier @code{Empty} is the name of the project. - This project name must be present after the reserved - word @code{end} at the end of the project file, followed by a semi-colon. - - Any name in a project file, such as the project name or a variable name, - has the same syntax as an Ada identifier. - - The reserved words of project files are the Ada reserved words plus - @code{extends}, @code{external}, and @code{project}. Note that the only Ada - reserved words currently used in project file syntax are: - - @itemize @bullet - @item - @code{case} - @item - @code{end} - @item - @code{for} - @item - @code{is} - @item - @code{others} - @item - @code{package} - @item - @code{renames} - @item - @code{type} - @item - @code{use} - @item - @code{when} - @item - @code{with} - @end itemize - - @noindent - Comments in project files have the same syntax as in Ada, two consecutives - hyphens through the end of the line. - - @node Packages - @subsection Packages - - @noindent - A project file may contain @emph{packages}. The name of a package must be one - of the identifiers (case insensitive) from a predefined list, and a package - with a given name may only appear once in a project file. The predefined list - includes the following packages: - - @itemize @bullet - @item - @code{Naming} - @item - @code{Builder} - @item - @code{Compiler} - @item - @code{Binder} - @item - @code{Linker} - @item - @code{Finder} - @item - @code{Cross_Reference} - @item - @code{gnatls} - @end itemize - - @noindent - (The complete list of the package names and their attributes can be found - in file @file{prj-attr.adb}). - - @noindent - In its simplest form, a package may be empty: - - @smallexample - @group - project Simple is - package Builder is - end Builder; - end Simple; - @end group - @end smallexample - - @noindent - A package may contain @emph{attribute declarations}, - @emph{variable declarations} and @emph{case constructions}, as will be - described below. - - When there is ambiguity between a project name and a package name, - the name always designates the project. To avoid possible confusion, it is - always a good idea to avoid naming a project with one of the - names allowed for packages or any name that starts with @code{gnat}. - - - @node Expressions - @subsection Expressions - - @noindent - An @emph{expression} is either a @emph{string expression} or a - @emph{string list expression}. - - A @emph{string expression} is either a @emph{simple string expression} or a - @emph{compound string expression}. - - A @emph{simple string expression} is one of the following: - @itemize @bullet - @item A literal string; e.g.@code{"comm/my_proj.gpr"} - @item A string-valued variable reference (see @ref{Variables}) - @item A string-valued attribute reference (see @ref{Attributes}) - @item An external reference (see @ref{External References in Project Files}) - @end itemize - - @noindent - A @emph{compound string expression} is a concatenation of string expressions, - using @code{"&"} - @smallexample - Path & "/" & File_Name & ".ads" - @end smallexample - - @noindent - A @emph{string list expression} is either a - @emph{simple string list expression} or a - @emph{compound string list expression}. - - A @emph{simple string list expression} is one of the following: - @itemize @bullet - @item A parenthesized list of zero or more string expressions, separated by commas - @smallexample - File_Names := (File_Name, "gnat.adc", File_Name & ".orig"); - Empty_List := (); - @end smallexample - @item A string list-valued variable reference - @item A string list-valued attribute reference - @end itemize - - @noindent - A @emph{compound string list expression} is the concatenation (using - @code{"&"}) of a simple string list expression and an expression. Note that - each term in a compound string list expression, except the first, may be - either a string expression or a string list expression. - - @smallexample - @group - File_Name_List := () & File_Name; -- One string in this list - Extended_File_Name_List := File_Name_List & (File_Name & ".orig"); - -- Two strings - Big_List := File_Name_List & Extended_File_Name_List; - -- Concatenation of two string lists: three strings - Illegal_List := "gnat.adc" & Extended_File_Name_List; - -- Illegal: must start with a string list - @end group - @end smallexample - - - @node String Types - @subsection String Types - - @noindent - The value of a variable may be restricted to a list of string literals. - The restricted list of string literals is given in a - @emph{string type declaration}. - - Here is an example of a string type declaration: - - @smallexample - type OS is ("NT, "nt", "Unix", "Linux", "other OS"); - @end smallexample - - @noindent - Variables of a string type are called @emph{typed variables}; all other - variables are called @emph{untyped variables}. Typed variables are - particularly useful in @code{case} constructions - (see @ref{case Constructions}). - - A string type declaration starts with the reserved word @code{type}, followed - by the name of the string type (case-insensitive), followed by the reserved - word @code{is}, followed by a parenthesized list of one or more string literals - separated by commas, followed by a semicolon. - - The string literals in the list are case sensitive and must all be different. - They may include any graphic characters allowed in Ada, including spaces. - - A string type may only be declared at the project level, not inside a package. - - A string type may be referenced by its name if it has been declared in the same - project file, or by its project name, followed by a dot, - followed by the string type name. - - - @node Variables - @subsection Variables - - @noindent - A variable may be declared at the project file level, or in a package. - Here are some examples of variable declarations: - - @smallexample - @group - This_OS : OS := external ("OS"); -- a typed variable declaration - That_OS := "Linux"; -- an untyped variable declaration - @end group - @end smallexample - - @noindent - A @emph{typed variable declaration} includes the variable name, followed by a colon, - followed by the name of a string type, followed by @code{:=}, followed by - a simple string expression. - - An @emph{untyped variable declaration} includes the variable name, - followed by @code{:=}, followed by an expression. Note that, despite the - terminology, this form of "declaration" resembles more an assignment - than a declaration in Ada. It is a declaration in several senses: - @itemize @bullet - @item - The variable name does not need to be defined previously - @item - The declaration establishes the @emph{kind} (string versus string list) of the - variable, and later declarations of the same variable need to be consistent - with this - @end itemize - - @noindent - A string variable declaration (typed or untyped) declares a variable - whose value is a string. This variable may be used as a string expression. - @smallexample - File_Name := "readme.txt"; - Saved_File_Name := File_Name & ".saved"; - @end smallexample - - @noindent - A string list variable declaration declares a variable whose value is a list - of strings. The list may contain any number (zero or more) of strings. - - @smallexample - Empty_List := (); - List_With_One_Element := ("-gnaty"); - List_With_Two_Elements := List_With_One_Element & "-gnatg"; - Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada" - "pack2.ada", "util_.ada", "util.ada"); - @end smallexample - - @noindent - The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable. - - The same untyped variable may be declared several times. - In this case, the new value replaces the old one, - and any subsequent reference to the variable uses the new value. - However, as noted above, if a variable has been declared as a string, all subsequent - declarations must give it a string value. Similarly, if a variable has - been declared as a string list, all subsequent declarations - must give it a string list value. - - A @emph{variable reference} may take several forms: - - @itemize @bullet - @item The simple variable name, for a variable in the current package (if any) or in the current project - @item A context name, followed by a dot, followed by the variable name. - @end itemize - - @noindent - A @emph{context} may be one of the following: - - @itemize @bullet - @item The name of an existing package in the current project - @item The name of an imported project of the current project - @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly) - @item An imported/parent project name, followed by a dot, followed by a package name - @end itemize - - @noindent - A variable reference may be used in an expression. - - - @node Attributes - @subsection Attributes - - @noindent - A project (and its packages) may have @emph{attributes} that define the project's properties. - Some attributes have values that are strings; - others have values that are string lists. - - There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays} - (see @ref{Associative Array Attributes}). - - The names of the attributes are restricted; there is a list of project - attributes, and a list of package attributes for each package. - The names are not case sensitive. - - The project attributes are as follows (all are simple attributes): - - @multitable @columnfractions .4 .3 - @item @emph{Attribute Name} - @tab @emph{Value} - @item @code{Source_Files} - @tab string list - @item @code{Source_Dirs} - @tab string list - @item @code{Source_List_File} - @tab string - @item @code{Object_Dir} - @tab string - @item @code{Exec_Dir} - @tab string - @item @code{Main} - @tab string list - @item @code{Languages} - @tab string list - @item @code{Library_Dir} - @tab string - @item @code{Library_Name} - @tab string - @item @code{Library_Kind} - @tab string - @item @code{Library_Elaboration} - @tab string - @item @code{Library_Version} - @tab string - @end multitable - - @noindent - The attributes for package @code{Naming} are as follows - (see @ref{Naming Schemes}): - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Specification_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Implementation_Suffix} - @tab associative array - @tab language name - @tab string - @item @code{Separate_Suffix} - @tab simple attribute - @tab n/a - @tab string - @item @code{Casing} - @tab simple attribute - @tab n/a - @tab string - @item @code{Dot_Replacement} - @tab simple attribute - @tab n/a - @tab string - @item @code{Specification} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Implementation} - @tab associative array - @tab Ada unit name - @tab string - @item @code{Specification_Exceptions} - @tab associative array - @tab language name - @tab string list - @item @code{Implementation_Exceptions} - @tab associative array - @tab language name - @tab string list - @end multitable - - @noindent - The attributes for package @code{Builder}, @code{Compiler}, @code{Binder}, - @code{Linker}, @code{Cross_Reference}, and @code{Finder} - are as follows (see @ref{Switches and Project Files}). - - @multitable @columnfractions .4 .2 .2 .2 - @item Attribute Name @tab Category @tab Index @tab Value - @item @code{Default_Switches} - @tab associative array - @tab language name - @tab string list - @item @code{Switches} - @tab associative array - @tab file name - @tab string list - @end multitable - - @noindent - In addition, package @code{Builder} has a single string attribute - @code{Local_Configuration_Pragmas} and package @code{Builder} has a single - string attribute @code{Global_Configuration_Pragmas}. - - @noindent - The attribute for package @code{Glide} are not documented: they are for - internal use only. - - @noindent - Each simple attribute has a default value: the empty string (for string-valued - attributes) and the empty list (for string list-valued attributes). - - Similar to variable declarations, an attribute declaration defines a new value - for an attribute. - - Examples of simple attribute declarations: - - @smallexample - for Object_Dir use "objects"; - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - @noindent - A @dfn{simple attribute declaration} starts with the reserved word @code{for}, - followed by the name of the attribute, followed by the reserved word - @code{use}, followed by an expression (whose kind depends on the attribute), - followed by a semicolon. - - Attributes may be referenced in expressions. - The general form for such a reference is @code{'}: - the entity for which the attribute is defined, - followed by an apostrophe, followed by the name of the attribute. - For associative array attributes, a litteral string between parentheses - need to be supplied as index. - - Examples are: - - @smallexample - project'Object_Dir - Naming'Dot_Replacement - Imported_Project'Source_Dirs - Imported_Project.Naming'Casing - Builder'Default_Switches("Ada") - @end smallexample - - @noindent - The entity may be: - @itemize @bullet - @item @code{project} for an attribute of the current project - @item The name of an existing package of the current project - @item The name of an imported project - @item The name of a parent project (extended by the current project) - @item An imported/parent project name, followed by a dot, - followed by a package name - @end itemize - - @noindent - Example: - @smallexample - @group - project Prj is - for Source_Dirs use project'Source_Dirs & "units"; - for Source_Dirs use project'Source_Dirs & "test/drivers" - end Prj; - @end group - @end smallexample - - @noindent - In the first attribute declaration, initially the attribute @code{Source_Dirs} - has the default value: an empty string list. After this declaration, - @code{Source_Dirs} is a string list of one element: "units". - After the second attribute declaration @code{Source_Dirs} is a string list of - two elements: "units" and "test/drivers". - - Note: this example is for illustration only. In practice, - the project file would contain only one attribute declaration: - - @smallexample - for Source_Dirs use ("units", "test/drivers"); - @end smallexample - - - @node Associative Array Attributes - @subsection Associative Array Attributes - - @noindent - Some attributes are defined as @emph{associative arrays}. An associative - array may be regarded as a function that takes a string as a parameter - and delivers a string or string list value as its result. - - Here are some examples of associative array attribute declarations: - - @smallexample - for Implementation ("main") use "Main.ada"; - for Switches ("main.ada") use ("-v", "-gnatv"); - for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g"; - @end smallexample - - @noindent - Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the - attribute, replacing the previous setting. - - - @node case Constructions - @subsection @code{case} Constructions - - @noindent - A @code{case} construction is used in a project file to effect conditional - behavior. - Here is a typical example: - - @smallexample - @group - project MyProj is - type OS_Type is ("Linux", "Unix", "NT", "VMS"); - - OS : OS_Type := external ("OS", "Linux"); - @end group - - @group - package Compiler is - case OS is - when "Linux" | "Unix" => - for Default_Switches ("Ada") use ("-gnath"); - when "NT" => - for Default_Switches ("Ada") use ("-gnatP"); - when others => - end case; - end Compiler; - end MyProj; - @end group - @end smallexample - - @noindent - The syntax of a @code{case} construction is based on the Ada case statement - (although there is no @code{null} construction for empty alternatives). - - Following the reserved word @code{case} there is the case variable (a typed - string variable), the reserved word @code{is}, and then a sequence of one or - more alternatives. - Each alternative comprises the reserved word @code{when}, either a list of - literal strings separated by the @code{"|"} character or the reserved word - @code{others}, and the @code{"=>"} token. - Each literal string must belong to the string type that is the type of the - case variable. - An @code{others} alternative, if present, must occur last. - The @code{end case;} sequence terminates the case construction. - - After each @code{=>}, there are zero or more constructions. The only - constructions allowed in a case construction are other case constructions and - attribute declarations. String type declarations, variable declarations and - package declarations are not allowed. - - The value of the case variable is often given by an external reference - (see @ref{External References in Project Files}). - - - @c **************************************** - @c * Objects and Sources in Project Files * - @c **************************************** - - @node Objects and Sources in Project Files - @section Objects and Sources in Project Files - - @menu - * Object Directory:: - * Exec Directory:: - * Source Directories:: - * Source File Names:: - @end menu - - @noindent - Each project has exactly one object directory and one or more source - directories. The source directories must contain at least one source file, - unless the project file explicitly specifies that no source files are present - (see @ref{Source File Names}). - - - @node Object Directory - @subsection Object Directory - - @noindent - The object directory for a project is the directory containing the compiler's - output (such as @file{ALI} files and object files) for the project's immediate - sources. Note that for inherited sources (when extending a parent project) the - parent project's object directory is used. - - The object directory is given by the value of the attribute @code{Object_Dir} - in the project file. - - @smallexample - for Object_Dir use "objects"; - @end smallexample - - @noindent - The attribute @var{Object_Dir} has a string value, the path name of the object - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be readable and writable. - - By default, when the attribute @code{Object_Dir} is not given an explicit value - or when its value is the empty string, the object directory is the same as the - directory containing the project file. - - - @node Exec Directory - @subsection Exec Directory - - @noindent - The exec directory for a project is the directory containing the executables - for the project's main subprograms. - - The exec directory is given by the value of the attribute @code{Exec_Dir} - in the project file. - - @smallexample - for Exec_Dir use "executables"; - @end smallexample - - @noindent - The attribute @var{Exec_Dir} has a string value, the path name of the exec - directory. The path name may be absolute or relative to the directory of the - project file. This directory must already exist, and be writable. - - By default, when the attribute @code{Exec_Dir} is not given an explicit value - or when its value is the empty string, the exec directory is the same as the - object directory of the project file. - - - @node Source Directories - @subsection Source Directories - - @noindent - The source directories of a project are specified by the project file - attribute @code{Source_Dirs}. - - This attribute's value is a string list. If the attribute is not given an - explicit value, then there is only one source directory, the one where the - project file resides. - - A @code{Source_Dirs} attribute that is explicitly defined to be the empty list, - as in - - @smallexample - for Source_Dirs use (); - @end smallexample - - @noindent - indicates that the project contains no source files. - - Otherwise, each string in the string list designates one or more - source directories. - - @smallexample - for Source_Dirs use ("sources", "test/drivers"); - @end smallexample - - @noindent - If a string in the list ends with @code{"/**"}, then the directory whose path - name precedes the two asterisks, as well as all its subdirectories - (recursively), are source directories. - - @smallexample - for Source_Dirs use ("/system/sources/**"); - @end smallexample - - @noindent - Here the directory @code{/system/sources} and all of its subdirectories - (recursively) are source directories. - - To specify that the source directories are the directory of the project file - and all of its subdirectories, you can declare @code{Source_Dirs} as follows: - @smallexample - for Source_Dirs use ("./**"); - @end smallexample - - @noindent - Each of the source directories must exist and be readable. - - - @node Source File Names - @subsection Source File Names - - @noindent - In a project that contains source files, their names may be specified by the - attributes @code{Source_Files} (a string list) or @code{Source_List_File} - (a string). Source file names never include any directory information. - - If the attribute @code{Source_Files} is given an explicit value, then each - element of the list is a source file name. - - @smallexample - for Source_Files use ("main.adb"); - for Source_Files use ("main.adb", "pack1.ads", "pack2.adb"); - @end smallexample - - @noindent - If the attribute @code{Source_Files} is not given an explicit value, - but the attribute @code{Source_List_File} is given a string value, - then the source file names are contained in the text file whose path name - (absolute or relative to the directory of the project file) is the - value of the attribute @code{Source_List_File}. - - Each line in the file that is not empty or is not a comment - contains a source file name. A comment line starts with two hyphens. - - @smallexample - for Source_List_File use "source_list.txt"; - @end smallexample - - @noindent - By default, if neither the attribute @code{Source_Files} nor the attribute - @code{Source_List_File} is given an explicit value, then each file in the - source directories that conforms to the project's naming scheme - (see @ref{Naming Schemes}) is an immediate source of the project. - - A warning is issued if both attributes @code{Source_Files} and - @code{Source_List_File} are given explicit values. In this case, the attribute - @code{Source_Files} prevails. - - Each source file name must be the name of one and only one existing source file - in one of the source directories. - - A @code{Source_Files} attribute defined with an empty list as its value - indicates that there are no source files in the project. - - Except for projects that are clearly specified as containing no Ada source - files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list, - or @code{Languages} specified without @code{"Ada"} in the list) - @smallexample - for Source_Dirs use (); - for Source_Files use (); - for Languages use ("C", "C++"); - @end smallexample - - @noindent - a project must contain at least one immediate source. - - Projects with no source files are useful as template packages - (see @ref{Packages in Project Files}) for other projects; in particular to - define a package @code{Naming} (see @ref{Naming Schemes}). - - - @c **************************** - @c * Importing Projects * - @c **************************** - - @node Importing Projects - @section Importing Projects - - @noindent - An immediate source of a project P may depend on source files that - are neither immediate sources of P nor in the predefined library. - To get this effect, P must @emph{import} the projects that contain the needed - source files. - - @smallexample - @group - with "project1", "utilities.gpr"; - with "/namings/apex.gpr"; - project Main is - ... - @end group - @end smallexample - - @noindent - As can be seen in this example, the syntax for importing projects is similar - to the syntax for importing compilation units in Ada. However, project files - use literal strings instead of names, and the @code{with} clause identifies - project files rather than packages. - - Each literal string is the file name or path name (absolute or relative) of a - project file. If a string is simply a file name, with no path, then its - location is determined by the @emph{project path}: - - @itemize @bullet - @item - If the environment variable @env{ADA_PROJECT_PATH} exists, then the project - path includes all the directories in this environment variable, plus the - directory of the project file. - - @item - If the environment variable @env{ADA_PROJECT_PATH} does not exist, - then the project path contains only one directory, namely the one where - the project file is located. - @end itemize - - @noindent - If a relative pathname is used as in - - @smallexample - with "tests/proj"; - @end smallexample - - @noindent - then the path is relative to the directory where the importing project file is - located. Any symbolic link will be fully resolved in the directory - of the importing project file before the imported project file is looked up. - - When the @code{with}'ed project file name does not have an extension, - the default is @file{.gpr}. If a file with this extension is not found, then - the file name as specified in the @code{with} clause (no extension) will be - used. In the above example, if a file @code{project1.gpr} is found, then it - will be used; otherwise, if a file @code{project1} exists then it will be used; - if neither file exists, this is an error. - - A warning is issued if the name of the project file does not match the - name of the project; this check is case insensitive. - - Any source file that is an immediate source of the imported project can be - used by the immediate sources of the importing project, and recursively. Thus - if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate - sources of @code{A} may depend on the immediate sources of @code{C}, even if - @code{A} does not import @code{C} explicitly. However, this is not recommended, - because if and when @code{B} ceases to import @code{C}, some sources in - @code{A} will no longer compile. - - A side effect of this capability is that cyclic dependences are not permitted: - if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not - allowed to import @code{A}. - - - @c ********************* - @c * Project Extension * - @c ********************* - - @node Project Extension - @section Project Extension - - @noindent - During development of a large system, it is sometimes necessary to use - modified versions of some of the source files without changing the original - sources. This can be achieved through a facility known as - @emph{project extension}. - - @smallexample - project Modified_Utilities extends "/baseline/utilities.gpr" is ... - @end smallexample - - @noindent - The project file for the project being extended (the @emph{parent}) is - identified by the literal string that follows the reserved word @code{extends}, - which itself follows the name of the extending project (the @emph{child}). - - By default, a child project inherits all the sources of its parent. - However, inherited sources can be overridden: a unit with the same name as one - in the parent will hide the original unit. - Inherited sources are considered to be sources (but not immediate sources) - of the child project; see @ref{Project File Syntax}. - - An inherited source file retains any switches specified in the parent project. - - For example if the project @code{Utilities} contains the specification and the - body of an Ada package @code{Util_IO}, then the project - @code{Modified_Utilities} can contain a new body for package @code{Util_IO}. - The original body of @code{Util_IO} will not be considered in program builds. - However, the package specification will still be found in the project - @code{Utilities}. - - A child project can have only one parent but it may import any number of other - projects. - - A project is not allowed to import directly or indirectly at the same time a - child project and any of its ancestors. - - - @c **************************************** - @c * External References in Project Files * - @c **************************************** - - @node External References in Project Files - @section External References in Project Files - - @noindent - A project file may contain references to external variables; such references - are called @emph{external references}. - - An external variable is either defined as part of the environment (an - environment variable in Unix, for example) or else specified on the command - line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the - command line value is used. - - An external reference is denoted by the built-in function - @code{external}, which returns a string value. This function has two forms: - @itemize @bullet - @item @code{external (external_variable_name)} - @item @code{external (external_variable_name, default_value)} - @end itemize - - @noindent - Each parameter must be a string literal. For example: - - @smallexample - external ("USER") - external ("OS", "Linux") - @end smallexample - - @noindent - In the form with one parameter, the function returns the value of - the external variable given as parameter. If this name is not present in the - environment, then the returned value is an empty string. - - In the form with two string parameters, the second parameter is - the value returned when the variable given as the first parameter is not - present in the environment. In the example above, if @code{"OS"} is not - the name of an environment variable and is not passed on the command line, - then the returned value will be @code{"Linux"}. - - An external reference may be part of a string expression or of a string - list expression, to define variables or attributes. - - @smallexample - @group - type Mode_Type is ("Debug", "Release"); - Mode : Mode_Type := external ("MODE"); - case Mode is - when "Debug" => - ... - @end group - @end smallexample - - - @c ***************************** - @c * Packages in Project Files * - @c ***************************** - - @node Packages in Project Files - @section Packages in Project Files - - @noindent - The @emph{package} is the project file feature that defines the settings for - project-aware tools. - For each such tool you can declare a corresponding package; the names for these - packages are preset (see @ref{Packages}) but are not case sensitive. - A package may contain variable declarations, attribute declarations, and case - constructions. - - @smallexample - @group - project Proj is - package Builder is -- used by gnatmake - for Default_Switches ("Ada") use ("-v", "-g"); - end Builder; - end Proj; - @end group - @end smallexample - - @noindent - A package declaration starts with the reserved word @code{package}, - followed by the package name (case insensitive), followed by the reserved word - @code{is}. It ends with the reserved word @code{end}, followed by the package - name, finally followed by a semi-colon. - - Most of the packages have an attribute @code{Default_Switches}. - This attribute is an associative array, and its value is a string list. - The index of the associative array is the name of a programming language (case - insensitive). This attribute indicates the switch or switches to be used - with the corresponding tool. - - Some packages also have another attribute, @code{Switches}, an associative - array whose value is a string list. The index is the name of a source file. - This attribute indicates the switch or switches to be used by the corresponding - tool when dealing with this specific file. - - Further information on these switch-related attributes is found in - @ref{Switches and Project Files}. - - A package may be declared as a @emph{renaming} of another package; e.g., from - the project file for an imported project. - - @smallexample - @group - with "/global/apex.gpr"; - project Example is - package Naming renames Apex.Naming; - ... - end Example; - @end group - @end smallexample - - @noindent - Packages that are renamed in other project files often come from project files - that have no sources: they are just used as templates. Any modification in the - template will be reflected automatically in all the project files that rename - a package from the template. - - In addition to the tool-oriented packages, you can also declare a package - named @code{Naming} to establish specialized source file naming conventions - (see @ref{Naming Schemes}). - - - @c ************************************ - @c * Variables from Imported Projects * - @c ************************************ - - @node Variables from Imported Projects - @section Variables from Imported Projects - - @noindent - An attribute or variable defined in an imported or parent project can - be used in expressions in the importing / extending project. - Such an attribute or variable is prefixed with the name of the project - and (if relevant) the name of package where it is defined. - - @smallexample - @group - with "imported"; - project Main extends "base" is - Var1 := Imported.Var; - Var2 := Base.Var & ".new"; - @end group - - @group - package Builder is - for Default_Switches ("Ada") use Imported.Builder.Ada_Switches & - "-gnatg" & "-v"; - end Builder; - @end group - - @group - package Compiler is - for Default_Switches ("Ada") use Base.Compiler.Ada_Switches; - end Compiler; - end Main; - @end group - @end smallexample - - @noindent - In this example: - - @itemize @bullet - @item - @code{Var1} is a copy of the variable @code{Var} defined in the project file - @file{"imported.gpr"} - @item - the value of @code{Var2} is a copy of the value of variable @code{Var} - defined in the project file @file{base.gpr}, concatenated with @code{".new"} - @item - attribute @code{Default_Switches ("Ada")} in package @code{Builder} - is a string list that includes in its value a copy of variable - @code{Ada_Switches} defined in the @code{Builder} package in project file - @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"}; - @item - attribute @code{Default_Switches ("Ada")} in package @code{Compiler} - is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler} - package in project file @file{base.gpr}, the project being extended. - @end itemize - - - @c ****************** - @c * Naming Schemes * - @c ****************** - - @node Naming Schemes - @section Naming Schemes - - @noindent - Sometimes an Ada software system is ported from a foreign compilation - environment to GNAT, with file names that do not use the default GNAT - conventions. Instead of changing all the file names (which for a variety of - reasons might not be possible), you can define the relevant file naming scheme - in the @code{Naming} package in your project file. For example, the following - package models the Apex file naming rules: - - @smallexample - @group - package Naming is - for Casing use "lowercase"; - for Dot_Replacement use "."; - for Specification_Suffix ("Ada") use ".1.ada"; - for Implementation_Suffix ("Ada") use ".2.ada"; - end Naming; - @end group - @end smallexample - - @noindent - You can define the following attributes in package @code{Naming}: - - @table @code - - @item @var{Casing} - This must be a string with one of the three values @code{"lowercase"}, - @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive. - - @noindent - If @var{Casing} is not specified, then the default is @code{"lowercase"}. - - @item @var{Dot_Replacement} - This must be a string whose value satisfies the following conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start or end with an alphanumeric character - @item It cannot be a single underscore - @item It cannot start with an underscore followed by an alphanumeric - @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."} - @end itemize - - @noindent - If @code{Dot_Replacement} is not specified, then the default is @code{"-"}. - - @item @var{Specification_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @end itemize - @noindent - If @code{Specification_Suffix ("Ada")} is not specified, then the default is - @code{".ads"}. - - @item @var{Implementation_Suffix} - This is an associative array (indexed by the programming language name, case - insensitive) whose value is a string that must satisfy the following - conditions: - - @itemize @bullet - @item It must not be empty - @item It cannot start with an alphanumeric character - @item It cannot start with an underscore followed by an alphanumeric character - @item It cannot be a suffix of @code{Specification_Suffix} - @end itemize - @noindent - If @code{Implementation_Suffix ("Ada")} is not specified, then the default is - @code{".adb"}. - - @item @var{Separate_Suffix} - This must be a string whose value satisfies the same conditions as - @code{Implementation_Suffix}. - - @noindent - If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same - value as @code{Implementation_Suffix ("Ada")}. - - @item @var{Specification} - @noindent - You can use the @code{Specification} attribute, an associative array, to define - the source file name for an individual Ada compilation unit's spec. The array - index must be a string literal that identifies the Ada unit (case insensitive). - The value of this attribute must be a string that identifies the file that - contains this unit's spec (case sensitive or insensitive depending on the - operating system). - - @smallexample - for Specification ("MyPack.MyChild") use "mypack.mychild.spec"; - @end smallexample - - @item @var{Implementation} - - You can use the @code{Implementation} attribute, an associative array, to - define the source file name for an individual Ada compilation unit's body - (possibly a subunit). The array index must be a string literal that identifies - the Ada unit (case insensitive). The value of this attribute must be a string - that identifies the file that contains this unit's body or subunit (case - sensitive or insensitive depending on the operating system). - - @smallexample - for Implementation ("MyPack.MyChild") use "mypack.mychild.body"; - @end smallexample - @end table - - - @c ******************** - @c * Library Projects * - @c ******************** - - @node Library Projects - @section Library Projects - - @noindent - @emph{Library projects} are projects whose object code is placed in a library. - (Note that this facility is not yet supported on all platforms) - - To create a library project, you need to define in its project file - two project-level attributes: @code{Library_Name} and @code{Library_Dir}. - Additionally, you may define the library-related attributes - @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}. - - The @code{Library_Name} attribute has a string value that must start with a - letter and include only letters and digits. - - The @code{Library_Dir} attribute has a string value that designates the path - (absolute or relative) of the directory where the library will reside. - It must designate an existing directory, and this directory needs to be - different from the project's object directory. It also needs to be writable. - - If both @code{Library_Name} and @code{Library_Dir} are specified and - are legal, then the project file defines a library project. The optional - library-related attributes are checked only for such project files. - - The @code{Library_Kind} attribute has a string value that must be one of the - following (case insensitive): @code{"static"}, @code{"dynamic"} or - @code{"relocatable"}. If this attribute is not specified, the library is a - static library. Otherwise, the library may be dynamic or relocatable. - Depending on the operating system, there may or may not be a distinction - between dynamic and relocatable libraries. For example, on Unix there is no - such distinction. - - The @code{Library_Version} attribute has a string value whose interpretation - is platform dependent. On Unix, it is used only for dynamic/relocatable - libraries as the internal name of the library (the @code{"soname"}). If the - library file name (built from the @code{Library_Name}) is different from the - @code{Library_Version}, then the library file will be a symbolic link to the - actual file whose name will be @code{Library_Version}. - - Example (on Unix): - - @smallexample - @group - project Plib is - - Version := "1"; - - for Library_Dir use "lib_dir"; - for Library_Name use "dummy"; - for Library_Kind use "relocatable"; - for Library_Version use "libdummy.so." & Version; - - end Plib; - @end group - @end smallexample - - @noindent - Directory @file{lib_dir} will contain the internal library file whose name - will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to - @file{libdummy.so.1}. - - When @command{gnatmake} detects that a project file (not the main project file) - is a library project file, it will check all immediate sources of the project - and rebuild the library if any of the sources have been recompiled. - All @file{ALI} files will also be copied from the object directory to the - library directory. To build executables, @command{gnatmake} will use the - library rather than the individual object files. - - - @c ************************************* - @c * Switches Related to Project Files * - @c ************************************* - @node Switches Related to Project Files - @section Switches Related to Project Files - - @noindent - The following switches are used by GNAT tools that support project files: - - @table @code - - @item @option{-P@var{project}} - Indicates the name of a project file. This project file will be parsed with - the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external - references indicated by @option{-X} switches, if any. - - @noindent - There must be only one @option{-P} switch on the command line. - - @noindent - Since the Project Manager parses the project file only after all the switches - on the command line are checked, the order of the switches @option{-P}, - @option{-Vp@emph{x}} or @option{-X} is not significant. - - @item @option{-X@var{name=value}} - Indicates that external variable @var{name} has the value @var{value}. - The Project Manager will use this value for occurrences of - @code{external(name)} when parsing the project file. - - @noindent - If @var{name} or @var{value} includes a space, then @var{name=value} should be - put between quotes. - @smallexample - -XOS=NT - -X"user=John Doe" - @end smallexample - - @noindent - Several @option{-X} switches can be used simultaneously. - If several @option{-X} switches specify the same @var{name}, only the last one - is used. - - @noindent - An external variable specified with a @option{-X} switch takes precedence - over the value of the same name in the environment. - - @item @option{-vP@emph{x}} - Indicates the verbosity of the parsing of GNAT project files. - @option{-vP0} means Default (no output for syntactically correct project - files); - @option{-vP1} means Medium; - @option{-vP2} means High. - @noindent - The default is Default. - @noindent - If several @option{-vP@emph{x}} switches are present, only the last one is - used. - - @end table - - - @c ********************************** - @c * Tools Supporting Project Files * - @c ********************************** - - @node Tools Supporting Project Files - @section Tools Supporting Project Files - - @menu - * gnatmake and Project Files:: - * The GNAT Driver and Project Files:: - * Glide and Project Files:: - @end menu - - @node gnatmake and Project Files - @subsection gnatmake and Project Files - - @noindent - This section covers two topics related to @command{gnatmake} and project files: - defining switches for @command{gnatmake} and for the tools that it invokes; - and the use of the @code{Main} attribute. - - @menu - * Switches and Project Files:: - * Project Files and Main Subprograms:: - @end menu - - @node Switches and Project Files - @subsubsection Switches and Project Files - - @noindent - For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and - @code{Linker}, you can specify a @code{Default_Switches} attribute, a - @code{Switches} attribute, or both; as their names imply, these switch-related - attributes affect which switches are used for which files when - @command{gnatmake} is invoked. As will be explained below, these - package-contributed switches precede the switches passed on the - @command{gnatmake} command line. - - The @code{Default_Switches} attribute is an associative array indexed by - language name (case insensitive) and returning a string list. For example: - - @smallexample - @group - package Compiler is - for Default_Switches ("Ada") use ("-gnaty", "-v"); - end Compiler; - @end group - @end smallexample - - @noindent - The @code{Switches} attribute is also an associative array, indexed by a file - name (which may or may not be case sensitive, depending on the operating - system) and returning a string list. For example: - - @smallexample - @group - package Builder is - for Switches ("main1.adb") use ("-O2"); - for Switches ("main2.adb") use ("-g"); - end Builder; - @end group - @end smallexample - - @noindent - For the @code{Builder} package, the file names should designate source files - for main subprograms. For the @code{Binder} and @code{Linker} packages, the - file names should designate @file{ALI} or source files for main subprograms. - In each case just the file name (without explicit extension) is acceptable. - - For each tool used in a program build (@command{gnatmake}, the compiler, the - binder, and the linker), its corresponding package @dfn{contributes} a set of - switches for each file on which the tool is invoked, based on the - switch-related attributes defined in the package. In particular, the switches - that each of these packages contributes for a given file @var{f} comprise: - - @itemize @bullet - @item - the value of attribute @code{Switches (@var{f})}, if it is specified in the - package for the given file, - @item - otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in - the package. - @end itemize - - @noindent - If neither of these attributes is defined in the package, then the package does - not contribute any switches for the given file. - - When @command{gnatmake} is invoked on a file, the switches comprise two sets, - in the following order: those contributed for the file by the @code{Builder} - package; and the switches passed on the command line. - - When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file, - the switches passed to the tool comprise three sets, in the following order: - - @enumerate - @item - the applicable switches contributed for the file by the @code{Builder} package - in the project file supplied on the command line; - - @item - those contributed for the file by the package (in the relevant project file -- - see below) corresponding to the tool; and - - @item - the applicable switches passed on the command line. - @end enumerate - - @noindent - The term @emph{applicable switches} reflects the fact that @command{gnatmake} - switches may or may not be passed to individual tools, depending on the - individual switch. - - @command{gnatmake} may invoke the compiler on source files from different - projects. The Project Manager will use the appropriate project file to - determine the @code{Compiler} package for each source file being compiled. - Likewise for the @code{Binder} and @code{Linker} packages. - - As an example, consider the following package in a project file: - - @smallexample - @group - project Proj1 is - package Compiler is - for Default_Switches ("Ada") use ("-g"); - for Switches ("a.adb") use ("-O1"); - for Switches ("b.adb") use ("-O2", "-gnaty"); - end Compiler; - end Proj1; - @end group - @end smallexample - - @noindent - If @command{gnatmake} is invoked with this project file, and it needs to - compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then - @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb} - with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with - @option{-g}. - - Another example illustrates the ordering of the switches contributed by - different packages: - - @smallexample - @group - project Proj2 is - package Builder is - for Switches ("main.adb") use ("-g", "-O1", "-f"); - end Builder; - @end group - - @group - package Compiler is - for Switches ("main.adb") use ("-O2"); - end Compiler; - end Proj2; - @end group - @end smallexample - - @noindent - If you issue the command: - - @smallexample - gnatmake -PProj2 -O0 main - @end smallexample - - @noindent - then the compiler will be invoked on @file{main.adb} with the following sequence of switches - - @smallexample - -g -O1 -O2 -O0 - @end smallexample - - with the last @option{-O} switch having precedence over the earlier ones; - several other switches (such as @option{-c}) are added implicitly. - - The switches @option{-g} and @option{-O1} are contributed by package - @code{Builder}, @option{-O2} is contributed by the package @code{Compiler} - and @option{-O0} comes from the command line. - - The @option{-g} switch will also be passed in the invocation of - @command{gnatlink.} - - A final example illustrates switch contributions from packages in different - project files: - - @smallexample - @group - project Proj3 is - for Source_Files use ("pack.ads", "pack.adb"); - package Compiler is - for Default_Switches ("Ada") use ("-gnata"); - end Compiler; - end Proj3; - @end group - - @group - with "Proj3"; - project Proj4 is - for Source_Files use ("foo_main.adb", "bar_main.adb"); - package Builder is - for Switches ("foo_main.adb") use ("-s", "-g"); - end Builder; - end Proj4; - @end group - - @group - -- Ada source file: - with Pack; - procedure Foo_Main is - ... - end Foo_Main; - @end group - @end smallexample - - If the command is - @smallexample - gnatmake -PProj4 foo_main.adb -cargs -gnato - @end smallexample - - @noindent - then the switches passed to the compiler for @file{foo_main.adb} are - @option{-g} (contributed by the package @code{Proj4.Builder}) and - @option{-gnato} (passed on the command line). - When the imported package @code{Pack} is compiled, the switches used are - @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from - package @code{Proj3.Compiler}, and @option{-gnato} from the command line. - - - @node Project Files and Main Subprograms - @subsubsection Project Files and Main Subprograms - - @noindent - When using a project file, you can invoke @command{gnatmake} - with several main subprograms, by specifying their source files on the command - line. Each of these needs to be an immediate source file of the project. - - @smallexample - gnatmake -Pprj main1 main2 main3 - @end smallexample - - @noindent - When using a project file, you can also invoke @command{gnatmake} without - explicitly specifying any main, and the effect depends on whether you have - defined the @code{Main} attribute. This attribute has a string list value, - where each element in the list is the name of a source file (the file - extension is optional) containing a main subprogram. - - If the @code{Main} attribute is defined in a project file as a non-empty - string list and the switch @option{-u} is not used on the command line, then - invoking @command{gnatmake} with this project file but without any main on the - command line is equivalent to invoking @command{gnatmake} with all the file - names in the @code{Main} attribute on the command line. - - Example: - @smallexample - @group - project Prj is - for Main use ("main1", "main2", "main3"); - end Prj; - @end group - @end smallexample - - @noindent - With this project file, @code{"gnatmake -Pprj"} is equivalent to - @code{"gnatmake -Pprj main1 main2 main3"}. - - When the project attribute @code{Main} is not specified, or is specified - as an empty string list, or when the switch @option{-u} is used on the command - line, then invoking @command{gnatmake} with no main on the command line will - result in all immediate sources of the project file being checked, and - potentially recompiled. Depending on the presence of the switch @option{-u}, - sources from other project files on which the immediate sources of the main - project file depend are also checked and potentially recompiled. In other - words, the @option{-u} switch is applied to all of the immediate sources of themain project file. - - - @node The GNAT Driver and Project Files - @subsection The GNAT Driver and Project Files - - @noindent - A number of GNAT tools, other than @command{gnatmake} are project-aware: - @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls} - and @command{gnatxref}. However, none of these tools can be invoked directly - with a project file switch (@code{-P}). They need to be invoke through the - @command{gnat} driver. - - The @command{gnat} driver is a front-end that accepts a number of commands and - call the corresponding tool. It has been designed initially for VMS to convert - VMS style qualifiers to Unix style switches, but it is now available to all - the GNAT supported platforms. - - On non VMS platforms, the @command{gnat} driver accepts the following commands - (case insensitive): - - @itemize @bullet - @item - BIND to invoke @command{gnatbind} - @item - CHOP to invoke @command{gnatchop} - @item - COMP or COMPILE to invoke the compiler - @item - ELIM to invoke @command{gnatelim} - @item - FIND to invoke @command{gnatfind} - @item - KR or KRUNCH to invoke @command{gnatkr} - @item - LINK to invoke @command{gnatlink} - @item - LS or LIST to invoke @command{gnatls} - @item - MAKE to invoke @command{gnatmake} - @item - NAME to invoke @command{gnatname} - @item - PREP or PREPROCESS to invoke @command{gnatprep} - @item - PSTA or STANDARD to invoke @command{gnatpsta} - @item - STUB to invoke @command{gnatstub} - @item - XREF to invoke @command{gnatxref} - @end itemize - - @noindent - Note that the compiler is invoked using the command @command{gnatmake -f -u}. - - @noindent - Following the command, you may put switches and arguments for the invoked - tool. - - @smallexample - gnat bind -C main.ali - gnat ls -a main - gnat chop foo.txt - @end smallexample - - @noindent - In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project - file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in - addition to the switches of the invoking tool. - - @noindent - For each of these command, there is possibly a package in the main project that - corresponds to the invoked tool. - - @itemize @bullet - @item - package @code{Binder} for command BIND (invoking @code{gnatbind}) - - @item - package @code{Finder} for command FIND (invoking @code{gnatfind}) - - @item - package @code{Gnatls} for command LS or LIST (invoking @code{gnatls}) - - @item - package @code{Linker} for command LINK (invoking @code{gnatlink}) - - @item - package @code{Cross_Reference} for command XREF (invoking @code{gnatlink}) - - @end itemize - - @noindent - Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable - with a string list value. It contains switches for the invocation of - @code{gnatls}. - - @smallexample - @group - project Proj1 is - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - end Proj1; - @end group - @end smallexample - - @noindent - All other packages contains a switch @code{Default_Switches}, an associative - array, indexed by the programming language (case insensitive) and having a - string list value. @code{Default_Switches ("Ada")} contains the switches for - the invocation of the tool corresponding to the package. - - @smallexample - @group - project Proj is - - for Source_Dirs use ("./**"); - - package gnatls is - for Switches use ("-a", "-v"); - end gnatls; - @end group - @group - - package Binder is - for Default_Switches ("Ada") use ("-C", "-e"); - end Binder; - @end group - @group - - package Linker is - for Default_Switches ("Ada") use ("-C"); - end Linker; - @end group - @group - - package Finder is - for Default_Switches ("Ada") use ("-a", "-f"); - end Finder; - @end group - @group - - package Cross_Reference is - for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u"); - end Cross_Reference; - end Proj; - @end group - @end smallexample - - @noindent - With the above project file, commands such as - - @smallexample - gnat ls -Pproj main - gnat xref -Pproj main - gnat bind -Pproj main.ali - @end smallexample - - @noindent - will set up the environment properly and invoke the tool with the switches - found in the package corresponding to the tool. - - - @node Glide and Project Files - @subsection Glide and Project Files - - @noindent - Glide will automatically recognize the @file{.gpr} extension for - project files, and will - convert them to its own internal format automatically. However, it - doesn't provide a syntax-oriented editor for modifying these - files. - The project file will be loaded as text when you select the menu item - @code{Ada} @result{} @code{Project} @result{} @code{Edit}. - You can edit this text and save the @file{gpr} file; - when you next select this project file in Glide it - will be automatically reloaded. - - - - @node An Extended Example - @section An Extended Example - - @noindent - Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources - in the respective directories. We would like to build them with a single - @command{gnatmake} command, and we would like to place their object files into - @file{.build} subdirectories of the source directories. Furthermore, we would - like to have to have two separate subdirectories in @file{.build} -- - @file{release} and @file{debug} -- which will contain the object files compiled with - different set of compilation flags. - - In other words, we have the following structure: - - @smallexample - @group - main - |- prog1 - | |- .build - | | debug - | | release - |- prog2 - |- .build - | debug - | release - @end group - @end smallexample - - @noindent - Here are the project files that we need to create in a directory @file{main} - to maintain this structure: - - @enumerate - - @item We create a @code{Common} project with a package @code{Compiler} that - specifies the compilation switches: - - @smallexample - File "common.gpr": - @group - @b{project} Common @b{is} - - @b{for} Source_Dirs @b{use} (); -- No source files - @end group - - @group - @b{type} Build_Type @b{is} ("release", "debug"); - Build : Build_Type := External ("BUILD", "debug"); - @end group - @group - @b{package} Compiler @b{is} - @b{case} Build @b{is} - @b{when} "release" => - @b{for} Default_Switches ("Ada") @b{use} ("-O2"); - @b{when} "debug" => - @b{for} Default_Switches ("Ada") @b{use} ("-g"); - @b{end case}; - @b{end} Compiler; - - @b{end} Common; - @end group - @end smallexample - - @item We create separate projects for the two programs: - - @smallexample - @group - File "prog1.gpr": - - @b{with} "common"; - @b{project} Prog1 @b{is} - - @b{for} Source_Dirs @b{use} ("prog1"); - @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Prog1; - @end group - @end smallexample - - @smallexample - @group - File "prog2.gpr": - - @b{with} "common"; - @b{project} Prog2 @b{is} - - @b{for} Source_Dirs @b{use} ("prog2"); - @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build; - - @b{package} Compiler @b{renames} Common.Compiler; - - @end group - @b{end} Prog2; - @end smallexample - - @item We create a wrapping project @var{Main}: - - @smallexample - @group - File "main.gpr": - - @b{with} "common"; - @b{with} "prog1"; - @b{with} "prog2"; - @b{project} Main @b{is} - - @b{package} Compiler @b{renames} Common.Compiler; - - @b{end} Main; - @end group - @end smallexample - - @item Finally we need to create a dummy procedure that @code{with}s (either - explicitly or implicitly) all the sources of our two programs. - - @end enumerate - - @noindent - Now we can build the programs using the command - - @smallexample - gnatmake -Pmain dummy - @end smallexample - - @noindent - for the Debug mode, or - - @smallexample - gnatmake -Pmain -XBUILD=release - @end smallexample - - @noindent - for the Release mode. - - - @c ******************************** - @c * Project File Complete Syntax * - @c ******************************** - - @node Project File Complete Syntax - @section Project File Complete Syntax - - @smallexample - project ::= - context_clause project_declaration - - context_clause ::= - @{with_clause@} - - with_clause ::= - @b{with} literal_string @{ , literal_string @} ; - - project_declaration ::= - @b{project} simple_name [ @b{extends} literal_string ] @b{is} - @{declarative_item@} - @b{end} simple_name; - - declarative_item ::= - package_declaration | - typed_string_declaration | - other_declarative_item - - package_declaration ::= - @b{package} simple_name package_completion - - package_completion ::= - package_body | package_renaming - - package body ::= - @b{is} - @{other_declarative_item@} - @b{end} simple_name ; - - package_renaming ::== - @b{renames} simple_name.simple_name ; - - typed_string_declaration ::= - @b{type} _simple_name @b{is} - ( literal_string @{, literal_string@} ); - - other_declarative_item ::= - attribute_declaration | - typed_variable_declaration | - variable_declaration | - case_construction - - attribute_declaration ::= - @b{for} attribute @b{use} expression ; - - attribute ::= - simple_name | - simple_name ( literal_string ) - - typed_variable_declaration ::= - simple_name : name := string_expression ; - - variable_declaration ::= - simple_name := expression; - - expression ::= - term @{& term@} - - term ::= - literal_string | - string_list | - name | - external_value | - attribute_reference - - literal_string ::= - (same as Ada) - - string_list ::= - ( expression @{ , expression @} ) - - external_value ::= - @b{external} ( literal_string [, literal_string] ) - - attribute_reference ::= - attribute_parent ' simple_name [ ( literal_string ) ] - - attribute_parent ::= - @b{project} | - simple_name | - simple_name . simple_name - - case_construction ::= - @b{case} name @b{is} - @{case_item@} - @b{end case} ; - - case_item ::= - @b{when} discrete_choice_list => @{case_construction | attribute_declaration@} - - discrete_choice_list ::= - literal_string @{| literal_string@} - - name ::= - simple_name @{. simple_name@} - - simple_name ::= - identifier (same as Ada) - - @end smallexample - - - @node Elaboration Order Handling in GNAT - @chapter Elaboration Order Handling in GNAT - @cindex Order of elaboration - @cindex Elaboration control - - @menu - * Elaboration Code in Ada 95:: - * Checking the Elaboration Order in Ada 95:: - * Controlling the Elaboration Order in Ada 95:: - * Controlling Elaboration in GNAT - Internal Calls:: - * Controlling Elaboration in GNAT - External Calls:: - * Default Behavior in GNAT - Ensuring Safety:: - * Elaboration Issues for Library Tasks:: - * Mixing Elaboration Models:: - * What to Do If the Default Elaboration Behavior Fails:: - * Elaboration for Access-to-Subprogram Values:: - * Summary of Procedures for Elaboration Control:: - * Other Elaboration Order Considerations:: - @end menu - - @noindent - This chapter describes the handling of elaboration code in Ada 95 and - in GNAT, and discusses how the order of elaboration of program units can - be controlled in GNAT, either automatically or with explicit programming - features. - - @node Elaboration Code in Ada 95 - @section Elaboration Code in Ada 95 - - @noindent - Ada 95 provides rather general mechanisms for executing code at elaboration - time, that is to say before the main program starts executing. Such code arises - in three contexts: - - @table @asis - @item Initializers for variables. - Variables declared at the library level, in package specs or bodies, can - require initialization that is performed at elaboration time, as in: - @smallexample - @cartouche - Sqrt_Half : Float := Sqrt (0.5); - @end cartouche - @end smallexample - - @item Package initialization code - Code in a @code{BEGIN-END} section at the outer level of a package body is - executed as part of the package body elaboration code. - - @item Library level task allocators - Tasks that are declared using task allocators at the library level - start executing immediately and hence can execute at elaboration time. - @end table - - @noindent - Subprogram calls are possible in any of these contexts, which means that - any arbitrary part of the program may be executed as part of the elaboration - code. It is even possible to write a program which does all its work at - elaboration time, with a null main program, although stylistically this - would usually be considered an inappropriate way to structure - a program. - - An important concern arises in the context of elaboration code: - we have to be sure that it is executed in an appropriate order. What we - have is a series of elaboration code sections, potentially one section - for each unit in the program. It is important that these execute - in the correct order. Correctness here means that, taking the above - example of the declaration of @code{Sqrt_Half}, - if some other piece of - elaboration code references @code{Sqrt_Half}, - then it must run after the - section of elaboration code that contains the declaration of - @code{Sqrt_Half}. - - There would never be any order of elaboration problem if we made a rule - that whenever you @code{with} a unit, you must elaborate both the spec and body - of that unit before elaborating the unit doing the @code{with}'ing: - - @smallexample - @group - @cartouche - @b{with} Unit_1; - @b{package} Unit_2 @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - would require that both the body and spec of @code{Unit_1} be elaborated - before the spec of @code{Unit_2}. However, a rule like that would be far too - restrictive. In particular, it would make it impossible to have routines - in separate packages that were mutually recursive. - - You might think that a clever enough compiler could look at the actual - elaboration code and determine an appropriate correct order of elaboration, - but in the general case, this is not possible. Consider the following - example. - - In the body of @code{Unit_1}, we have a procedure @code{Func_1} - that references - the variable @code{Sqrt_1}, which is declared in the elaboration code - of the body of @code{Unit_1}: - - @smallexample - @cartouche - Sqrt_1 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_1} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_1 = 1 @b{then} - Q := Unit_2.Func_2; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - @code{Unit_2} is exactly parallel, - it has a procedure @code{Func_2} that references - the variable @code{Sqrt_2}, which is declared in the elaboration code of - the body @code{Unit_2}: - - @smallexample - @cartouche - Sqrt_2 : Float := Sqrt (0.1); - @end cartouche - @end smallexample - - @noindent - The elaboration code of the body of @code{Unit_2} also contains: - - @smallexample - @group - @cartouche - @b{if} expression_2 = 2 @b{then} - Q := Unit_1.Func_1; - @b{end if}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the question is, which of the following orders of elaboration is - acceptable: - - @smallexample - @group - Spec of Unit_1 - Spec of Unit_2 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - or - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_2 - Body of Unit_1 - @end group - @end smallexample - - @noindent - If you carefully analyze the flow here, you will see that you cannot tell - at compile time the answer to this question. - If @code{expression_1} is not equal to 1, - and @code{expression_2} is not equal to 2, - then either order is acceptable, because neither of the function calls is - executed. If both tests evaluate to true, then neither order is acceptable - and in fact there is no correct order. - - If one of the two expressions is true, and the other is false, then one - of the above orders is correct, and the other is incorrect. For example, - if @code{expression_1} = 1 and @code{expression_2} /= 2, - then the call to @code{Func_2} - will occur, but not the call to @code{Func_1.} - This means that it is essential - to elaborate the body of @code{Unit_1} before - the body of @code{Unit_2}, so the first - order of elaboration is correct and the second is wrong. - - By making @code{expression_1} and @code{expression_2} - depend on input data, or perhaps - the time of day, we can make it impossible for the compiler or binder - to figure out which of these expressions will be true, and hence it - is impossible to guarantee a safe order of elaboration at run time. - - @node Checking the Elaboration Order in Ada 95 - @section Checking the Elaboration Order in Ada 95 - - @noindent - In some languages that involve the same kind of elaboration problems, - e.g. Java and C++, the programmer is expected to worry about these - ordering problems himself, and it is common to - write a program in which an incorrect elaboration order gives - surprising results, because it references variables before they - are initialized. - Ada 95 is designed to be a safe language, and a programmer-beware approach is - clearly not sufficient. Consequently, the language provides three lines - of defense: - - @table @asis - @item Standard rules - Some standard rules restrict the possible choice of elaboration - order. In particular, if you @code{with} a unit, then its spec is always - elaborated before the unit doing the @code{with}. Similarly, a parent - spec is always elaborated before the child spec, and finally - a spec is always elaborated before its corresponding body. - - @item Dynamic elaboration checks - @cindex Elaboration checks - @cindex Checks, elaboration - Dynamic checks are made at run time, so that if some entity is accessed - before it is elaborated (typically by means of a subprogram call) - then the exception (@code{Program_Error}) is raised. - - @item Elaboration control - Facilities are provided for the programmer to specify the desired order - of elaboration. - @end table - - Let's look at these facilities in more detail. First, the rules for - dynamic checking. One possible rule would be simply to say that the - exception is raised if you access a variable which has not yet been - elaborated. The trouble with this approach is that it could require - expensive checks on every variable reference. Instead Ada 95 has two - rules which are a little more restrictive, but easier to check, and - easier to state: - - @table @asis - @item Restrictions on calls - A subprogram can only be called at elaboration time if its body - has been elaborated. The rules for elaboration given above guarantee - that the spec of the subprogram has been elaborated before the - call, but not the body. If this rule is violated, then the - exception @code{Program_Error} is raised. - - @item Restrictions on instantiations - A generic unit can only be instantiated if the body of the generic - unit has been elaborated. Again, the rules for elaboration given above - guarantee that the spec of the generic unit has been elaborated - before the instantiation, but not the body. If this rule is - violated, then the exception @code{Program_Error} is raised. - @end table - - @noindent - The idea is that if the body has been elaborated, then any variables - it references must have been elaborated; by checking for the body being - elaborated we guarantee that none of its references causes any - trouble. As we noted above, this is a little too restrictive, because a - subprogram that has no non-local references in its body may in fact be safe - to call. However, it really would be unsafe to rely on this, because - it would mean that the caller was aware of details of the implementation - in the body. This goes against the basic tenets of Ada. - - A plausible implementation can be described as follows. - A Boolean variable is associated with each subprogram - and each generic unit. This variable is initialized to False, and is set to - True at the point body is elaborated. Every call or instantiation checks the - variable, and raises @code{Program_Error} if the variable is False. - - Note that one might think that it would be good enough to have one Boolean - variable for each package, but that would not deal with cases of trying - to call a body in the same package as the call - that has not been elaborated yet. - Of course a compiler may be able to do enough analysis to optimize away - some of the Boolean variables as unnecessary, and @code{GNAT} indeed - does such optimizations, but still the easiest conceptual model is to - think of there being one variable per subprogram. - - @node Controlling the Elaboration Order in Ada 95 - @section Controlling the Elaboration Order in Ada 95 - - @noindent - In the previous section we discussed the rules in Ada 95 which ensure - that @code{Program_Error} is raised if an incorrect elaboration order is - chosen. This prevents erroneous executions, but we need mechanisms to - specify a correct execution and avoid the exception altogether. - To achieve this, Ada 95 provides a number of features for controlling - the order of elaboration. We discuss these features in this section. - - First, there are several ways of indicating to the compiler that a given - unit has no elaboration problems: - - @table @asis - @item packages that do not require a body - In Ada 95, a library package that does not require a body does not permit - a body. This means that if we have a such a package, as in: - - @smallexample - @group - @cartouche - @b{package} Definitions @b{is} - @b{generic} - @b{type} m @b{is new} integer; - @b{package} Subp @b{is} - @b{type} a @b{is array} (1 .. 10) @b{of} m; - @b{type} b @b{is array} (1 .. 20) @b{of} m; - @b{end} Subp; - @b{end} Definitions; - @end cartouche - @end group - @end smallexample - - @noindent - A package that @code{with}'s @code{Definitions} may safely instantiate - @code{Definitions.Subp} because the compiler can determine that there - definitely is no package body to worry about in this case - - @item pragma Pure - @cindex pragma Pure - @findex Pure - Places sufficient restrictions on a unit to guarantee that - no call to any subprogram in the unit can result in an - elaboration problem. This means that the compiler does not need - to worry about the point of elaboration of such units, and in - particular, does not need to check any calls to any subprograms - in this unit. - - @item pragma Preelaborate - @findex Preelaborate - @cindex pragma Preelaborate - This pragma places slightly less stringent restrictions on a unit than - does pragma Pure, - but these restrictions are still sufficient to ensure that there - are no elaboration problems with any calls to the unit. - - @item pragma Elaborate_Body - @findex Elaborate_Body - @cindex pragma Elaborate_Body - This pragma requires that the body of a unit be elaborated immediately - after its spec. Suppose a unit @code{A} has such a pragma, - and unit @code{B} does - a @code{with} of unit @code{A}. Recall that the standard rules require - the spec of unit @code{A} - to be elaborated before the @code{with}'ing unit; given the pragma in - @code{A}, we also know that the body of @code{A} - will be elaborated before @code{B}, so - that calls to @code{A} are safe and do not need a check. - @end table - - @noindent - Note that, - unlike pragma @code{Pure} and pragma @code{Preelaborate}, - the use of - @code{Elaborate_Body} does not guarantee that the program is - free of elaboration problems, because it may not be possible - to satisfy the requested elaboration order. - Let's go back to the example with @code{Unit_1} and @code{Unit_2}. - If a programmer - marks @code{Unit_1} as @code{Elaborate_Body}, - and not @code{Unit_2,} then the order of - elaboration will be: - - @smallexample - @group - Spec of Unit_2 - Spec of Unit_1 - Body of Unit_1 - Body of Unit_2 - @end group - @end smallexample - - @noindent - Now that means that the call to @code{Func_1} in @code{Unit_2} - need not be checked, - it must be safe. But the call to @code{Func_2} in - @code{Unit_1} may still fail if - @code{Expression_1} is equal to 1, - and the programmer must still take - responsibility for this not being the case. - - If all units carry a pragma @code{Elaborate_Body}, then all problems are - eliminated, except for calls entirely within a body, which are - in any case fully under programmer control. However, using the pragma - everywhere is not always possible. - In particular, for our @code{Unit_1}/@code{Unit_2} example, if - we marked both of them as having pragma @code{Elaborate_Body}, then - clearly there would be no possible elaboration order. - - The above pragmas allow a server to guarantee safe use by clients, and - clearly this is the preferable approach. Consequently a good rule in - Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible, - and if this is not possible, - mark them as @code{Elaborate_Body} if possible. - As we have seen, there are situations where neither of these - three pragmas can be used. - So we also provide methods for clients to control the - order of elaboration of the servers on which they depend: - - @table @asis - @item pragma Elaborate (unit) - @findex Elaborate - @cindex pragma Elaborate - This pragma is placed in the context clause, after a @code{with} clause, - and it requires that the body of the named unit be elaborated before - the unit in which the pragma occurs. The idea is to use this pragma - if the current unit calls at elaboration time, directly or indirectly, - some subprogram in the named unit. - - @item pragma Elaborate_All (unit) - @findex Elaborate_All - @cindex pragma Elaborate_All - This is a stronger version of the Elaborate pragma. Consider the - following example: - - @smallexample - Unit A @code{with}'s unit B and calls B.Func in elab code - Unit B @code{with}'s unit C, and B.Func calls C.Func - @end smallexample - - @noindent - Now if we put a pragma @code{Elaborate (B)} - in unit @code{A}, this ensures that the - body of @code{B} is elaborated before the call, but not the - body of @code{C}, so - the call to @code{C.Func} could still cause @code{Program_Error} to - be raised. - - The effect of a pragma @code{Elaborate_All} is stronger, it requires - not only that the body of the named unit be elaborated before the - unit doing the @code{with}, but also the bodies of all units that the - named unit uses, following @code{with} links transitively. For example, - if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, - then it requires - not only that the body of @code{B} be elaborated before @code{A}, - but also the - body of @code{C}, because @code{B} @code{with}'s @code{C}. - @end table - - @noindent - We are now in a position to give a usage rule in Ada 95 for avoiding - elaboration problems, at least if dynamic dispatching and access to - subprogram values are not used. We will handle these cases separately - later. - - The rule is simple. If a unit has elaboration code that can directly or - indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate - a generic unit in a @code{with}'ed unit, - then if the @code{with}'ed unit does not have - pragma @code{Pure} or @code{Preelaborate}, then the client should have - a pragma @code{Elaborate_All} - for the @code{with}'ed unit. By following this rule a client is - assured that calls can be made without risk of an exception. - If this rule is not followed, then a program may be in one of four - states: - - @table @asis - @item No order exists - No order of elaboration exists which follows the rules, taking into - account any @code{Elaborate}, @code{Elaborate_All}, - or @code{Elaborate_Body} pragmas. In - this case, an Ada 95 compiler must diagnose the situation at bind - time, and refuse to build an executable program. - - @item One or more orders exist, all incorrect - One or more acceptable elaboration orders exists, and all of them - generate an elaboration order problem. In this case, the binder - can build an executable program, but @code{Program_Error} will be raised - when the program is run. - - @item Several orders exist, some right, some incorrect - One or more acceptable elaboration orders exists, and some of them - work, and some do not. The programmer has not controlled - the order of elaboration, so the binder may or may not pick one of - the correct orders, and the program may or may not raise an - exception when it is run. This is the worst case, because it means - that the program may fail when moved to another compiler, or even - another version of the same compiler. - - @item One or more orders exists, all correct - One ore more acceptable elaboration orders exist, and all of them - work. In this case the program runs successfully. This state of - affairs can be guaranteed by following the rule we gave above, but - may be true even if the rule is not followed. - @end table - - @noindent - Note that one additional advantage of following our Elaborate_All rule - is that the program continues to stay in the ideal (all orders OK) state - even if maintenance - changes some bodies of some subprograms. Conversely, if a program that does - not follow this rule happens to be safe at some point, this state of affairs - may deteriorate silently as a result of maintenance changes. - - You may have noticed that the above discussion did not mention - the use of @code{Elaborate_Body}. This was a deliberate omission. If you - @code{with} an @code{Elaborate_Body} unit, it still may be the case that - code in the body makes calls to some other unit, so it is still necessary - to use @code{Elaborate_All} on such units. - - @node Controlling Elaboration in GNAT - Internal Calls - @section Controlling Elaboration in GNAT - Internal Calls - - @noindent - In the case of internal calls, i.e. calls within a single package, the - programmer has full control over the order of elaboration, and it is up - to the programmer to elaborate declarations in an appropriate order. For - example writing: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - Q : Float := One; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - @end cartouche - @end group - @end smallexample - - @noindent - will obviously raise @code{Program_Error} at run time, because function - One will be called before its body is elaborated. In this case GNAT will - generate a warning that the call will raise @code{Program_Error}: - - @smallexample - @group - @cartouche - 1. procedure y is - 2. function One return Float; - 3. - 4. Q : Float := One; - | - >>> warning: cannot call "One" before body is elaborated - >>> warning: Program_Error will be raised at run time - - 5. - 6. function One return Float is - 7. begin - 8. return 1.0; - 9. end One; - 10. - 11. begin - 12. null; - 13. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that in this particular case, it is likely that the call is safe, because - the function @code{One} does not access any global variables. - Nevertheless in Ada 95, we do not want the validity of the check to depend on - the contents of the body (think about the separate compilation case), so this - is still wrong, as we discussed in the previous sections. - - The error is easily corrected by rearranging the declarations so that the - body of One appears before the declaration containing the call - (note that in Ada 95, - declarations can appear in any order, so there is no restriction that - would prevent this reordering, and if we write: - - @smallexample - @group - @cartouche - @b{function} One @b{return} Float; - - @b{function} One @b{return} Float @b{is} - @b{begin} - return 1.0; - @b{end} One; - - Q : Float := One; - @end cartouche - @end group - @end smallexample - - @noindent - then all is well, no warning is generated, and no - @code{Program_Error} exception - will be raised. - Things are more complicated when a chain of subprograms is executed: - - @smallexample - @group - @cartouche - @b{function} A @b{return} Integer; - @b{function} B @b{return} Integer; - @b{function} C @b{return} Integer; - - @b{function} B @b{return} Integer @b{is begin return} A; @b{end}; - @b{function} C @b{return} Integer @b{is begin return} B; @b{end}; - - X : Integer := C; - - @b{function} A @b{return} Integer @b{is begin return} 1; @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Now the call to @code{C} - at elaboration time in the declaration of @code{X} is correct, because - the body of @code{C} is already elaborated, - and the call to @code{B} within the body of - @code{C} is correct, but the call - to @code{A} within the body of @code{B} is incorrect, because the body - of @code{A} has not been elaborated, so @code{Program_Error} - will be raised on the call to @code{A}. - In this case GNAT will generate a - warning that @code{Program_Error} may be - raised at the point of the call. Let's look at the warning: - - @smallexample - @group - @cartouche - 1. procedure x is - 2. function A return Integer; - 3. function B return Integer; - 4. function C return Integer; - 5. - 6. function B return Integer is begin return A; end; - | - >>> warning: call to "A" before body is elaborated may - raise Program_Error - >>> warning: "B" called at line 7 - >>> warning: "C" called at line 9 - - 7. function C return Integer is begin return B; end; - 8. - 9. X : Integer := C; - 10. - 11. function A return Integer is begin return 1; end; - 12. - 13. begin - 14. null; - 15. end; - @end cartouche - @end group - @end smallexample - - @noindent - Note that the message here says "may raise", instead of the direct case, - where the message says "will be raised". That's because whether - @code{A} is - actually called depends in general on run-time flow of control. - For example, if the body of @code{B} said - - @smallexample - @group - @cartouche - @b{function} B @b{return} Integer @b{is} - @b{begin} - @b{if} some-condition-depending-on-input-data @b{then} - @b{return} A; - @b{else} - @b{return} 1; - @b{end if}; - @b{end} B; - @end cartouche - @end group - @end smallexample - - @noindent - then we could not know until run time whether the incorrect call to A would - actually occur, so @code{Program_Error} might - or might not be raised. It is possible for a compiler to - do a better job of analyzing bodies, to - determine whether or not @code{Program_Error} - might be raised, but it certainly - couldn't do a perfect job (that would require solving the halting problem - and is provably impossible), and because this is a warning anyway, it does - not seem worth the effort to do the analysis. Cases in which it - would be relevant are rare. - - In practice, warnings of either of the forms given - above will usually correspond to - real errors, and should be examined carefully and eliminated. - In the rare case where a warning is bogus, it can be suppressed by any of - the following methods: - - @itemize @bullet - @item - Compile with the @option{-gnatws} switch set - - @item - Suppress @code{Elaboration_Checks} for the called subprogram - - @item - Use pragma @code{Warnings_Off} to turn warnings off for the call - @end itemize - - @noindent - For the internal elaboration check case, - GNAT by default generates the - necessary run-time checks to ensure - that @code{Program_Error} is raised if any - call fails an elaboration check. Of course this can only happen if a - warning has been issued as described above. The use of pragma - @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress - some of these checks, meaning that it may be possible (but is not - guaranteed) for a program to be able to call a subprogram whose body - is not yet elaborated, without raising a @code{Program_Error} exception. - - @node Controlling Elaboration in GNAT - External Calls - @section Controlling Elaboration in GNAT - External Calls - - @noindent - The previous section discussed the case in which the execution of a - particular thread of elaboration code occurred entirely within a - single unit. This is the easy case to handle, because a programmer - has direct and total control over the order of elaboration, and - furthermore, checks need only be generated in cases which are rare - and which the compiler can easily detect. - The situation is more complex when separate compilation is taken into account. - Consider the following: - - @smallexample - @cartouche - @group - @b{package} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float; - @b{end} Math; - - @b{package body} Math @b{is} - @b{function} Sqrt (Arg : Float) @b{return} Float @b{is} - @b{begin} - ... - @b{end} Sqrt; - @b{end} Math; - @end group - @group - @b{with} Math; - @b{package} Stuff @b{is} - X : Float := Math.Sqrt (0.5); - @b{end} Stuff; - - @b{with} Stuff; - @b{procedure} Main @b{is} - @b{begin} - ... - @b{end} Main; - @end group - @end cartouche - @end smallexample - - @noindent - where @code{Main} is the main program. When this program is executed, the - elaboration code must first be executed, and one of the jobs of the - binder is to determine the order in which the units of a program are - to be elaborated. In this case we have four units: the spec and body - of @code{Math}, - the spec of @code{Stuff} and the body of @code{Main}). - In what order should the four separate sections of elaboration code - be executed? - - There are some restrictions in the order of elaboration that the binder - can choose. In particular, if unit U has a @code{with} - for a package @code{X}, then you - are assured that the spec of @code{X} - is elaborated before U , but you are - not assured that the body of @code{X} - is elaborated before U. - This means that in the above case, the binder is allowed to choose the - order: - - @smallexample - spec of Math - spec of Stuff - body of Math - body of Main - @end smallexample - - @noindent - but that's not good, because now the call to @code{Math.Sqrt} - that happens during - the elaboration of the @code{Stuff} - spec happens before the body of @code{Math.Sqrt} is - elaborated, and hence causes @code{Program_Error} exception to be raised. - At first glance, one might say that the binder is misbehaving, because - obviously you want to elaborate the body of something you @code{with} - first, but - that is not a general rule that can be followed in all cases. Consider - - @smallexample - @group - @cartouche - @b{package} X @b{is} ... - - @b{package} Y @b{is} ... - - @b{with} X; - @b{package body} Y @b{is} ... - - @b{with} Y; - @b{package body} X @b{is} ... - @end cartouche - @end group - @end smallexample - - @noindent - This is a common arrangement, and, apart from the order of elaboration - problems that might arise in connection with elaboration code, this works fine. - A rule that says that you must first elaborate the body of anything you - @code{with} cannot work in this case: - the body of @code{X} @code{with}'s @code{Y}, - which means you would have to - elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, - which means - you have to elaborate the body of @code{X} first, but ... and we have a - loop that cannot be broken. - - It is true that the binder can in many cases guess an order of elaboration - that is unlikely to cause a @code{Program_Error} - exception to be raised, and it tries to do so (in the - above example of @code{Math/Stuff/Spec}, the GNAT binder will - by default - elaborate the body of @code{Math} right after its spec, so all will be well). - - However, a program that blindly relies on the binder to be helpful can - get into trouble, as we discussed in the previous sections, so - GNAT - provides a number of facilities for assisting the programmer in - developing programs that are robust with respect to elaboration order. - - @node Default Behavior in GNAT - Ensuring Safety - @section Default Behavior in GNAT - Ensuring Safety - - @noindent - The default behavior in GNAT ensures elaboration safety. In its - default mode GNAT implements the - rule we previously described as the right approach. Let's restate it: - - @itemize - @item - @emph{If a unit has elaboration code that can directly or indirectly make a - call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit - in a @code{with}'ed unit, then if the @code{with}'ed unit - does not have pragma @code{Pure} or - @code{Preelaborate}, then the client should have an - @code{Elaborate_All} for the @code{with}'ed unit.} - @end itemize - - @noindent - By following this rule a client - is assured that calls and instantiations can be made without risk of an exception. - - In this mode GNAT traces all calls that are potentially made from - elaboration code, and puts in any missing implicit @code{Elaborate_All} - pragmas. - The advantage of this approach is that no elaboration problems - are possible if the binder can find an elaboration order that is - consistent with these implicit @code{Elaborate_All} pragmas. The - disadvantage of this approach is that no such order may exist. - - If the binder does not generate any diagnostics, then it means that it - has found an elaboration order that is guaranteed to be safe. However, - the binder may still be relying on implicitly generated - @code{Elaborate_All} pragmas so portability to other compilers than - GNAT is not guaranteed. - - If it is important to guarantee portability, then the compilations should - use the - @option{-gnatwl} - (warn on elaboration problems) switch. This will cause warning messages - to be generated indicating the missing @code{Elaborate_All} pragmas. - Consider the following source program: - - @smallexample - @group - @cartouche - @b{with} k; - @b{package} j @b{is} - m : integer := k.r; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - where it is clear that there - should be a pragma @code{Elaborate_All} - for unit @code{k}. An implicit pragma will be generated, and it is - likely that the binder will be able to honor it. However, - it is safer to include the pragma explicitly in the source. If this - unit is compiled with the - @option{-gnatwl} - switch, then the compiler outputs a warning: - - @smallexample - @group - @cartouche - 1. with k; - 2. package j is - 3. m : integer := k.r; - | - >>> warning: call to "r" may raise Program_Error - >>> warning: missing pragma Elaborate_All for "k" - - 4. end; - @end cartouche - @end group - @end smallexample - - @noindent - and these warnings can be used as a guide for supplying manually - the missing pragmas. - - This default mode is more restrictive than the Ada Reference - Manual, and it is possible to construct programs which will compile - using the dynamic model described there, but will run into a - circularity using the safer static model we have described. - - Of course any Ada compiler must be able to operate in a mode - consistent with the requirements of the Ada Reference Manual, - and in particular must have the capability of implementing the - standard dynamic model of elaboration with run-time checks. - - In GNAT, this standard mode can be achieved either by the use of - the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake}) - command, or by the use of the configuration pragma: - - @smallexample - pragma Elaboration_Checks (RM); - @end smallexample - - @noindent - Either approach will cause the unit affected to be compiled using the - standard dynamic run-time elaboration checks described in the Ada - Reference Manual. The static model is generally preferable, since it - is clearly safer to rely on compile and link time checks rather than - run-time checks. However, in the case of legacy code, it may be - difficult to meet the requirements of the static model. This - issue is further discussed in - @ref{What to Do If the Default Elaboration Behavior Fails}. - - Note that the static model provides a strict subset of the allowed - behavior and programs of the Ada Reference Manual, so if you do - adhere to the static model and no circularities exist, - then you are assured that your program will - work using the dynamic model. - - @node Elaboration Issues for Library Tasks - @section Elaboration Issues for Library Tasks - @cindex Library tasks, elaboration issues - @cindex Elaboration of library tasks - - @noindent - In this section we examine special elaboration issues that arise for - programs that declare library level tasks. - - Generally the model of execution of an Ada program is that all units are - elaborated, and then execution of the program starts. However, the - declaration of library tasks definitely does not fit this model. The - reason for this is that library tasks start as soon as they are declared - (more precisely, as soon as the statement part of the enclosing package - body is reached), that is to say before elaboration - of the program is complete. This means that if such a task calls a - subprogram, or an entry in another task, the callee may or may not be - elaborated yet, and in the standard - Reference Manual model of dynamic elaboration checks, you can even - get timing dependent Program_Error exceptions, since there can be - a race between the elaboration code and the task code. - - The static model of elaboration in GNAT seeks to avoid all such - dynamic behavior, by being conservative, and the conservative - approach in this particular case is to assume that all the code - in a task body is potentially executed at elaboration time if - a task is declared at the library level. - - This can definitely result in unexpected circularities. Consider - the following example - - @smallexample - package Decls is - task Lib_Task is - entry Start; - end Lib_Task; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - procedure Main is - begin - Decls.Lib_Task.Start; - end; - @end smallexample - - @noindent - If the above example is compiled in the default static elaboration - mode, then a circularity occurs. The circularity comes from the call - @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since - this call occurs in elaboration code, we need an implicit pragma - @code{Elaborate_All} for @code{Utils}. This means that not only must - the spec and body of @code{Utils} be elaborated before the body - of @code{Decls}, but also the spec and body of any unit that is - @code{with'ed} by the body of @code{Utils} must also be elaborated before - the body of @code{Decls}. This is the transitive implication of - pragma @code{Elaborate_All} and it makes sense, because in general - the body of @code{Put_Val} might have a call to something in a - @code{with'ed} unit. - - In this case, the body of Utils (actually its spec) @code{with's} - @code{Decls}. Unfortunately this means that the body of @code{Decls} - must be elaborated before itself, in case there is a call from the - body of @code{Utils}. - - Here is the exact chain of events we are worrying about: - - @enumerate - @item - In the body of @code{Decls} a call is made from within the body of a library - task to a subprogram in the package @code{Utils}. Since this call may - occur at elaboration time (given that the task is activated at elaboration - time), we have to assume the worst, i.e. that the - call does happen at elaboration time. - - @item - This means that the body and spec of @code{Util} must be elaborated before - the body of @code{Decls} so that this call does not cause an access before - elaboration. - - @item - Within the body of @code{Util}, specifically within the body of - @code{Util.Put_Val} there may be calls to any unit @code{with}'ed - by this package. - - @item - One such @code{with}'ed package is package @code{Decls}, so there - might be a call to a subprogram in @code{Decls} in @code{Put_Val}. - In fact there is such a call in this example, but we would have to - assume that there was such a call even if it were not there, since - we are not supposed to write the body of @code{Decls} knowing what - is in the body of @code{Utils}; certainly in the case of the - static elaboration model, the compiler does not know what is in - other bodies and must assume the worst. - - @item - This means that the spec and body of @code{Decls} must also be - elaborated before we elaborate the unit containing the call, but - that unit is @code{Decls}! This means that the body of @code{Decls} - must be elaborated before itself, and that's a circularity. - @end enumerate - - @noindent - Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in - the body of @code{Decls} you will get a true Ada Reference Manual - circularity that makes the program illegal. - - In practice, we have found that problems with the static model of - elaboration in existing code often arise from library tasks, so - we must address this particular situation. - - Note that if we compile and run the program above, using the dynamic model of - elaboration (that is to say use the @option{-gnatE} switch), - then it compiles, binds, - links, and runs, printing the expected result of 2. Therefore in some sense - the circularity here is only apparent, and we need to capture - the properties of this program that distinguish it from other library-level - tasks that have real elaboration problems. - - We have four possible answers to this question: - - @itemize @bullet - - @item - Use the dynamic model of elaboration. - - If we use the @option{-gnatE} switch, then as noted above, the program works. - Why is this? If we examine the task body, it is apparent that the task cannot - proceed past the - @code{accept} statement until after elaboration has been completed, because - the corresponding entry call comes from the main program, not earlier. - This is why the dynamic model works here. But that's really giving - up on a precise analysis, and we prefer to take this approach only if we cannot - solve the - problem in any other manner. So let us examine two ways to reorganize - the program to avoid the potential elaboration problem. - - @item - Split library tasks into separate packages. - - Write separate packages, so that library tasks are isolated from - other declarations as much as possible. Let us look at a variation on - the above program. - - @smallexample - package Decls1 is - task Lib_Task is - entry Start; - end Lib_Task; - end Decls1; - - with Utils; - package body Decls1 is - task body Lib_Task is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task; - end Decls1; - - package Decls2 is - type My_Int is new Integer; - function Ident (M : My_Int) return My_Int; - end Decls2; - - with Utils; - package body Decls2 is - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls2; - - with Decls2; - package Utils is - procedure Put_Val (Arg : Decls2.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls2.My_Int) is - begin - Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls1; - procedure Main is - begin - Decls1.Lib_Task.Start; - end; - @end smallexample - - @noindent - All we have done is to split @code{Decls} into two packages, one - containing the library task, and one containing everything else. Now - there is no cycle, and the program compiles, binds, links and executes - using the default static model of elaboration. - - @item - Declare separate task types. - - A significant part of the problem arises because of the use of the - single task declaration form. This means that the elaboration of - the task type, and the elaboration of the task itself (i.e. the - creation of the task) happen at the same time. A good rule - of style in Ada 95 is to always create explicit task types. By - following the additional step of placing task objects in separate - packages from the task type declaration, many elaboration problems - are avoided. Here is another modified example of the example program: - - @smallexample - package Decls is - task type Lib_Task_Type is - entry Start; - end Lib_Task_Type; - - type My_Int is new Integer; - - function Ident (M : My_Int) return My_Int; - end Decls; - - with Utils; - package body Decls is - task body Lib_Task_Type is - begin - accept Start; - Utils.Put_Val (2); - end Lib_Task_Type; - - function Ident (M : My_Int) return My_Int is - begin - return M; - end Ident; - end Decls; - - with Decls; - package Utils is - procedure Put_Val (Arg : Decls.My_Int); - end Utils; - - with Text_IO; - package body Utils is - procedure Put_Val (Arg : Decls.My_Int) is - begin - Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); - end Put_Val; - end Utils; - - with Decls; - package Declst is - Lib_Task : Decls.Lib_Task_Type; - end Declst; - - with Declst; - procedure Main is - begin - Declst.Lib_Task.Start; - end; - @end smallexample - - @noindent - What we have done here is to replace the @code{task} declaration in - package @code{Decls} with a @code{task type} declaration. Then we - introduce a separate package @code{Declst} to contain the actual - task object. This separates the elaboration issues for - the @code{task type} - declaration, which causes no trouble, from the elaboration issues - of the task object, which is also unproblematic, since it is now independent - of the elaboration of @code{Utils}. - This separation of concerns also corresponds to - a generally sound engineering principle of separating declarations - from instances. This version of the program also compiles, binds, links, - and executes, generating the expected output. - - @item - Use No_Entry_Calls_In_Elaboration_Code restriction. - @cindex No_Entry_Calls_In_Elaboration_Code - - The previous two approaches described how a program can be restructured - to avoid the special problems caused by library task bodies. in practice, - however, such restructuring may be difficult to apply to existing legacy code, - so we must consider solutions that do not require massive rewriting. - - Let us consider more carefully why our original sample program works - under the dynamic model of elaboration. The reason is that the code - in the task body blocks immediately on the @code{accept} - statement. Now of course there is nothing to prohibit elaboration - code from making entry calls (for example from another library level task), - so we cannot tell in isolation that - the task will not execute the accept statement during elaboration. - - However, in practice it is very unusual to see elaboration code - make any entry calls, and the pattern of tasks starting - at elaboration time and then immediately blocking on @code{accept} or - @code{select} statements is very common. What this means is that - the compiler is being too pessimistic when it analyzes the - whole package body as though it might be executed at elaboration - time. - - If we know that the elaboration code contains no entry calls, (a very safe - assumption most of the time, that could almost be made the default - behavior), then we can compile all units of the program under control - of the following configuration pragma: - - @smallexample - pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); - @end smallexample - - @noindent - This pragma can be placed in the @file{gnat.adc} file in the usual - manner. If we take our original unmodified program and compile it - in the presence of a @file{gnat.adc} containing the above pragma, - then once again, we can compile, bind, link, and execute, obtaining - the expected result. In the presence of this pragma, the compiler does - not trace calls in a task body, that appear after the first @code{accept} - or @code{select} statement, and therefore does not report a potential - circularity in the original program. - - The compiler will check to the extent it can that the above - restriction is not violated, but it is not always possible to do a - complete check at compile time, so it is important to use this - pragma only if the stated restriction is in fact met, that is to say - no task receives an entry call before elaboration of all units is completed. - - @end itemize - - @node Mixing Elaboration Models - @section Mixing Elaboration Models - @noindent - So far, we have assumed that the entire program is either compiled - using the dynamic model or static model, ensuring consistency. It - is possible to mix the two models, but rules have to be followed - if this mixing is done to ensure that elaboration checks are not - omitted. - - The basic rule is that @emph{a unit compiled with the static model cannot - be @code{with'ed} by a unit compiled with the dynamic model}. The - reason for this is that in the static model, a unit assumes that - its clients guarantee to use (the equivalent of) pragma - @code{Elaborate_All} so that no elaboration checks are required - in inner subprograms, and this assumption is violated if the - client is compiled with dynamic checks. - - The precise rule is as follows. A unit that is compiled with dynamic - checks can only @code{with} a unit that meets at least one of the - following criteria: - - @itemize @bullet - - @item - The @code{with'ed} unit is itself compiled with dynamic elaboration - checks (that is with the @option{-gnatE} switch. - - @item - The @code{with'ed} unit is an internal GNAT implementation unit from - the System, Interfaces, Ada, or GNAT hierarchies. - - @item - The @code{with'ed} unit has pragma Preelaborate or pragma Pure. - - @item - The @code{with'ing} unit (that is the client) has an explicit pragma - @code{Elaborate_All} for the @code{with'ed} unit. - - @end itemize - - @noindent - If this rule is violated, that is if a unit with dynamic elaboration - checks @code{with's} a unit that does not meet one of the above four - criteria, then the binder (@code{gnatbind}) will issue a warning - similar to that in the following example: - - @smallexample - warning: "x.ads" has dynamic elaboration checks and with's - warning: "y.ads" which has static elaboration checks - @end smallexample - - @noindent - These warnings indicate that the rule has been violated, and that as a result - elaboration checks may be missed in the resulting executable file. - This warning may be suppressed using the @code{-ws} binder switch - in the usual manner. - - One useful application of this mixing rule is in the case of a subsystem - which does not itself @code{with} units from the remainder of the - application. In this case, the entire subsystem can be compiled with - dynamic checks to resolve a circularity in the subsystem, while - allowing the main application that uses this subsystem to be compiled - using the more reliable default static model. - - @node What to Do If the Default Elaboration Behavior Fails - @section What to Do If the Default Elaboration Behavior Fails - - @noindent - If the binder cannot find an acceptable order, it outputs detailed - diagnostics. For example: - @smallexample - @group - @iftex - @leftskip=0cm - @end iftex - error: elaboration circularity detected - info: "proc (body)" must be elaborated before "pack (body)" - info: reason: Elaborate_All probably needed in unit "pack (body)" - info: recompile "pack (body)" with -gnatwl - info: for full details - info: "proc (body)" - info: is needed by its spec: - info: "proc (spec)" - info: which is withed by: - info: "pack (body)" - info: "pack (body)" must be elaborated before "proc (body)" - info: reason: pragma Elaborate in unit "proc (body)" - @end group - - @end smallexample - - @noindent - In this case we have a cycle that the binder cannot break. On the one - hand, there is an explicit pragma Elaborate in @code{proc} for - @code{pack}. This means that the body of @code{pack} must be elaborated - before the body of @code{proc}. On the other hand, there is elaboration - code in @code{pack} that calls a subprogram in @code{proc}. This means - that for maximum safety, there should really be a pragma - Elaborate_All in @code{pack} for @code{proc} which would require that - the body of @code{proc} be elaborated before the body of - @code{pack}. Clearly both requirements cannot be satisfied. - Faced with a circularity of this kind, you have three different options. - - @table @asis - @item Fix the program - The most desirable option from the point of view of long-term maintenance - is to rearrange the program so that the elaboration problems are avoided. - One useful technique is to place the elaboration code into separate - child packages. Another is to move some of the initialization code to - explicitly called subprograms, where the program controls the order - of initialization explicitly. Although this is the most desirable option, - it may be impractical and involve too much modification, especially in - the case of complex legacy code. - - @item Perform dynamic checks - If the compilations are done using the - @option{-gnatE} - (dynamic elaboration check) switch, then GNAT behaves in - a quite different manner. Dynamic checks are generated for all calls - that could possibly result in raising an exception. With this switch, - the compiler does not generate implicit @code{Elaborate_All} pragmas. - The behavior then is exactly as specified in the Ada 95 Reference Manual. - The binder will generate an executable program that may or may not - raise @code{Program_Error}, and then it is the programmer's job to ensure - that it does not raise an exception. Note that it is important to - compile all units with the switch, it cannot be used selectively. - - @item Suppress checks - The drawback of dynamic checks is that they generate a - significant overhead at run time, both in space and time. If you - are absolutely sure that your program cannot raise any elaboration - exceptions, and you still want to use the dynamic elaboration model, - then you can use the configuration pragma - @code{Suppress (Elaboration_Checks)} to suppress all such checks. For - example this pragma could be placed in the @file{gnat.adc} file. - - @item Suppress checks selectively - When you know that certain calls in elaboration code cannot possibly - lead to an elaboration error, and the binder nevertheless generates warnings - on those calls and inserts Elaborate_All pragmas that lead to elaboration - circularities, it is possible to remove those warnings locally and obtain - a program that will bind. Clearly this can be unsafe, and it is the - responsibility of the programmer to make sure that the resulting program has - no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can - be used with different granularity to suppress warnings and break - elaboration circularities: - - @itemize @bullet - @item - Place the pragma that names the called subprogram in the declarative part - that contains the call. - - @item - Place the pragma in the declarative part, without naming an entity. This - disables warnings on all calls in the corresponding declarative region. - - @item - Place the pragma in the package spec that declares the called subprogram, - and name the subprogram. This disables warnings on all elaboration calls to - that subprogram. - - @item - Place the pragma in the package spec that declares the called subprogram, - without naming any entity. This disables warnings on all elaboration calls to - all subprograms declared in this spec. - @end itemize - - @noindent - These four cases are listed in order of decreasing safety, and therefore - require increasing programmer care in their application. Consider the - following program: - @smallexample - - package Pack1 is - function F1 return Integer; - X1 : Integer; - end Pack1; - - package Pack2 is - function F2 return Integer; - function Pure (x : integer) return integer; - -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) - -- pragma Suppress (Elaboration_Check); -- (4) - end Pack2; - - with Pack2; - package body Pack1 is - function F1 return Integer is - begin - return 100; - end F1; - Val : integer := Pack2.Pure (11); -- Elab. call (1) - begin - declare - -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) - -- pragma Suppress(Elaboration_Check); -- (2) - begin - X1 := Pack2.F2 + 1; -- Elab. call (2) - end; - end Pack1; - - with Pack1; - package body Pack2 is - function F2 return Integer is - begin - return Pack1.F1; - end F2; - function Pure (x : integer) return integer is - begin - return x ** 3 - 3 * x; - end; - end Pack2; - - with Pack1, Ada.Text_IO; - procedure Proc3 is - begin - Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 - end Proc3; - @end smallexample - In the absence of any pragmas, an attempt to bind this program produces - the following diagnostics: - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - error: elaboration circularity detected - info: "pack1 (body)" must be elaborated before "pack1 (body)" - info: reason: Elaborate_All probably needed in unit "pack1 (body)" - info: recompile "pack1 (body)" with -gnatwl for full details - info: "pack1 (body)" - info: must be elaborated along with its spec: - info: "pack1 (spec)" - info: which is withed by: - info: "pack2 (body)" - info: which must be elaborated along with its spec: - info: "pack2 (spec)" - info: which is withed by: - info: "pack1 (body)" - @end group - @end smallexample - The sources of the circularity are the two calls to @code{Pack2.Pure} and - @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to - F2 is safe, even though F2 calls F1, because the call appears after the - elaboration of the body of F1. Therefore the pragma (1) is safe, and will - remove the warning on the call. It is also possible to use pragma (2) - because there are no other potentially unsafe calls in the block. - - @noindent - The call to @code{Pure} is safe because this function does not depend on the - state of @code{Pack2}. Therefore any call to this function is safe, and it - is correct to place pragma (3) in the corresponding package spec. - - @noindent - Finally, we could place pragma (4) in the spec of @code{Pack2} to disable - warnings on all calls to functions declared therein. Note that this is not - necessarily safe, and requires more detailed examination of the subprogram - bodies involved. In particular, a call to @code{F2} requires that @code{F1} - be already elaborated. - @end table - - @noindent - It is hard to generalize on which of these four approaches should be - taken. Obviously if it is possible to fix the program so that the default - treatment works, this is preferable, but this may not always be practical. - It is certainly simple enough to use - @option{-gnatE} - but the danger in this case is that, even if the GNAT binder - finds a correct elaboration order, it may not always do so, - and certainly a binder from another Ada compiler might not. A - combination of testing and analysis (for which the warnings generated - with the - @option{-gnatwl} - switch can be useful) must be used to ensure that the program is free - of errors. One switch that is useful in this testing is the - @code{-p (pessimistic elaboration order)} - switch for - @code{gnatbind}. - Normally the binder tries to find an order that has the best chance of - of avoiding elaboration problems. With this switch, the binder - plays a devil's advocate role, and tries to choose the order that - has the best chance of failing. If your program works even with this - switch, then it has a better chance of being error free, but this is still - not a guarantee. - - For an example of this approach in action, consider the C-tests (executable - tests) from the ACVC suite. If these are compiled and run with the default - treatment, then all but one of them succeed without generating any error - diagnostics from the binder. However, there is one test that fails, and - this is not surprising, because the whole point of this test is to ensure - that the compiler can handle cases where it is impossible to determine - a correct order statically, and it checks that an exception is indeed - raised at run time. - - This one test must be compiled and run using the - @option{-gnatE} - switch, and then it passes. Alternatively, the entire suite can - be run using this switch. It is never wrong to run with the dynamic - elaboration switch if your code is correct, and we assume that the - C-tests are indeed correct (it is less efficient, but efficiency is - not a factor in running the ACVC tests.) - - @node Elaboration for Access-to-Subprogram Values - @section Elaboration for Access-to-Subprogram Values - @cindex Access-to-subprogram - - @noindent - The introduction of access-to-subprogram types in Ada 95 complicates - the handling of elaboration. The trouble is that it becomes - impossible to tell at compile time which procedure - is being called. This means that it is not possible for the binder - to analyze the elaboration requirements in this case. - - If at the point at which the access value is created - (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}), - the body of the subprogram is - known to have been elaborated, then the access value is safe, and its use - does not require a check. This may be achieved by appropriate arrangement - of the order of declarations if the subprogram is in the current unit, - or, if the subprogram is in another unit, by using pragma - @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body} - on the referenced unit. - - If the referenced body is not known to have been elaborated at the point - the access value is created, then any use of the access value must do a - dynamic check, and this dynamic check will fail and raise a - @code{Program_Error} exception if the body has not been elaborated yet. - GNAT will generate the necessary checks, and in addition, if the - @option{-gnatwl} - switch is set, will generate warnings that such checks are required. - - The use of dynamic dispatching for tagged types similarly generates - a requirement for dynamic checks, and premature calls to any primitive - operation of a tagged type before the body of the operation has been elaborated, - will result in the raising of @code{Program_Error}. - - @node Summary of Procedures for Elaboration Control - @section Summary of Procedures for Elaboration Control - @cindex Elaboration control - - @noindent - First, compile your program with the default options, using none of - the special elaboration control switches. If the binder successfully - binds your program, then you can be confident that, apart from issues - raised by the use of access-to-subprogram types and dynamic dispatching, - the program is free of elaboration errors. If it is important that the - program be portable, then use the - @option{-gnatwl} - switch to generate warnings about missing @code{Elaborate_All} - pragmas, and supply the missing pragmas. - - If the program fails to bind using the default static elaboration - handling, then you can fix the program to eliminate the binder - message, or recompile the entire program with the - @option{-gnatE} switch to generate dynamic elaboration checks, - and, if you are sure there really are no elaboration problems, - use a global pragma @code{Suppress (Elaboration_Checks)}. - - @node Other Elaboration Order Considerations - @section Other Elaboration Order Considerations - @noindent - This section has been entirely concerned with the issue of finding a valid - elaboration order, as defined by the Ada Reference Manual. In a case - where several elaboration orders are valid, the task is to find one - of the possible valid elaboration orders (and the static model in GNAT - will ensure that this is achieved). - - The purpose of the elaboration rules in the Ada Reference Manual is to - make sure that no entity is accessed before it has been elaborated. For - a subprogram, this means that the spec and body must have been elaborated - before the subprogram is called. For an object, this means that the object - must have been elaborated before its value is read or written. A violation - of either of these two requirements is an access before elaboration order, - and this section has been all about avoiding such errors. - - In the case where more than one order of elaboration is possible, in the - sense that access before elaboration errors are avoided, then any one of - the orders is "correct" in the sense that it meets the requirements of - the Ada Reference Manual, and no such error occurs. - - However, it may be the case for a given program, that there are - constraints on the order of elaboration that come not from consideration - of avoiding elaboration errors, but rather from extra-lingual logic - requirements. Consider this example: - - @smallexample - with Init_Constants; - package Constants is - X : Integer := 0; - Y : Integer := 0; - end Constants; - - package Init_Constants is - procedure Calc; - end Init_Constants; - - with Constants; - package body Init_Constants is - procedure Calc is begin null; end; - begin - Constants.X := 3; - Constants.Y := 4; - end Init_Constants; - - with Constants; - package Calc is - Z : Integer := Constants.X + Constants.Y; - end Calc; - - with Calc; - with Text_IO; use Text_IO; - procedure Main is - begin - Put_Line (Calc.Z'Img); - end Main; - @end smallexample - - @noindent - In this example, there is more than one valid order of elaboration. For - example both the following are correct orders: - - @smallexample - Init_Constants spec - Constants spec - Calc spec - Main body - Init_Constants body - - and - - Init_Constants spec - Init_Constants body - Constants spec - Calc spec - Main body - @end smallexample - - @noindent - There is no language rule to prefer one or the other, both are correct - from an order of elaboration point of view. But the programmatic effects - of the two orders are very different. In the first, the elaboration routine - of @code{Calc} initializes @code{Z} to zero, and then the main program - runs with this value of zero. But in the second order, the elaboration - routine of @code{Calc} runs after the body of Init_Constants has set - @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} - runs. - - One could perhaps by applying pretty clever non-artificial intelligence - to the situation guess that it is more likely that the second order of - elaboration is the one desired, but there is no formal linguistic reason - to prefer one over the other. In fact in this particular case, GNAT will - prefer the second order, because of the rule that bodies are elaborated - as soon as possible, but it's just luck that this is what was wanted - (if indeed the second order was preferred). - - If the program cares about the order of elaboration routines in a case like - this, it is important to specify the order required. In this particular - case, that could have been achieved by adding to the spec of Calc: - - @smallexample - pragma Elaborate_All (Constants); - @end smallexample - - @noindent - which requires that the body (if any) and spec of @code{Constants}, - as well as the body and spec of any unit @code{with}'ed by - @code{Constants} be elaborated before @code{Calc} is elaborated. - - Clearly no automatic method can always guess which alternative you require, - and if you are working with legacy code that had constraints of this kind - which were not properly specified by adding @code{Elaborate} or - @code{Elaborate_All} pragmas, then indeed it is possible that two different - compilers can choose different orders. - - The @code{gnatbind} - @code{-p} switch may be useful in smoking - out problems. This switch causes bodies to be elaborated as late as possible - instead of as early as possible. In the example above, it would have forced - the choice of the first elaboration order. If you get different results - when using this switch, and particularly if one set of results is right, - and one is wrong as far as you are concerned, it shows that you have some - missing @code{Elaborate} pragmas. For the example above, we have the - following output: - - @smallexample - gnatmake -f -q main - main - 7 - gnatmake -f -q main -bargs -p - main - 0 - @end smallexample - - @noindent - It is of course quite unlikely that both these results are correct, so - it is up to you in a case like this to investigate the source of the - difference, by looking at the two elaboration orders that are chosen, - and figuring out which is correct, and then adding the necessary - @code{Elaborate_All} pragmas to ensure the desired order. - - @node The Cross-Referencing Tools gnatxref and gnatfind - @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind} - @findex gnatxref - @findex gnatfind - - @noindent - The compiler generates cross-referencing information (unless - you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files. - This information indicates where in the source each entity is declared and - referenced. Note that entities in package Standard are not included, but - entities in all other predefined units are included in the output. - - Before using any of these two tools, you need to compile successfully your - application, so that GNAT gets a chance to generate the cross-referencing - information. - - The two tools @code{gnatxref} and @code{gnatfind} take advantage of this - information to provide the user with the capability to easily locate the - declaration and references to an entity. These tools are quite similar, - the difference being that @code{gnatfind} is intended for locating - definitions and/or references to a specified entity or entities, whereas - @code{gnatxref} is oriented to generating a full report of all - cross-references. - - To use these tools, you must not compile your application using the - @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The - GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing - information will not be generated. - - @menu - * gnatxref Switches:: - * gnatfind Switches:: - * Project Files for gnatxref and gnatfind:: - * Regular Expressions in gnatfind and gnatxref:: - * Examples of gnatxref Usage:: - * Examples of gnatfind Usage:: - @end menu - - @node gnatxref Switches - @section @code{gnatxref} Switches - - @noindent - The command lines for @code{gnatxref} is: - @smallexample - $ gnatxref [switches] sourcefile1 [sourcefile2 ...] - @end smallexample - - @noindent - where - - @table @code - @item sourcefile1, sourcefile2 - identifies the source files for which a report is to be generated. The - 'with'ed units will be processed too. You must provide at least one file. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - @end table - - @noindent - The switches can be : - @table @code - @item -a - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatxref}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set @code{gnatxref} will output the parent type - reference for each matching derived types. - - @item -f - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item -g - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file to use @xref{Project Files}. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{-aI} - and @samp{-aO}. - @item -u - Output only unused symbols. This may be really useful if you give your - main compilation unit on the command line, as @code{gnatxref} will then - display every unused entity and 'with'ed package. - - @item -v - Instead of producing the default output, @code{gnatxref} will generate a - @file{tags} file that can be used by vi. For examples how to use this - feature, see @xref{Examples of gnatxref Usage}. The tags file is output - to the standard output, thus you will have to redirect it to a file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref -ag} instead of - @samp{gnatxref -a -g}. - - @node gnatfind Switches - @section @code{gnatfind} Switches - - @noindent - The command line for @code{gnatfind} is: - - @smallexample - $ gnatfind [switches] pattern[:sourcefile[:line[:column]]] - [file1 file2 ...] - @end smallexample - - @noindent - where - - @table @code - @item pattern - An entity will be output only if it matches the regular expression found - in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}. - - Omitting the pattern is equivalent to specifying @samp{*}, which - will match any entity. Note that if you do not provide a pattern, you - have to provide both a sourcefile and a line. - - Entity names are given in Latin-1, with uppercase/lowercase equivalence - for matching purposes. At the current time there is no support for - 8-bit codes other than Latin-1, or for wide characters in identifiers. - - @item sourcefile - @code{gnatfind} will look for references, bodies or declarations - of symbols referenced in @file{sourcefile}, at line @samp{line} - and column @samp{column}. See @pxref{Examples of gnatfind Usage} - for syntax examples. - - @item line - is a decimal integer identifying the line number containing - the reference to the entity (or entities) to be located. - - @item column - is a decimal integer identifying the exact location on the - line of the first character of the identifier for the - entity reference. Columns are numbered from 1. - - @item file1 file2 ... - The search will be restricted to these files. If none are given, then - the search will be done for every library file in the search path. - These file must appear only after the pattern or sourcefile. - - These file names are considered to be regular expressions, so for instance - specifying 'source*.adb' is the same as giving every file in the current - directory whose name starts with 'source' and whose extension is 'adb'. - - Not that if you specify at least one file in this part, @code{gnatfind} may - sometimes not be able to find the body of the subprograms... - - @end table - - At least one of 'sourcefile' or 'pattern' has to be present on - the command line. - - The following switches are available: - @table @code - - @item -a - If this switch is present, @code{gnatfind} and @code{gnatxref} will parse - the read-only files found in the library search path. Otherwise, these files - will be ignored. This option can be used to protect Gnat sources or your own - libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} - much faster, and their output much smaller. - - @item -aIDIR - When looking for source files also look in directory DIR. The order in which - source file search is undertaken is the same as for @file{gnatmake}. - - @item -aODIR - When searching for library and object files, look in directory - DIR. The order in which library files are searched is the same as for - @file{gnatmake}. - - @item -nostdinc - Do not look for sources in the system default directory. - - @item -nostdlib - Do not look for library files in the system default directory. - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatfind}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -d - If this switch is set, then @code{gnatfind} will output the parent type - reference for each matching derived types. - - @item -e - By default, @code{gnatfind} accept the simple regular expression set for - @samp{pattern}. If this switch is set, then the pattern will be - considered as full Unix-style regular expression. - - @item -f - If this switch is set, the output file names will be preceded by their - directory (if the file was found in the search path). If this switch is - not set, the directory will not be printed. - - @item -g - If this switch is set, information is output only for library-level - entities, ignoring local entities. The use of this switch may accelerate - @code{gnatfind} and @code{gnatxref}. - - @item -IDIR - Equivalent to @samp{-aODIR -aIDIR}. - - @item -pFILE - Specify a project file (@pxref{Project Files}) to use. - By default, @code{gnatxref} and @code{gnatfind} will try to locate a - project file in the current directory. - - If a project file is either specified or found by the tools, then the content - of the source directory and object directory lines are added as if they - had been specified respectively by @samp{-aI} and - @samp{-aO}. - - @item -r - By default, @code{gnatfind} will output only the information about the - declaration, body or type completion of the entities. If this switch is - set, the @code{gnatfind} will locate every reference to the entities in - the files specified on the command line (or in every file in the search - path if no file is given on the command line). - - @item -s - If this switch is set, then @code{gnatfind} will output the content - of the Ada source file lines were the entity was found. - - @item -t - If this switch is set, then @code{gnatfind} will output the type hierarchy for - the specified type. It act like -d option but recursively from parent - type to parent type. When this switch is set it is not possible to - specify more than one file. - - @end table - - All these switches may be in any order on the command line, and may even - appear after the file names. They need not be separated by spaces, thus - you can say @samp{gnatxref -ag} instead of - @samp{gnatxref -a -g}. - - As stated previously, gnatfind will search in every directory in the - search path. You can force it to look only in the current directory if - you specify @code{*} at the end of the command line. - - - @node Project Files for gnatxref and gnatfind - @section Project Files for @command{gnatxref} and @command{gnatfind} - - @noindent - Project files allow a programmer to specify how to compile its - application, where to find sources,... These files are used primarily by - the Glide Ada mode, but they can also be used by the two tools - @code{gnatxref} and @code{gnatfind}. - - A project file name must end with @file{.adp}. If a single one is - present in the current directory, then @code{gnatxref} and @code{gnatfind} will - extract the information from it. If multiple project files are found, none of - them is read, and you have to use the @samp{-p} switch to specify the one - you want to use. - - The following lines can be included, even though most of them have default - values which can be used in most cases. - The lines can be entered in any order in the file. - Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of - each line. If you have multiple instances, only the last one is taken into - account. - - @table @code - @item src_dir=DIR [default: "./"] - specifies a directory where to look for source files. Multiple src_dir lines - can be specified and they will be searched in the order they - are specified. - - @item obj_dir=DIR [default: "./"] - specifies a directory where to look for object and library files. Multiple - obj_dir lines can be specified and they will be searched in the order they - are specified - - @item comp_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{comp_opt@}} notation. This is intended to store the default - switches given to @file{gnatmake} and @file{gcc}. - - @item bind_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{bind_opt@}} notation. This is intended to store the default - switches given to @file{gnatbind}. - - @item link_opt=SWITCHES [default: ""] - creates a variable which can be referred to subsequently by using - the @samp{$@{link_opt@}} notation. This is intended to store the default - switches given to @file{gnatlink}. - - @item main=EXECUTABLE [default: ""] - specifies the name of the executable for the application. This variable can - be referred to in the following lines by using the @samp{$@{main@}} notation. - - @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"] - specifies the command used to compile a single file in the application. - - @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"] - specifies the command used to recompile the whole application. - - @item run_cmd=COMMAND [default: "$@{main@}"] - specifies the command used to run the application. - - @item debug_cmd=COMMAND [default: "gdb $@{main@}"] - specifies the command used to debug the application - - @end table - - @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir} - and @samp{obj_dir} lines, and ignore the others. - - @node Regular Expressions in gnatfind and gnatxref - @section Regular Expressions in @code{gnatfind} and @code{gnatxref} - - @noindent - As specified in the section about @code{gnatfind}, the pattern can be a - regular expression. Actually, there are to set of regular expressions - which are recognized by the program : - - @table @code - @item globbing patterns - These are the most usual regular expression. They are the same that you - generally used in a Unix shell command line, or in a DOS session. - - Here is a more formal grammar : - @smallexample - @group - @iftex - @leftskip=.5cm - @end iftex - regexp ::= term - term ::= elmt -- matches elmt - term ::= elmt elmt -- concatenation (elmt then elmt) - term ::= * -- any string of 0 or more characters - term ::= ? -- matches any character - term ::= [char @{char@}] -- matches any character listed - term ::= [char - char] -- matches any character in range - @end group - @end smallexample - - @item full regular expression - The second set of regular expressions is much more powerful. This is the - type of regular expressions recognized by utilities such a @file{grep}. - - The following is the form of a regular expression, expressed in Ada - reference manual style BNF is as follows - - @smallexample - @iftex - @leftskip=.5cm - @end iftex - @group - regexp ::= term @{| term@} -- alternation (term or term ...) - - term ::= item @{item@} -- concatenation (item then item) - - item ::= elmt -- match elmt - item ::= elmt * -- zero or more elmt's - item ::= elmt + -- one or more elmt's - item ::= elmt ? -- matches elmt or nothing - @end group - @group - elmt ::= nschar -- matches given character - elmt ::= [nschar @{nschar@}] -- matches any character listed - elmt ::= [^ nschar @{nschar@}] -- matches any character not listed - elmt ::= [char - char] -- matches chars in given range - elmt ::= \ char -- matches given character - elmt ::= . -- matches any single character - elmt ::= ( regexp ) -- parens used for grouping - - char ::= any character, including special characters - nschar ::= any character except ()[].*+?^ - @end group - @end smallexample - - Following are a few examples : - - @table @samp - @item abcde|fghi - will match any of the two strings 'abcde' and 'fghi'. - - @item abc*d - will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on - - @item [a-z]+ - will match any string which has only lowercase characters in it (and at - least one character - - @end table - @end table - - @node Examples of gnatxref Usage - @section Examples of @code{gnatxref} Usage - - @subsection General Usage - - @noindent - For the following examples, we will consider the following units : - - @smallexample - @group - @cartouche - main.ads: - 1: @b{with} Bar; - 2: @b{package} Main @b{is} - 3: @b{procedure} Foo (B : @b{in} Integer); - 4: C : Integer; - 5: @b{private} - 6: D : Integer; - 7: @b{end} Main; - - main.adb: - 1: @b{package body} Main @b{is} - 2: @b{procedure} Foo (B : @b{in} Integer) @b{is} - 3: @b{begin} - 4: C := B; - 5: D := B; - 6: Bar.Print (B); - 7: Bar.Print (C); - 8: @b{end} Foo; - 9: @b{end} Main; - - bar.ads: - 1: @b{package} Bar @b{is} - 2: @b{procedure} Print (B : Integer); - 3: @b{end} bar; - @end cartouche - @end group - @end smallexample - - @table @code - - @noindent - The first thing to do is to recompile your application (for instance, in - that case just by doing a @samp{gnatmake main}, so that GNAT generates - the cross-referencing information. - You can then issue any of the following commands: - - @item gnatxref main.adb - @code{gnatxref} generates cross-reference information for main.adb - and every unit 'with'ed by main.adb. - - The output would be: - @smallexample - @iftex - @leftskip=0cm - @end iftex - B Type: Integer - Decl: bar.ads 2:22 - B Type: Integer - Decl: main.ads 3:20 - Body: main.adb 2:20 - Ref: main.adb 4:13 5:13 6:19 - Bar Type: Unit - Decl: bar.ads 1:9 - Ref: main.adb 6:8 7:8 - main.ads 1:6 - C Type: Integer - Decl: main.ads 4:5 - Modi: main.adb 4:8 - Ref: main.adb 7:19 - D Type: Integer - Decl: main.ads 6:5 - Modi: main.adb 5:8 - Foo Type: Unit - Decl: main.ads 3:15 - Body: main.adb 2:15 - Main Type: Unit - Decl: main.ads 2:9 - Body: main.adb 1:14 - Print Type: Unit - Decl: bar.ads 2:15 - Ref: main.adb 6:12 7:12 - @end smallexample - - @noindent - that is the entity @code{Main} is declared in main.ads, line 2, column 9, - its body is in main.adb, line 1, column 14 and is not referenced any where. - - The entity @code{Print} is declared in bar.ads, line 2, column 15 and it - it referenced in main.adb, line 6 column 12 and line 7 column 12. - - @item gnatxref package1.adb package2.ads - @code{gnatxref} will generates cross-reference information for - package1.adb, package2.ads and any other package 'with'ed by any - of these. - - @end table - - @subsection Using gnatxref with vi - - @code{gnatxref} can generate a tags file output, which can be used - directly from @file{vi}. Note that the standard version of @file{vi} - will not work properly with overloaded symbols. Consider using another - free implementation of @file{vi}, such as @file{vim}. - - @smallexample - $ gnatxref -v gnatfind.adb > tags - @end smallexample - - @noindent - will generate the tags file for @code{gnatfind} itself (if the sources - are in the search path!). - - From @file{vi}, you can then use the command @samp{:tag @i{entity}} - (replacing @i{entity} by whatever you are looking for), and vi will - display a new file with the corresponding declaration of entity. - - @node Examples of gnatfind Usage - @section Examples of @code{gnatfind} Usage - - @table @code - - @item gnatfind -f xyz:main.adb - Find declarations for all entities xyz referenced at least once in - main.adb. The references are search in every library file in the search - path. - - The directories will be printed as well (as the @samp{-f} - switch is set) - - The output will look like: - @smallexample - directory/main.ads:106:14: xyz <= declaration - directory/main.adb:24:10: xyz <= body - directory/foo.ads:45:23: xyz <= declaration - @end smallexample - - @noindent - that is to say, one of the entities xyz found in main.adb is declared at - line 12 of main.ads (and its body is in main.adb), and another one is - declared at line 45 of foo.ads - - @item gnatfind -fs xyz:main.adb - This is the same command as the previous one, instead @code{gnatfind} will - display the content of the Ada source file lines. - - The output will look like: - - @smallexample - directory/main.ads:106:14: xyz <= declaration - procedure xyz; - directory/main.adb:24:10: xyz <= body - procedure xyz is - directory/foo.ads:45:23: xyz <= declaration - xyz : Integer; - @end smallexample - - @noindent - This can make it easier to find exactly the location your are looking - for. - - @item gnatfind -r "*x*":main.ads:123 foo.adb - Find references to all entities containing an x that are - referenced on line 123 of main.ads. - The references will be searched only in main.adb and foo.adb. - - @item gnatfind main.ads:123 - Find declarations and bodies for all entities that are referenced on - line 123 of main.ads. - - This is the same as @code{gnatfind "*":main.adb:123}. - - @item gnatfind mydir/main.adb:123:45 - Find the declaration for the entity referenced at column 45 in - line 123 of file main.adb in directory mydir. Note that it - is usual to omit the identifier name when the column is given, - since the column position identifies a unique reference. - - The column has to be the beginning of the identifier, and should not - point to any character in the middle of the identifier. - - @end table - - @node File Name Krunching Using gnatkr - @chapter File Name Krunching Using @code{gnatkr} - @findex gnatkr - - @noindent - This chapter discusses the method used by the compiler to shorten - the default file names chosen for Ada units so that they do not - exceed the maximum length permitted. It also describes the - @code{gnatkr} utility that can be used to determine the result of - applying this shortening. - @menu - * About gnatkr:: - * Using gnatkr:: - * Krunching Method:: - * Examples of gnatkr Usage:: - @end menu - - @node About gnatkr - @section About @code{gnatkr} - - @noindent - The default file naming rule in GNAT - is that the file name must be derived from - the unit name. The exact default rule is as follows: - @itemize @bullet - @item - Take the unit name and replace all dots by hyphens. - @item - If such a replacement occurs in the - second character position of a name, and the first character is - a, g, s, or i then replace the dot by the character - ~ (tilde) - instead of a minus. - @end itemize - The reason for this exception is to avoid clashes - with the standard names for children of System, Ada, Interfaces, - and GNAT, which use the prefixes s- a- i- and g- - respectively. - - The @code{-gnatk@var{nn}} - switch of the compiler activates a "krunching" - circuit that limits file names to nn characters (where nn is a decimal - integer). For example, using OpenVMS, - where the maximum file name length is - 39, the value of nn is usually set to 39, but if you want to generate - a set of files that would be usable if ported to a system with some - different maximum file length, then a different value can be specified. - The default value of 39 for OpenVMS need not be specified. - - The @code{gnatkr} utility can be used to determine the krunched name for - a given file, when krunched to a specified maximum length. - - @node Using gnatkr - @section Using @code{gnatkr} - - @noindent - The @code{gnatkr} command has the form - - @smallexample - $ gnatkr @var{name} [@var{length}] - @end smallexample - - - @noindent - @var{name} can be an Ada name with dots or the GNAT name of the unit, - where the dots representing child units or subunit are replaced by - hyphens. The only confusion arises if a name ends in @code{.ads} or - @code{.adb}. @code{gnatkr} takes this to be an extension if there are - no other dots in the name and the whole name is in lowercase. - - @var{length} represents the length of the krunched name. The default - when no argument is given is 8 characters. A length of zero stands for - unlimited, in other words do not chop except for system files which are - always 8. - - @noindent - The output is the krunched name. The output has an extension only if the - original argument was a file name with an extension. - - @node Krunching Method - @section Krunching Method - - @noindent - The initial file name is determined by the name of the unit that the file - contains. The name is formed by taking the full expanded name of the - unit and replacing the separating dots with hyphens and - using lowercase - for all letters, except that a hyphen in the second character position is - replaced by a tilde if the first character is - a, i, g, or s. - The extension is @code{.ads} for a - specification and @code{.adb} for a body. - Krunching does not affect the extension, but the file name is shortened to - the specified length by following these rules: - - @itemize @bullet - @item - The name is divided into segments separated by hyphens, tildes or - underscores and all hyphens, tildes, and underscores are - eliminated. If this leaves the name short enough, we are done. - - @item - If the name is too long, the longest segment is located (left-most if there are two - of equal length), and shortened by dropping its last character. This is - repeated until the name is short enough. - - As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb} - to fit the name into 8 characters as required by some operating systems. - - @smallexample - our-strings-wide_fixed 22 - our strings wide fixed 19 - our string wide fixed 18 - our strin wide fixed 17 - our stri wide fixed 16 - our stri wide fixe 15 - our str wide fixe 14 - our str wid fixe 13 - our str wid fix 12 - ou str wid fix 11 - ou st wid fix 10 - ou st wi fix 9 - ou st wi fi 8 - Final file name: oustwifi.adb - @end smallexample - - @item - The file names for all predefined units are always krunched to eight - characters. The krunching of these predefined units uses the following - special prefix replacements: - - @table @file - @item ada- - replaced by @file{a-} - - @item gnat- - replaced by @file{g-} - - @item interfaces- - replaced by @file{i-} - - @item system- - replaced by @file{s-} - @end table - - These system files have a hyphen in the second character position. That - is why normal user files replace such a character with a - tilde, to - avoid confusion with system file names. - - As an example of this special rule, consider - @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows: - - @smallexample - ada-strings-wide_fixed 22 - a- strings wide fixed 18 - a- string wide fixed 17 - a- strin wide fixed 16 - a- stri wide fixed 15 - a- stri wide fixe 14 - a- str wide fixe 13 - a- str wid fixe 12 - a- str wid fix 11 - a- st wid fix 10 - a- st wi fix 9 - a- st wi fi 8 - Final file name: a-stwifi.adb - @end smallexample - @end itemize - - Of course no file shortening algorithm can guarantee uniqueness over all - possible unit names, and if file name krunching is used then it is your - responsibility to ensure that no name clashes occur. The utility - program @code{gnatkr} is supplied for conveniently determining the - krunched name of a file. - - @node Examples of gnatkr Usage - @section Examples of @code{gnatkr} Usage - - @smallexample - @iftex - @leftskip=0cm - @end iftex - $ gnatkr very_long_unit_name.ads --> velounna.ads - $ gnatkr grandparent-parent-child.ads --> grparchi.ads - $ gnatkr Grandparent.Parent.Child --> grparchi - $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads - $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads - @end smallexample - - @node Preprocessing Using gnatprep - @chapter Preprocessing Using @code{gnatprep} - @findex gnatprep - - @noindent - The @code{gnatprep} utility provides - a simple preprocessing capability for Ada programs. - It is designed for use with GNAT, but is not dependent on any special - features of GNAT. - - @menu - * Using gnatprep:: - * Switches for gnatprep:: - * Form of Definitions File:: - * Form of Input Text for gnatprep:: - @end menu - - @node Using gnatprep - @section Using @code{gnatprep} - - @noindent - To call @code{gnatprep} use - - @smallexample - $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile] - @end smallexample - - @noindent - where - @table @code - @item infile - is the full name of the input file, which is an Ada source - file containing preprocessor directives. - - @item outfile - is the full name of the output file, which is an Ada source - in standard Ada form. When used with GNAT, this file name will - normally have an ads or adb suffix. - - @item deffile - is the full name of a text file containing definitions of - symbols to be referenced by the preprocessor. This argument is - optional, and can be replaced by the use of the @code{-D} switch. - - @item switches - is an optional sequence of switches as described in the next section. - @end table - - @node Switches for gnatprep - @section Switches for @code{gnatprep} - - @table @code - - @item -b - Causes both preprocessor lines and the lines deleted by - preprocessing to be replaced by blank lines in the output source file, - preserving line numbers in the output file. - - @item -c - Causes both preprocessor lines and the lines deleted - by preprocessing to be retained in the output source as comments marked - with the special string "--! ". This option will result in line numbers - being preserved in the output file. - - @item -Dsymbol=value - Defines a new symbol, associated with value. If no value is given on the - command line, then symbol is considered to be @code{True}. This switch - can be used in place of a definition file. - - - @item -r - Causes a @code{Source_Reference} pragma to be generated that - references the original input file, so that error messages will use - the file name of this original file. The use of this switch implies - that preprocessor lines are not to be removed from the file, so its - use will force @code{-b} mode if - @code{-c} - has not been specified explicitly. - - Note that if the file to be preprocessed contains multiple units, then - it will be necessary to @code{gnatchop} the output file from - @code{gnatprep}. If a @code{Source_Reference} pragma is present - in the preprocessed file, it will be respected by - @code{gnatchop -r} - so that the final chopped files will correctly refer to the original - input source file for @code{gnatprep}. - - @item -s - Causes a sorted list of symbol names and values to be - listed on the standard output file. - - @item -u - Causes undefined symbols to be treated as having the value FALSE in the context - of a preprocessor test. In the absence of this option, an undefined symbol in - a @code{#if} or @code{#elsif} test will be treated as an error. - - @end table - - @noindent - Note: if neither @code{-b} nor @code{-c} is present, - then preprocessor lines and - deleted lines are completely removed from the output, unless -r is - specified, in which case -b is assumed. - - @node Form of Definitions File - @section Form of Definitions File - - @noindent - The definitions file contains lines of the form - - @smallexample - symbol := value - @end smallexample - - @noindent - where symbol is an identifier, following normal Ada (case-insensitive) - rules for its syntax, and value is one of the following: - - @itemize @bullet - @item - Empty, corresponding to a null substitution - @item - A string literal using normal Ada syntax - @item - Any sequence of characters from the set - (letters, digits, period, underline). - @end itemize - - @noindent - Comment lines may also appear in the definitions file, starting with - the usual @code{--}, - and comments may be added to the definitions lines. - - @node Form of Input Text for gnatprep - @section Form of Input Text for @code{gnatprep} - - @noindent - The input text may contain preprocessor conditional inclusion lines, - as well as general symbol substitution sequences. - - The preprocessor conditional inclusion commands have the form - - @smallexample - @group - @cartouche - #if @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - #elsif @i{expression} [then] - lines - ... - #else - lines - #end if; - @end cartouche - @end group - @end smallexample - - @noindent - In this example, @i{expression} is defined by the following grammar: - @smallexample - @i{expression} ::= - @i{expression} ::= = "" - @i{expression} ::= = - @i{expression} ::= 'Defined - @i{expression} ::= not @i{expression} - @i{expression} ::= @i{expression} and @i{expression} - @i{expression} ::= @i{expression} or @i{expression} - @i{expression} ::= @i{expression} and then @i{expression} - @i{expression} ::= @i{expression} or else @i{expression} - @i{expression} ::= ( @i{expression} ) - @end smallexample - - @noindent - For the first test (@i{expression} ::= ) the symbol must have - either the value true or false, that is to say the right-hand of the - symbol definition must be one of the (case-insensitive) literals - @code{True} or @code{False}. If the value is true, then the - corresponding lines are included, and if the value is false, they are - excluded. - - The test (@i{expression} ::= @code{'Defined}) is true only if - the symbol has been defined in the definition file or by a @code{-D} - switch on the command line. Otherwise, the test is false. - - The equality tests are case insensitive, as are all the preprocessor lines. - - If the symbol referenced is not defined in the symbol definitions file, - then the effect depends on whether or not switch @code{-u} - is specified. If so, then the symbol is treated as if it had the value - false and the test fails. If this switch is not specified, then - it is an error to reference an undefined symbol. It is also an error to - reference a symbol that is defined with a value other than @code{True} - or @code{False}. - - The use of the @code{not} operator inverts the sense of this logical test, so - that the lines are included only if the symbol is not defined. - The @code{then} keyword is optional as shown - - The @code{#} must be the first non-blank character on a line, but - otherwise the format is free form. Spaces or tabs may appear between - the @code{#} and the keyword. The keywords and the symbols are case - insensitive as in normal Ada code. Comments may be used on a - preprocessor line, but other than that, no other tokens may appear on a - preprocessor line. Any number of @code{elsif} clauses can be present, - including none at all. The @code{else} is optional, as in Ada. - - The @code{#} marking the start of a preprocessor line must be the first - non-blank character on the line, i.e. it must be preceded only by - spaces or horizontal tabs. - - Symbol substitution outside of preprocessor lines is obtained by using - the sequence - - @smallexample - $symbol - @end smallexample - - @noindent - anywhere within a source line, except in a comment or within a - string literal. The identifier - following the @code{$} must match one of the symbols defined in the symbol - definition file, and the result is to substitute the value of the - symbol in place of @code{$symbol} in the output file. - - Note that although the substitution of strings within a string literal - is not possible, it is possible to have a symbol whose defined value is - a string literal. So instead of setting XYZ to @code{hello} and writing: - - @smallexample - Header : String := "$XYZ"; - @end smallexample - - @noindent - you should set XYZ to @code{"hello"} and write: - - @smallexample - Header : String := $XYZ; - @end smallexample - - @noindent - and then the substitution will occur as desired. - - - @node The GNAT Library Browser gnatls - @chapter The GNAT Library Browser @code{gnatls} - @findex gnatls - @cindex Library browser - - @noindent - @code{gnatls} is a tool that outputs information about compiled - units. It gives the relationship between objects, unit names and source - files. It can also be used to check the source dependencies of a unit - as well as various characteristics. - - @menu - * Running gnatls:: - * Switches for gnatls:: - * Examples of gnatls Usage:: - @end menu - - @node Running gnatls - @section Running @code{gnatls} - - @noindent - The @code{gnatls} command has the form - - @smallexample - $ gnatls switches @var{object_or_ali_file} - @end smallexample - - @noindent - The main argument is the list of object or @file{ali} files - (@pxref{The Ada Library Information Files}) - for which information is requested. - - In normal mode, without additional option, @code{gnatls} produces a - four-column listing. Each line represents information for a specific - object. The first column gives the full path of the object, the second - column gives the name of the principal unit in this object, the third - column gives the status of the source and the fourth column gives the - full path of the source representing this unit. - Here is a simple example of use: - - @smallexample - $ gnatls *.o - ./demo1.o demo1 DIF demo1.adb - ./demo2.o demo2 OK demo2.adb - ./hello.o h1 OK hello.adb - ./instr-child.o instr.child MOK instr-child.adb - ./instr.o instr OK instr.adb - ./tef.o tef DIF tef.adb - ./text_io_example.o text_io_example OK text_io_example.adb - ./tgef.o tgef DIF tgef.adb - @end smallexample - - @noindent - The first line can be interpreted as follows: the main unit which is - contained in - object file @file{demo1.o} is demo1, whose main source is in - @file{demo1.adb}. Furthermore, the version of the source used for the - compilation of demo1 has been modified (DIF). Each source file has a status - qualifier which can be: - - @table @code - @item OK (unchanged) - The version of the source file used for the compilation of the - specified unit corresponds exactly to the actual source file. - - @item MOK (slightly modified) - The version of the source file used for the compilation of the - specified unit differs from the actual source file but not enough to - require recompilation. If you use gnatmake with the qualifier - @code{-m (minimal recompilation)}, a file marked - MOK will not be recompiled. - - @item DIF (modified) - No version of the source found on the path corresponds to the source - used to build this object. - - @item ??? (file not found) - No source file was found for this unit. - - @item HID (hidden, unchanged version not first on PATH) - The version of the source that corresponds exactly to the source used - for compilation has been found on the path but it is hidden by another - version of the same source that has been modified. - - @end table - - @node Switches for gnatls - @section Switches for @code{gnatls} - - @noindent - @code{gnatls} recognizes the following switches: - - @table @code - @item -a - @cindex @code{-a} (@code{gnatls}) - Consider all units, including those of the predefined Ada library. - Especially useful with @code{-d}. - - @item -d - @cindex @code{-d} (@code{gnatls}) - List sources from which specified units depend on. - - @item -h - @cindex @code{-h} (@code{gnatls}) - Output the list of options. - - @item -o - @cindex @code{-o} (@code{gnatls}) - Only output information about object files. - - @item -s - @cindex @code{-s} (@code{gnatls}) - Only output information about source files. - - @item -u - @cindex @code{-u} (@code{gnatls}) - Only output information about compilation units. - - @item -aO@var{dir} - @itemx -aI@var{dir} - @itemx -I@var{dir} - @itemx -I- - @itemx -nostdinc - Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags - (see @ref{Switches for gnatmake}). - - @item --RTS=@var{rts-path} - @cindex @code{--RTS} (@code{gnatls}) - Specifies the default location of the runtime library. Same meaning as the - equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}). - - @item -v - @cindex @code{-s} (@code{gnatls}) - Verbose mode. Output the complete source and object paths. Do not use - the default column layout but instead use long format giving as much as - information possible on each requested units, including special - characteristics such as: - - @table @code - @item Preelaborable - The unit is preelaborable in the Ada 95 sense. - - @item No_Elab_Code - No elaboration code has been produced by the compiler for this unit. - - @item Pure - The unit is pure in the Ada 95 sense. - - @item Elaborate_Body - The unit contains a pragma Elaborate_Body. - - @item Remote_Types - The unit contains a pragma Remote_Types. - - @item Shared_Passive - The unit contains a pragma Shared_Passive. - - @item Predefined - This unit is part of the predefined environment and cannot be modified - by the user. - - @item Remote_Call_Interface - The unit contains a pragma Remote_Call_Interface. - - @end table - - @end table - - @node Examples of gnatls Usage - @section Example of @code{gnatls} Usage - - @noindent - Example of using the verbose switch. Note how the source and - object paths are affected by the -I switch. - - @smallexample - $ gnatls -v -I.. demo1.o - - GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc. - - Source Search Path: - - ../ - /home/comar/local/adainclude/ - - Object Search Path: - - ../ - /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/ - - ./demo1.o - Unit => - Name => demo1 - Kind => subprogram body - Flags => No_Elab_Code - Source => demo1.adb modified - @end smallexample - - @noindent - The following is an example of use of the dependency list. - Note the use of the -s switch - which gives a straight list of source files. This can be useful for - building specialized scripts. - - @smallexample - $ gnatls -d demo2.o - ./demo2.o demo2 OK demo2.adb - OK gen_list.ads - OK gen_list.adb - OK instr.ads - OK instr-child.ads - - $ gnatls -d -s -a demo1.o - demo1.adb - /home/comar/local/adainclude/ada.ads - /home/comar/local/adainclude/a-finali.ads - /home/comar/local/adainclude/a-filico.ads - /home/comar/local/adainclude/a-stream.ads - /home/comar/local/adainclude/a-tags.ads - gen_list.ads - gen_list.adb - /home/comar/local/adainclude/gnat.ads - /home/comar/local/adainclude/g-io.ads - instr.ads - /home/comar/local/adainclude/system.ads - /home/comar/local/adainclude/s-exctab.ads - /home/comar/local/adainclude/s-finimp.ads - /home/comar/local/adainclude/s-finroo.ads - /home/comar/local/adainclude/s-secsta.ads - /home/comar/local/adainclude/s-stalib.ads - /home/comar/local/adainclude/s-stoele.ads - /home/comar/local/adainclude/s-stratt.ads - /home/comar/local/adainclude/s-tasoli.ads - /home/comar/local/adainclude/s-unstyp.ads - /home/comar/local/adainclude/unchconv.ads - @end smallexample - - - @node GNAT and Libraries - @chapter GNAT and Libraries - @cindex Library, building, installing - - @noindent - This chapter addresses some of the issues related to building and using - a library with GNAT. It also shows how the GNAT run-time library can be - recompiled. - - @menu - * Creating an Ada Library:: - * Installing an Ada Library:: - * Using an Ada Library:: - * Creating an Ada Library to be Used in a Non-Ada Context:: - * Rebuilding the GNAT Run-Time Library:: - @end menu - - @node Creating an Ada Library - @section Creating an Ada Library - - @noindent - In the GNAT environment, a library has two components: - @itemize @bullet - @item - Source files. - @item - Compiled code and Ali files. See @ref{The Ada Library Information Files}. - @end itemize - - @noindent - In order to use other packages @ref{The GNAT Compilation Model} - requires a certain number of sources to be available to the compiler. - The minimal set of - sources required includes the specs of all the packages that make up the - visible part of the library as well as all the sources upon which they - depend. The bodies of all visible generic units must also be provided. - @noindent - Although it is not strictly mandatory, it is recommended that all sources - needed to recompile the library be provided, so that the user can make - full use of inter-unit inlining and source-level debugging. This can also - make the situation easier for users that need to upgrade their compilation - toolchain and thus need to recompile the library from sources. - - @noindent - The compiled code can be provided in different ways. The simplest way is - to provide directly the set of objects produced by the compiler during - the compilation of the library. It is also possible to group the objects - into an archive using whatever commands are provided by the operating - system. Finally, it is also possible to create a shared library (see - option -shared in the GCC manual). - - @noindent - There are various possibilities for compiling the units that make up the - library: for example with a Makefile @ref{Using the GNU make Utility}, - or with a conventional script. - For simple libraries, it is also possible to create a - dummy main program which depends upon all the packages that comprise the - interface of the library. This dummy main program can then be given to - gnatmake, in order to build all the necessary objects. Here is an example - of such a dummy program and the generic commands used to build an - archive or a shared library. - - @smallexample - @iftex - @leftskip=.7cm - @end iftex - @b{with} My_Lib.Service1; - @b{with} My_Lib.Service2; - @b{with} My_Lib.Service3; - @b{procedure} My_Lib_Dummy @b{is} - @b{begin} - @b{null}; - @b{end}; - - # compiling the library - $ gnatmake -c my_lib_dummy.adb - - # we don't need the dummy object itself - $ rm my_lib_dummy.o my_lib_dummy.ali - - # create an archive with the remaining objects - $ ar rc libmy_lib.a *.o - # some systems may require "ranlib" to be run as well - - # or create a shared library - $ gcc -shared -o libmy_lib.so *.o - # some systems may require the code to have been compiled with -fPIC - @end smallexample - - @noindent - When the objects are grouped in an archive or a shared library, the user - needs to specify the desired library at link time, unless a pragma - linker_options has been used in one of the sources: - @smallexample - @b{pragma} Linker_Options ("-lmy_lib"); - @end smallexample - - @node Installing an Ada Library - @section Installing an Ada Library - - @noindent - In the GNAT model, installing a library consists in copying into a specific - location the files that make up this library. It is possible to install - the sources in a different directory from the other files (ALI, objects, - archives) since the source path and the object path can easily be - specified separately. - - @noindent - For general purpose libraries, it is possible for the system - administrator to put those libraries in the default compiler paths. To - achieve this, he must specify their location in the configuration files - "ada_source_path" and "ada_object_path" that must be located in the GNAT - installation tree at the same place as the gcc spec file. The location of - the gcc spec file can be determined as follows: - @smallexample - $ gcc -v - @end smallexample - - @noindent - The configuration files mentioned above have simple format: each line in them - must contain one unique - directory name. Those names are added to the corresponding path - in their order of appearance in the file. The names can be either absolute - or relative, in the latter case, they are relative to where theses files - are located. - - @noindent - "ada_source_path" and "ada_object_path" might actually not be present in a - GNAT installation, in which case, GNAT will look for its run-time library in - the directories "adainclude" for the sources and "adalib" for the - objects and ALI files. When the files exist, the compiler does not - look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file - must contain the location for the GNAT run-time sources (which can simply - be "adainclude"). In the same way, the "ada_object_path" file must contain - the location for the GNAT run-time objects (which can simply - be "adalib"). - - @noindent - You can also specify a new default path to the runtime library at compilation - time with the switch "--RTS=@var{rts-path}". You can easily choose and change - the runtime you want your program to be compiled with. This switch is - recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref. - - @noindent - It is possible to install a library before or after the standard GNAT - library, by reordering the lines in the configuration files. In general, a - library must be installed before the GNAT library if it redefines any part of it. - - @node Using an Ada Library - @section Using an Ada Library - - @noindent - In order to use a Ada library, you need to make sure that this - library is on both your source and object path - @ref{Search Paths and the Run-Time Library (RTL)} - and @ref{Search Paths for gnatbind}. For - instance, you can use the library "mylib" installed in "/dir/my_lib_src" - and "/dir/my_lib_obj" with the following commands: - - @smallexample - $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \ - -largs -lmy_lib - @end smallexample - - @noindent - This can be simplified down to the following: - @smallexample - $ gnatmake my_appl - @end smallexample - when the following conditions are met: - @itemize @bullet - @item - "/dir/my_lib_src" has been added by the user to the environment - variable "ADA_INCLUDE_PATH", or by the administrator to the file - "ada_source_path" - @item - "/dir/my_lib_obj" has been added by the user to the environment - variable "ADA_OBJECTS_PATH", or by the administrator to the file - "ada_object_path" - @item - a pragma linker_options, as mentioned in @ref{Creating an Ada Library} - as been added to the sources. - @end itemize - @noindent - - @node Creating an Ada Library to be Used in a Non-Ada Context - @section Creating an Ada Library to be Used in a Non-Ada Context - - @noindent - The previous sections detailed how to create and install a library that - was usable from an Ada main program. Using this library in a non-Ada - context is not possible, because the elaboration of the library is - automatically done as part of the main program elaboration. - - GNAT also provides the ability to build libraries that can be used both - in an Ada and non-Ada context. This section describes how to build such - a library, and then how to use it from a C program. The method for - interfacing with the library from other languages such as Fortran for - instance remains the same. - - @subsection Creating the Library - - @itemize @bullet - @item Identify the units representing the interface of the library. - - Here is an example of simple library interface: - - @smallexample - package Interface is - - procedure Do_Something; - - procedure Do_Something_Else; - - end Interface; - @end smallexample - - @item Use @code{pragma Export} or @code{pragma Convention} for the - exported entities. - - Our package @code{Interface} is then updated as follow: - @smallexample - package Interface is - - procedure Do_Something; - pragma Export (C, Do_Something, "do_something"); - - procedure Do_Something_Else; - pragma Export (C, Do_Something_Else, "do_something_else"); - - end Interface; - @end smallexample - - @item Compile all the units composing the library. - - @item Bind the library objects. - - This step is performed by invoking gnatbind with the @code{-L} - switch. @code{gnatbind} will then generate the library elaboration - procedure (named @code{init}) and the run-time finalization - procedure (named @code{final}). - - @smallexample - # generate the binder file in Ada - $ gnatbind -Lmylib interface - - # generate the binder file in C - $ gnatbind -C -Lmylib interface - @end smallexample - - @item Compile the files generated by the binder - - @smallexample - $ gcc -c b~interface.adb - @end smallexample - - @item Create the library; - - The procedure is identical to the procedure explained in - @ref{Creating an Ada Library}, - except that @file{b~interface.o} needs to be added to - the list of objects. - - @smallexample - # create an archive file - $ ar cr libmylib.a b~interface.o - - # create a shared library - $ gcc -shared -o libmylib.so b~interface.o - @end smallexample - - @item Provide a "foreign" view of the library interface; - - The example below shows the content of @code{mylib_interface.h} (note - that there is no rule for the naming of this file, any name can be used) - @smallexample - /* the library elaboration procedure */ - extern void mylibinit (void); - - /* the library finalization procedure */ - extern void mylibfinal (void); - - /* the interface exported by the library */ - extern void do_something (void); - extern void do_something_else (void); - @end smallexample - @end itemize - - @subsection Using the Library - - @noindent - Libraries built as explained above can be used from any program, provided - that the elaboration procedures (named @code{mylibinit} in the previous - example) are called before the library services are used. Any number of - libraries can be used simultaneously, as long as the elaboration - procedure of each library is called. - - Below is an example of C program that uses our @code{mylib} library. - - @smallexample - #include "mylib_interface.h" - - int - main (void) - @{ - /* First, elaborate the library before using it */ - mylibinit (); - - /* Main program, using the library exported entities */ - do_something (); - do_something_else (); - - /* Library finalization at the end of the program */ - mylibfinal (); - return 0; - @} - @end smallexample - - @noindent - Note that this same library can be used from an equivalent Ada main - program. In addition, if the libraries are installed as detailed in - @ref{Installing an Ada Library}, it is not necessary to invoke the - library elaboration and finalization routines. The binder will ensure - that this is done as part of the main program elaboration and - finalization phases. - - @subsection The Finalization Phase - - @noindent - Invoking any library finalization procedure generated by @code{gnatbind} - shuts down the Ada run time permanently. Consequently, the finalization - of all Ada libraries must be performed at the end of the program. No - call to these libraries nor the Ada run time should be made past the - finalization phase. - - @subsection Restrictions in Libraries - - @noindent - The pragmas listed below should be used with caution inside libraries, - as they can create incompatibilities with other Ada libraries: - @itemize @bullet - @item pragma @code{Locking_Policy} - @item pragma @code{Queuing_Policy} - @item pragma @code{Task_Dispatching_Policy} - @item pragma @code{Unreserve_All_Interrupts} - @end itemize - When using a library that contains such pragmas, the user must make sure - that all libraries use the same pragmas with the same values. Otherwise, - a @code{Program_Error} will - be raised during the elaboration of the conflicting - libraries. The usage of these pragmas and its consequences for the user - should therefore be well documented. - - Similarly, the traceback in exception occurrences mechanism should be - enabled or disabled in a consistent manner across all libraries. - Otherwise, a Program_Error will be raised during the elaboration of the - conflicting libraries. - - If the @code{'Version} and @code{'Body_Version} - attributes are used inside a library, then it is necessary to - perform a @code{gnatbind} step that mentions all ali files in all - libraries, so that version identifiers can be properly computed. - In practice these attributes are rarely used, so this is unlikely - to be a consideration. - - @node Rebuilding the GNAT Run-Time Library - @section Rebuilding the GNAT Run-Time Library - - @noindent - It may be useful to recompile the GNAT library in various contexts, the - most important one being the use of partition-wide configuration pragmas - such as Normalize_Scalar. A special Makefile called - @code{Makefile.adalib} is provided to that effect and can be found in - the directory containing the GNAT library. The location of this - directory depends on the way the GNAT environment has been installed and can - be determined by means of the command: - - @smallexample - $ gnatls -v - @end smallexample - - @noindent - The last entry in the object search path usually contains the - gnat library. This Makefile contains its own documentation and in - particular the set of instructions needed to rebuild a new library and - to use it. - - @node Using the GNU make Utility - @chapter Using the GNU @code{make} Utility - @findex make - - @noindent - This chapter offers some examples of makefiles that solve specific - problems. It does not explain how to write a makefile (see the GNU make - documentation), nor does it try to replace the @code{gnatmake} utility - (@pxref{The GNAT Make Program gnatmake}). - - All the examples in this section are specific to the GNU version of - make. Although @code{make} is a standard utility, and the basic language - is the same, these examples use some advanced features found only in - @code{GNU make}. - - @menu - * Using gnatmake in a Makefile:: - * Automatically Creating a List of Directories:: - * Generating the Command Line Switches:: - * Overcoming Command Line Length Limits:: - @end menu - - @node Using gnatmake in a Makefile - @section Using gnatmake in a Makefile - @findex makefile - @cindex GNU make - - @noindent - Complex project organizations can be handled in a very powerful way by - using GNU make combined with gnatmake. For instance, here is a Makefile - which allows you to build each subsystem of a big project into a separate - shared library. Such a makefile allows you to significantly reduce the link - time of very big applications while maintaining full coherence at - each step of the build process. - - The list of dependencies are handled automatically by - @code{gnatmake}. The Makefile is simply used to call gnatmake in each of - the appropriate directories. - - Note that you should also read the example on how to automatically - create the list of directories (@pxref{Automatically Creating a List of Directories}) - which might help you in case your project has a lot of - subdirectories. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - ## This Makefile is intended to be used with the following directory - ## configuration: - ## - The sources are split into a series of csc (computer software components) - ## Each of these csc is put in its own directory. - ## Their name are referenced by the directory names. - ## They will be compiled into shared library (although this would also work - ## with static libraries - ## - The main program (and possibly other packages that do not belong to any - ## csc is put in the top level directory (where the Makefile is). - ## toplevel_dir __ first_csc (sources) __ lib (will contain the library) - ## \_ second_csc (sources) __ lib (will contain the library) - ## \_ ... - ## Although this Makefile is build for shared library, it is easy to modify - ## to build partial link objects instead (modify the lines with -shared and - ## gnatlink below) - ## - ## With this makefile, you can change any file in the system or add any new - ## file, and everything will be recompiled correctly (only the relevant shared - ## objects will be recompiled, and the main program will be re-linked). - - # The list of computer software component for your project. This might be - # generated automatically. - CSC_LIST=aa bb cc - - # Name of the main program (no extension) - MAIN=main - - # If we need to build objects with -fPIC, uncomment the following line - #NEED_FPIC=-fPIC - - # The following variable should give the directory containing libgnat.so - # You can get this directory through 'gnatls -v'. This is usually the last - # directory in the Object_Path. - GLIB=... - - # The directories for the libraries - # (This macro expands the list of CSC to the list of shared libraries, you - # could simply use the expanded form : - # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so - LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@} - - $@{MAIN@}: objects $@{LIB_DIR@} - gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared - gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@} - - objects:: - # recompile the sources - gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@} - - # Note: In a future version of GNAT, the following commands will be simplified - # by a new tool, gnatmlib - $@{LIB_DIR@}: - mkdir -p $@{dir $@@ @} - cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat - cd $@{dir $@@ @}; cp -f ../*.ali . - - # The dependencies for the modules - # Note that we have to force the expansion of *.o, since in some cases make won't - # be able to do it itself. - aa/lib/libaa.so: $@{wildcard aa/*.o@} - bb/lib/libbb.so: $@{wildcard bb/*.o@} - cc/lib/libcc.so: $@{wildcard cc/*.o@} - - # Make sure all of the shared libraries are in the path before starting the - # program - run:: - LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@} - - clean:: - $@{RM@} -rf $@{CSC_LIST:%=%/lib@} - $@{RM@} $@{CSC_LIST:%=%/*.ali@} - $@{RM@} $@{CSC_LIST:%=%/*.o@} - $@{RM@} *.o *.ali $@{MAIN@} - @end smallexample - - @node Automatically Creating a List of Directories - @section Automatically Creating a List of Directories - - @noindent - In most makefiles, you will have to specify a list of directories, and - store it in a variable. For small projects, it is often easier to - specify each of them by hand, since you then have full control over what - is the proper order for these directories, which ones should be - included... - - However, in larger projects, which might involve hundreds of - subdirectories, it might be more convenient to generate this list - automatically. - - The example below presents two methods. The first one, although less - general, gives you more control over the list. It involves wildcard - characters, that are automatically expanded by @code{make}. Its - shortcoming is that you need to explicitly specify some of the - organization of your project, such as for instance the directory tree - depth, whether some directories are found in a separate tree,... - - The second method is the most general one. It requires an external - program, called @code{find}, which is standard on all Unix systems. All - the directories found under a given root directory will be added to the - list. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # The examples below are based on the following directory hierarchy: - # All the directories can contain any number of files - # ROOT_DIRECTORY -> a -> aa -> aaa - # -> ab - # -> ac - # -> b -> ba -> baa - # -> bb - # -> bc - # This Makefile creates a variable called DIRS, that can be reused any time - # you need this list (see the other examples in this section) - - # The root of your project's directory hierarchy - ROOT_DIRECTORY=. - - #### - # First method: specify explicitly the list of directories - # This allows you to specify any subset of all the directories you need. - #### - - DIRS := a/aa/ a/ab/ b/ba/ - - #### - # Second method: use wildcards - # Note that the argument(s) to wildcard below should end with a '/'. - # Since wildcards also return file names, we have to filter them out - # to avoid duplicate directory names. - # We thus use make's @code{dir} and @code{sort} functions. - # It sets DIRs to the following value (note that the directories aaa and baa - # are not given, unless you change the arguments to wildcard). - # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/ - #### - - DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@} - - #### - # Third method: use an external program - # This command is much faster if run on local disks, avoiding NFS slowdowns. - # This is the most complete command: it sets DIRs to the following value: - # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc - #### - - DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@} - - @end smallexample - - @node Generating the Command Line Switches - @section Generating the Command Line Switches - - @noindent - Once you have created the list of directories as explained in the - previous section (@pxref{Automatically Creating a List of Directories}), - you can easily generate the command line arguments to pass to gnatmake. - - For the sake of completeness, this example assumes that the source path - is not the same as the object path, and that you have two separate lists - of directories. - - @smallexample - # see "Automatically creating a list of directories" to create - # these variables - SOURCE_DIRS= - OBJECT_DIRS= - - GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@} - GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@} - - all: - gnatmake $@{GNATMAKE_SWITCHES@} main_unit - @end smallexample - - @node Overcoming Command Line Length Limits - @section Overcoming Command Line Length Limits - - @noindent - One problem that might be encountered on big projects is that many - operating systems limit the length of the command line. It is thus hard to give - gnatmake the list of source and object directories. - - This example shows how you can set up environment variables, which will - make @code{gnatmake} behave exactly as if the directories had been - specified on the command line, but have a much higher length limit (or - even none on most systems). - - It assumes that you have created a list of directories in your Makefile, - using one of the methods presented in - @ref{Automatically Creating a List of Directories}. - For the sake of completeness, we assume that the object - path (where the ALI files are found) is different from the sources patch. - - Note a small trick in the Makefile below: for efficiency reasons, we - create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are - expanded immediately by @code{make}. This way we overcome the standard - make behavior which is to expand the variables only when they are - actually used. - - @smallexample - @iftex - @leftskip=0cm - @font@heightrm=cmr8 - @heightrm - @end iftex - # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH. - # This is the same thing as putting the -I arguments on the command line. - # (the equivalent of using -aI on the command line would be to define - # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH). - # You can of course have different values for these variables. - # - # Note also that we need to keep the previous values of these variables, since - # they might have been set before running 'make' to specify where the GNAT - # library is installed. - - # see "Automatically creating a list of directories" to create these - # variables - SOURCE_DIRS= - OBJECT_DIRS= - - empty:= - space:=$@{empty@} $@{empty@} - SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@} - OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@} - ADA_INCLUDE_PATH += $@{SOURCE_LIST@} - ADA_OBJECT_PATH += $@{OBJECT_LIST@} - export ADA_INCLUDE_PATH - export ADA_OBJECT_PATH - - all: - gnatmake main_unit - @end smallexample - - @node Finding Memory Problems with gnatmem - @chapter Finding Memory Problems with @code{gnatmem} - @findex gnatmem - - @noindent - @code{gnatmem}, is a tool that monitors dynamic allocation and - deallocation activity in a program, and displays information about - incorrect deallocations and possible sources of memory leaks. Gnatmem - provides three type of information: - @itemize @bullet - @item - General information concerning memory management, such as the total - number of allocations and deallocations, the amount of allocated - memory and the high water mark, i.e. the largest amount of allocated - memory in the course of program execution. - - @item - Backtraces for all incorrect deallocations, that is to say deallocations - which do not correspond to a valid allocation. - - @item - Information on each allocation that is potentially the origin of a memory - leak. - @end itemize - - The @code{gnatmem} command has two modes. It can be used with @code{gdb} - or with instrumented allocation and deallocation routines. The later - mode is called the @code{GMEM} mode. Both modes produce the very same - output. - - @menu - * Running gnatmem (GDB Mode):: - * Running gnatmem (GMEM Mode):: - * Switches for gnatmem:: - * Examples of gnatmem Usage:: - * GDB and GMEM Modes:: - * Implementation Note:: - @end menu - - @node Running gnatmem (GDB Mode) - @section Running @code{gnatmem} (GDB Mode) - - @noindent - The @code{gnatmem} command has the form - - @smallexample - $ gnatmem [-q] [n] [-o file] user_program [program_arg]* - or - $ gnatmem [-q] [n] -i file - @end smallexample - - @noindent - Gnatmem must be supplied with the executable to examine, followed by its - run-time inputs. For example, if a program is executed with the command: - @smallexample - $ my_program arg1 arg2 - @end smallexample - then it can be run under @code{gnatmem} control using the command: - @smallexample - $ gnatmem my_program arg1 arg2 - @end smallexample - - The program is transparently executed under the control of the debugger - @ref{The GNAT Debugger GDB}. This does not affect the behavior - of the program, except for sensitive real-time programs. When the program - has completed execution, @code{gnatmem} outputs a report containing general - allocation/deallocation information and potential memory leak. - For better results, the user program should be compiled with - debugging options @ref{Switches for gcc}. - - Here is a simple example of use: - - *************** debut cc - @smallexample - $ gnatmem test_gm - - Global information - ------------------ - Total number of allocations : 45 - Total number of deallocations : 6 - Final Water Mark (non freed mem) : 11.29 Kilobytes - High Water Mark : 11.40 Kilobytes - - . - . - . - Allocation Root # 2 - ------------------- - Number of non freed allocations : 11 - Final Water Mark (non freed mem) : 1.16 Kilobytes - High Water Mark : 1.27 Kilobytes - Backtrace : - test_gm.adb:23 test_gm.alloc - . - . - . - @end smallexample - - The first block of output give general information. In this case, the - Ada construct "@b{new}" was executed 45 times, and only 6 calls to an - unchecked deallocation routine occurred. - - Subsequent paragraphs display information on all allocation roots. - An allocation root is a specific point in the execution of the program - that generates some dynamic allocation, such as a "@b{new}" construct. This - root is represented by an execution backtrace (or subprogram call - stack). By default the backtrace depth for allocations roots is 1, so - that a root corresponds exactly to a source location. The backtrace can - be made deeper, to make the root more specific. - - @node Running gnatmem (GMEM Mode) - @section Running @code{gnatmem} (GMEM Mode) - @cindex @code{GMEM} (@code{gnatmem}) - - @noindent - The @code{gnatmem} command has the form - - @smallexample - $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]* - @end smallexample - - The program must have been linked with the instrumented version of the - allocation and deallocation routines. This is done with linking with the - @file{libgmem.a} library. For better results, the user program should be - compiled with debugging options @ref{Switches for gcc}. For example to - build @file{my_program}: - - @smallexample - $ gnatmake -g my_program -largs -lgmem - @end smallexample - - @noindent - When running @file{my_program} the file @file{gmem.out} is produced. This file - contains information about all allocations and deallocations done by the - program. It is produced by the instrumented allocations and - deallocations routines and will be used by @code{gnatmem}. - - @noindent - Gnatmem must be supplied with the @file{gmem.out} file and the executable to - examine followed by its run-time inputs. For example, if a program is - executed with the command: - @smallexample - $ my_program arg1 arg2 - @end smallexample - then @file{gmem.out} can be analysed by @code{gnatmem} using the command: - @smallexample - $ gnatmem -i gmem.out my_program arg1 arg2 - @end smallexample - - @node Switches for gnatmem - @section Switches for @code{gnatmem} - - @noindent - @code{gnatmem} recognizes the following switches: - - @table @code - - @item @code{-q} - @cindex @code{-q} (@code{gnatmem}) - Quiet. Gives the minimum output needed to identify the origin of the - memory leaks. Omit statistical information. - - @item @code{n} - @cindex @code{n} (@code{gnatmem}) - N is an integer literal (usually between 1 and 10) which controls the - depth of the backtraces defining allocation root. The default value for - N is 1. The deeper the backtrace, the more precise the localization of - the root. Note that the total number of roots can depend on this - parameter. - - @item @code{-o file} - @cindex @code{-o} (@code{gnatmem}) - Direct the gdb output to the specified file. The @code{gdb} script used - to generate this output is also saved in the file @file{gnatmem.tmp}. - - @item @code{-i file} - @cindex @code{-i} (@code{gnatmem}) - Do the @code{gnatmem} processing starting from @file{file} which has - been generated by a previous call to @code{gnatmem} with the -o - switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful - for post mortem processing. - - @end table - - @node Examples of gnatmem Usage - @section Example of @code{gnatmem} Usage - - @noindent - This section is based on the @code{GDB} mode of @code{gnatmem}. The same - results can be achieved using @code{GMEM} mode. See section - @ref{Running gnatmem (GMEM Mode)}. - - @noindent - The first example shows the use of @code{gnatmem} - on a simple leaking program. - Suppose that we have the following Ada program: - - @smallexample - @group - @cartouche - @b{with} Unchecked_Deallocation; - @b{procedure} Test_Gm @b{is} - - @b{type} T @b{is array} (1..1000) @b{of} Integer; - @b{type} Ptr @b{is access} T; - @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr); - A : Ptr; - - @b{procedure} My_Alloc @b{is} - @b{begin} - A := @b{new} T; - @b{end} My_Alloc; - - @b{procedure} My_DeAlloc @b{is} - B : Ptr := A; - @b{begin} - Free (B); - @b{end} My_DeAlloc; - - @b{begin} - My_Alloc; - @b{for} I @b{in} 1 .. 5 @b{loop} - @b{for} J @b{in} I .. 5 @b{loop} - My_Alloc; - @b{end loop}; - My_Dealloc; - @b{end loop}; - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - The program needs to be compiled with debugging option: - - @smallexample - $ gnatmake -g test_gm - @end smallexample - - @code{gnatmem} is invoked simply with - @smallexample - $ gnatmem test_gm - @end smallexample - - @noindent - which produces the following output: - - @smallexample - Global information - ------------------ - Total number of allocations : 18 - Total number of deallocations : 5 - Final Water Mark (non freed mem) : 53.00 Kilobytes - High Water Mark : 56.90 Kilobytes - - Allocation Root # 1 - ------------------- - Number of non freed allocations : 11 - Final Water Mark (non freed mem) : 42.97 Kilobytes - High Water Mark : 46.88 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - - Allocation Root # 2 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 10.02 Kilobytes - High Water Mark : 10.02 Kilobytes - Backtrace : - s-secsta.adb:81 system.secondary_stack.ss_init - - Allocation Root # 3 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 12 Bytes - High Water Mark : 12 Bytes - Backtrace : - s-secsta.adb:181 system.secondary_stack.ss_init - @end smallexample - - @noindent - Note that the GNAT run time contains itself a certain number of - allocations that have no corresponding deallocation, - as shown here for root #2 and root - #1. This is a normal behavior when the number of non freed allocations - is one, it locates dynamic data structures that the run time needs for - the complete lifetime of the program. Note also that there is only one - allocation root in the user program with a single line back trace: - test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the - program shows that 'My_Alloc' is called at 2 different points in the - source (line 21 and line 24). If those two allocation roots need to be - distinguished, the backtrace depth parameter can be used: - - @smallexample - $ gnatmem 3 test_gm - @end smallexample - - @noindent - which will give the following output: - - @smallexample - Global information - ------------------ - Total number of allocations : 18 - Total number of deallocations : 5 - Final Water Mark (non freed mem) : 53.00 Kilobytes - High Water Mark : 56.90 Kilobytes - - Allocation Root # 1 - ------------------- - Number of non freed allocations : 10 - Final Water Mark (non freed mem) : 39.06 Kilobytes - High Water Mark : 42.97 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - test_gm.adb:24 test_gm - b_test_gm.c:52 main - - Allocation Root # 2 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 10.02 Kilobytes - High Water Mark : 10.02 Kilobytes - Backtrace : - s-secsta.adb:81 system.secondary_stack.ss_init - s-secsta.adb:283 - b_test_gm.c:33 adainit - - Allocation Root # 3 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 3.91 Kilobytes - High Water Mark : 3.91 Kilobytes - Backtrace : - test_gm.adb:11 test_gm.my_alloc - test_gm.adb:21 test_gm - b_test_gm.c:52 main - - Allocation Root # 4 - ------------------- - Number of non freed allocations : 1 - Final Water Mark (non freed mem) : 12 Bytes - High Water Mark : 12 Bytes - Backtrace : - s-secsta.adb:181 system.secondary_stack.ss_init - s-secsta.adb:283 - b_test_gm.c:33 adainit - @end smallexample - - @noindent - The allocation root #1 of the first example has been split in 2 roots #1 - and #3 thanks to the more precise associated backtrace. - - @node GDB and GMEM Modes - @section GDB and GMEM Modes - - @noindent - The main advantage of the @code{GMEM} mode is that it is a lot faster than the - @code{GDB} mode where the application must be monitored by a @code{GDB} script. - But the @code{GMEM} mode is available only for DEC Unix, Linux x86, - Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86). - - @noindent - The main advantage of the @code{GDB} mode is that it is available on all - supported platforms. But it can be very slow if the application does a - lot of allocations and deallocations. - - @node Implementation Note - @section Implementation Note - - @menu - * gnatmem Using GDB Mode:: - * gnatmem Using GMEM Mode:: - @end menu - - @node gnatmem Using GDB Mode - @subsection @code{gnatmem} Using @code{GDB} Mode - - @noindent - @code{gnatmem} executes the user program under the control of @code{GDB} using - a script that sets breakpoints and gathers information on each dynamic - allocation and deallocation. The output of the script is then analyzed - by @code{gnatmem} - in order to locate memory leaks and their origin in the - program. Gnatmem works by recording each address returned by the - allocation procedure (@code{__gnat_malloc}) - along with the backtrace at the - allocation point. On each deallocation, the deallocated address is - matched with the corresponding allocation. At the end of the processing, - the unmatched allocations are considered potential leaks. All the - allocations associated with the same backtrace are grouped together and - form an allocation root. The allocation roots are then sorted so that - those with the biggest number of unmatched allocation are printed - first. A delicate aspect of this technique is to distinguish between the - data produced by the user program and the data produced by the gdb - script. Currently, on systems that allow probing the terminal, the gdb - command "tty" is used to force the program output to be redirected to the - current terminal while the @code{gdb} output is directed to a file or to a - pipe in order to be processed subsequently by @code{gnatmem}. - - @node gnatmem Using GMEM Mode - @subsection @code{gnatmem} Using @code{GMEM} Mode - - @noindent - This mode use the same algorithm to detect memory leak as the @code{GDB} - mode of @code{gnatmem}, the only difference is in the way data are - gathered. In @code{GMEM} mode the program is linked with instrumented - version of @code{__gnat_malloc} and @code{__gnat_free} - routines. Information needed to find memory leak are recorded by these - routines in file @file{gmem.out}. This mode also require that the stack - traceback be available, this is only implemented on some platforms - @ref{GDB and GMEM Modes}. - - - @node Finding Memory Problems with GNAT Debug Pool - @chapter Finding Memory Problems with GNAT Debug Pool - @findex Debug Pool - @cindex storage, pool, memory corruption - - @noindent - The use of unchecked deallocation and unchecked conversion can easily - lead to incorrect memory references. The problems generated by such - references are usually difficult to tackle because the symptoms can be - very remote from the origin of the problem. In such cases, it is - very helpful to detect the problem as early as possible. This is the - purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. - - @noindent - In order to use the GNAT specific debugging pool, the user must - associate a debug pool object with each of the access types that may be - related to suspected memory problems. See Ada Reference Manual - 13.11. - @smallexample - @b{type} Ptr @b{is} @b{access} Some_Type; - Pool : GNAT.Debug_Pools.Debug_Pool; - @b{for} Ptr'Storage_Pool @b{use} Pool; - @end smallexample - - @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of - pool: the Checked_Pool. Such pools, like standard Ada storage pools, - allow the user to redefine allocation and deallocation strategies. They - also provide a checkpoint for each dereference, through the use of - the primitive operation @code{Dereference} which is implicitly called at - each dereference of an access value. - - Once an access type has been associated with a debug pool, operations on - values of the type may raise four distinct exceptions, - which correspond to four potential kinds of memory corruption: - @itemize @bullet - @item - @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} - @item - @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } - @end itemize - - @noindent - For types associated with a Debug_Pool, dynamic allocation is performed using - the standard - GNAT allocation routine. References to all allocated chunks of memory - are kept in an internal dictionary. The deallocation strategy consists - in not releasing the memory to the underlying system but rather to fill - it with a memory pattern easily recognizable during debugging sessions: - The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#. - Upon each dereference, a check is made that the access value denotes a properly - allocated memory location. Here is a complete example of use of - @code{Debug_Pools}, that includes typical instances of memory corruption: - @smallexample - @iftex - @leftskip=0cm - @end iftex - @b{with} Gnat.Io; @b{use} Gnat.Io; - @b{with} Unchecked_Deallocation; - @b{with} Unchecked_Conversion; - @b{with} GNAT.Debug_Pools; - @b{with} System.Storage_Elements; - @b{with} Ada.Exceptions; @b{use} Ada.Exceptions; - @b{procedure} Debug_Pool_Test @b{is} - - @b{type} T @b{is} @b{access} Integer; - @b{type} U @b{is} @b{access} @b{all} T; - - P : GNAT.Debug_Pools.Debug_Pool; - @b{for} T'Storage_Pool @b{use} P; - - @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T); - @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T); - A, B : @b{aliased} T; - - @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line); - - @b{begin} - Info (P); - A := @b{new} Integer; - B := @b{new} Integer; - B := A; - Info (P); - Free (A); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - B := UC(A'Access); - @b{begin} - Put_Line (Integer'Image(B.@b{all})); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - @b{begin} - Free (B); - @b{exception} - @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E)); - @b{end}; - Info (P); - @b{end} Debug_Pool_Test; - @end smallexample - @noindent - The debug pool mechanism provides the following precise diagnostics on the - execution of this erroneous program: - @smallexample - Debug Pool info: - Total allocated bytes : 0 - Total deallocated bytes : 0 - Current Water Mark: 0 - High Water Mark: 0 - - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 0 - Current Water Mark: 8 - High Water Mark: 8 - - raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE - raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE - Debug Pool info: - Total allocated bytes : 8 - Total deallocated bytes : 4 - Current Water Mark: 4 - High Water Mark: 8 - - @end smallexample - - @node Creating Sample Bodies Using gnatstub - @chapter Creating Sample Bodies Using @code{gnatstub} - @findex gnatstub - - @noindent - @code{gnatstub} creates body stubs, that is, empty but compilable bodies - for library unit declarations. - - To create a body stub, @code{gnatstub} has to compile the library - unit declaration. Therefore, bodies can be created only for legal - library units. Moreover, if a library unit depends semantically upon - units located outside the current directory, you have to provide - the source search path when calling @code{gnatstub}, see the description - of @code{gnatstub} switches below. - - @menu - * Running gnatstub:: - * Switches for gnatstub:: - @end menu - - @node Running gnatstub - @section Running @code{gnatstub} - - @noindent - @code{gnatstub} has the command-line interface of the form - - @smallexample - $ gnatstub [switches] filename [directory] - @end smallexample - - @noindent - where - @table @code - @item filename - is the name of the source file that contains a library unit declaration - for which a body must be created. This name should follow the GNAT file name - conventions. No crunching is allowed for this file name. The file - name may contain the path information. - - @item directory - indicates the directory to place a body stub (default is the - current directory) - - @item switches - is an optional sequence of switches as described in the next section - @end table - - @node Switches for gnatstub - @section Switches for @code{gnatstub} - - @table @code - - @item -f - If the destination directory already contains a file with a name of the body file - for the argument spec file, replace it with the generated body stub. - - @item -hs - Put the comment header (i.e. all the comments preceding the - compilation unit) from the source of the library unit declaration - into the body stub. - - @item -hg - Put a sample comment header into the body stub. - - @item -IDIR - @itemx -I- - These switches have the same meaning as in calls to gcc. - They define the source search path in the call to gcc issued - by @code{gnatstub} to compile an argument source file. - - @item -i@var{n} - (@var{n} is a decimal natural number). Set the indentation level in the - generated body sample to n, '-i0' means "no indentation", - the default indentation is 3. - - @item -k - Do not remove the tree file (i.e. the snapshot of the compiler internal - structures used by @code{gnatstub}) after creating the body stub. - - @item -l@var{n} - (@var{n} is a decimal positive number) Set the maximum line length in the - body stub to n, the default is 78. - - @item -q - Quiet mode: do not generate a confirmation when a body is - successfully created or a message when a body is not required for an - argument unit. - - @item -r - Reuse the tree file (if it exists) instead of creating it: instead of - creating the tree file for the library unit declaration, gnatstub - tries to find it in the current directory and use it for creating - a body. If the tree file is not found, no body is created. @code{-r} - also implies @code{-k}, whether or not - @code{-k} is set explicitly. - - @item -t - Overwrite the existing tree file: if the current directory already - contains the file which, according to the GNAT file name rules should - be considered as a tree file for the argument source file, gnatstub - will refuse to create the tree file needed to create a body sampler, - unless @code{-t} option is set - - @item -v - Verbose mode: generate version information. - - @end table - - @node Reducing the Size of Ada Executables with gnatelim - @chapter Reducing the Size of Ada Executables with @code{gnatelim} - @findex gnatelim - - @menu - * About gnatelim:: - * Eliminate Pragma:: - * Tree Files:: - * Preparing Tree and Bind Files for gnatelim:: - * Running gnatelim:: - * Correcting the List of Eliminate Pragmas:: - * Making Your Executables Smaller:: - * Summary of the gnatelim Usage Cycle:: - @end menu - - @node About gnatelim - @section About @code{gnatelim} - - @noindent - When a program shares a set of Ada - packages with other programs, it may happen that this program uses - only a fraction of the subprograms defined in these packages. The code - created for these unused subprograms increases the size of the executable. - - @code{gnatelim} tracks unused subprograms in an Ada program and - outputs a list of GNAT-specific @code{Eliminate} pragmas (see next - section) marking all the subprograms that are declared but never called. - By placing the list of @code{Eliminate} pragmas in the GNAT configuration - file @file{gnat.adc} and recompiling your program, you may decrease the - size of its executable, because the compiler will not generate the code - for 'eliminated' subprograms. - - @code{gnatelim} needs as its input data a set of tree files - (see @ref{Tree Files}) representing all the components of a program to - process and a bind file for a main subprogram (see - @ref{Preparing Tree and Bind Files for gnatelim}). - - @node Eliminate Pragma - @section @code{Eliminate} Pragma - @findex Eliminate - - @noindent - The simplified syntax of the Eliminate pragma used by @code{gnatelim} is: - - @smallexample - @cartouche - @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name); - @end cartouche - @end smallexample - - @noindent - where - @table @code - @item Library_Unit_Name - full expanded Ada name of a library unit - - @item Subprogram_Name - a simple or expanded name of a subprogram declared within this - compilation unit - - @end table - - @noindent - The effect of an @code{Eliminate} pragma placed in the GNAT configuration - file @file{gnat.adc} is: - - @itemize @bullet - - @item - If the subprogram @code{Subprogram_Name} is declared within - the library unit @code{Library_Unit_Name}, the compiler will not generate - code for this subprogram. This applies to all overloaded subprograms denoted - by @code{Subprogram_Name}. - - @item - If a subprogram marked by the pragma @code{Eliminate} is used (called) - in a program, the compiler will produce an error message in the place where - it is called. - @end itemize - - @node Tree Files - @section Tree Files - @cindex Tree file - - @noindent - A tree file stores a snapshot of the compiler internal data - structures at the very end of a successful compilation. It contains all the - syntactic and semantic information for the compiled unit and all the - units upon which it depends semantically. - To use tools that make use of tree files, you - need to first produce the right set of tree files. - - GNAT produces correct tree files when -gnatt -gnatc options are set - in a gcc call. The tree files have an .adt extension. - Therefore, to produce a tree file for the compilation unit contained in a file - named @file{foo.adb}, you must use the command - - @smallexample - $ gcc -c -gnatc -gnatt foo.adb - @end smallexample - - @noindent - and you will get the tree file @file{foo.adt}. - compilation. - - @node Preparing Tree and Bind Files for gnatelim - @section Preparing Tree and Bind Files for @code{gnatelim} - - @noindent - A set of tree files covering the program to be analyzed with - @code{gnatelim} and - the bind file for the main subprogram does not have to - be in the current directory. - '-T' gnatelim option may be used to provide - the search path for tree files, and '-b' - option may be used to point to the bind - file to process (see @ref{Running gnatelim}) - - If you do not have the appropriate set of tree - files and the right bind file, you - may create them in the current directory using the following procedure. - - Let @code{Main_Prog} be the name of a main subprogram, and suppose - this subprogram is in a file named @file{main_prog.adb}. - - To create a bind file for @code{gnatelim}, run @code{gnatbind} for - the main subprogram. @code{gnatelim} can work with both Ada and C - bind files; when both are present, it uses the Ada bind file. - The following commands will build the program and create the bind file: - - @smallexample - $ gnatmake -c Main_Prog - $ gnatbind main_prog - @end smallexample - - @noindent - To create a minimal set of tree files covering the whole program, call - @code{gnatmake} for this program as follows: - - @smallexample - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end smallexample - - @noindent - The @code{-c} gnatmake option turns off the bind and link - steps, that are useless anyway because the sources are compiled with - @option{-gnatc} option which turns off code generation. - - The @code{-f} gnatmake option forces - recompilation of all the needed sources. - - This sequence of actions will create all the data needed by @code{gnatelim} - from scratch and therefore guarantee its consistency. If you would like to - use some existing set of files as @code{gnatelim} output, you must make - sure that the set of files is complete and consistent. You can use the - @code{-m} switch to check if there are missed tree files - - Note, that @code{gnatelim} needs neither object nor ALI files. - - @node Running gnatelim - @section Running @code{gnatelim} - - @noindent - @code{gnatelim} has the following command-line interface: - - @smallexample - $ gnatelim [options] name - @end smallexample - - @noindent - @code{name} should be a full expanded Ada name of a main subprogram - of a program (partition). - - @code{gnatelim} options: - - @table @code - @item -q - Quiet mode: by default @code{gnatelim} generates to the standard error - stream a trace of the source file names of the compilation units being - processed. This option turns this trace off. - - @item -v - Verbose mode: @code{gnatelim} version information is printed as Ada - comments to the standard output stream. - - @item -a - Also look for subprograms from the GNAT run time that can be eliminated. - - @item -m - Check if any tree files are missing for an accurate result. - - @item -T@var{dir} - When looking for tree files also look in directory @var{dir} - - @item -b@var{bind_file} - Specifies @var{bind_file} as the bind file to process. If not set, the name - of the bind file is computed from the full expanded Ada name of a main subprogram. - - @item -d@var{x} - Activate internal debugging switches. @var{x} is a letter or digit, or - string of letters or digits, which specifies the type of debugging - mode desired. Normally these are used only for internal development - or system debugging purposes. You can find full documentation for these - switches in the body of the @code{Gnatelim.Options} unit in the compiler - source file @file{gnatelim-options.adb}. - @end table - - @noindent - @code{gnatelim} sends its output to the standard output stream, and all the - tracing and debug information is sent to the standard error stream. - In order to produce a proper GNAT configuration file - @file{gnat.adc}, redirection must be used: - - @smallexample - $ gnatelim Main_Prog > gnat.adc - @end smallexample - - @noindent - or - - @smallexample - $ gnatelim Main_Prog >> gnat.adc - @end smallexample - - @noindent - In order to append the @code{gnatelim} output to the existing contents of - @file{gnat.adc}. - - @node Correcting the List of Eliminate Pragmas - @section Correcting the List of Eliminate Pragmas - - @noindent - In some rare cases it may happen that @code{gnatelim} will try to eliminate - subprograms which are actually called in the program. In this case, the - compiler will generate an error message of the form: - - @smallexample - file.adb:106:07: cannot call eliminated subprogram "My_Prog" - @end smallexample - - @noindent - You will need to manually remove the wrong @code{Eliminate} pragmas from - the @file{gnat.adc} file. It is advised that you recompile your program - from scratch after that because you need a consistent @file{gnat.adc} file - during the entire compilation. - - @node Making Your Executables Smaller - @section Making Your Executables Smaller - - @noindent - In order to get a smaller executable for your program you now have to - recompile the program completely with the new @file{gnat.adc} file - created by @code{gnatelim} in your current directory: - - @smallexample - $ gnatmake -f Main_Prog - @end smallexample - - @noindent - (you will need @code{-f} option for gnatmake to - recompile everything - with the set of pragmas @code{Eliminate} you have obtained with - @code{gnatelim}). - - Be aware that the set of @code{Eliminate} pragmas is specific to each - program. It is not recommended to merge sets of @code{Eliminate} - pragmas created for different programs in one @file{gnat.adc} file. - - @node Summary of the gnatelim Usage Cycle - @section Summary of the gnatelim Usage Cycle - - @noindent - Here is a quick summary of the steps to be taken in order to reduce - the size of your executables with @code{gnatelim}. You may use - other GNAT options to control the optimization level, - to produce the debugging information, to set search path, etc. - - @enumerate - @item - Produce a bind file and a set of tree files - - @smallexample - $ gnatmake -c Main_Prog - $ gnatbind main_prog - $ gnatmake -f -c -gnatc -gnatt Main_Prog - @end smallexample - - @item - Generate a list of @code{Eliminate} pragmas - @smallexample - $ gnatelim Main_Prog >[>] gnat.adc - @end smallexample - - @item - Recompile the application - - @smallexample - $ gnatmake -f Main_Prog - @end smallexample - - @end enumerate - - @node Other Utility Programs - @chapter Other Utility Programs - - @noindent - This chapter discusses some other utility programs available in the Ada - environment. - - @menu - * Using Other Utility Programs with GNAT:: - * The gnatpsta Utility Program:: - * The External Symbol Naming Scheme of GNAT:: - * Ada Mode for Glide:: - * Converting Ada Files to html with gnathtml:: - * Installing gnathtml:: - @end menu - - @node Using Other Utility Programs with GNAT - @section Using Other Utility Programs with GNAT - - @noindent - The object files generated by GNAT are in standard system format and in - particular the debugging information uses this format. This means - programs generated by GNAT can be used with existing utilities that - depend on these formats. - - In general, any utility program that works with C will also often work with - Ada programs generated by GNAT. This includes software utilities such as - gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such - as Purify. - - @node The gnatpsta Utility Program - @section The @code{gnatpsta} Utility Program - - @noindent - Many of the definitions in package Standard are implementation-dependent. - However, the source of this package does not exist as an Ada source - file, so these values cannot be determined by inspecting the source. - They can be determined by examining in detail the coding of - @file{cstand.adb} which creates the image of Standard in the compiler, - but this is awkward and requires a great deal of internal knowledge - about the system. - - The @code{gnatpsta} utility is designed to deal with this situation. - It is an Ada program that dynamically determines the - values of all the relevant parameters in Standard, and prints them - out in the form of an Ada source listing for Standard, displaying all - the values of interest. This output is generated to - @file{stdout}. - - To determine the value of any parameter in package Standard, simply - run @code{gnatpsta} with no qualifiers or arguments, and examine - the output. This is preferable to consulting documentation, because - you know that the values you are getting are the actual ones provided - by the executing system. - - @node The External Symbol Naming Scheme of GNAT - @section The External Symbol Naming Scheme of GNAT - - @noindent - In order to interpret the output from GNAT, when using tools that are - originally intended for use with other languages, it is useful to - understand the conventions used to generate link names from the Ada - entity names. - - All link names are in all lowercase letters. With the exception of library - procedure names, the mechanism used is simply to use the full expanded - Ada name with dots replaced by double underscores. For example, suppose - we have the following package spec: - - @smallexample - @group - @cartouche - @b{package} QRS @b{is} - MN : Integer; - @b{end} QRS; - @end cartouche - @end group - @end smallexample - - @noindent - The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so - the corresponding link name is @code{qrs__mn}. - @findex Export - Of course if a @code{pragma Export} is used this may be overridden: - - @smallexample - @group - @cartouche - @b{package} Exports @b{is} - Var1 : Integer; - @b{pragma} Export (Var1, C, External_Name => "var1_name"); - Var2 : Integer; - @b{pragma} Export (Var2, C, Link_Name => "var2_link_name"); - @b{end} Exports; - @end cartouche - @end group - @end smallexample - - @noindent - In this case, the link name for @var{Var1} is whatever link name the - C compiler would assign for the C function @var{var1_name}. This typically - would be either @var{var1_name} or @var{_var1_name}, depending on operating - system conventions, but other possibilities exist. The link name for - @var{Var2} is @var{var2_link_name}, and this is not operating system - dependent. - - @findex _main - One exception occurs for library level procedures. A potential ambiguity - arises between the required name @code{_main} for the C main program, - and the name we would otherwise assign to an Ada library level procedure - called @code{Main} (which might well not be the main program). - - To avoid this ambiguity, we attach the prefix @code{_ada_} to such - names. So if we have a library level procedure such as - - @smallexample - @group - @cartouche - @b{procedure} Hello (S : String); - @end cartouche - @end group - @end smallexample - - @noindent - the external name of this procedure will be @var{_ada_hello}. - - @node Ada Mode for Glide - @section Ada Mode for @code{Glide} - - @noindent - The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the - user in understanding existing code and facilitates writing new code. It - furthermore provides some utility functions for easier integration of - standard Emacs features when programming in Ada. - - @subsection General Features: - - @itemize @bullet - @item - Full Integrated Development Environment : - - @itemize @bullet - @item - support of 'project files' for the configuration (directories, - compilation options,...) - - @item - compiling and stepping through error messages. - - @item - running and debugging your applications within Glide. - @end itemize - - @item - easy to use for beginners by pull-down menus, - - @item - user configurable by many user-option variables. - @end itemize - - @subsection Ada Mode Features That Help Understanding Code: - - @itemize @bullet - @item - functions for easy and quick stepping through Ada code, - - @item - getting cross reference information for identifiers (e.g. find the - defining place by a keystroke), - - @item - displaying an index menu of types and subprograms and move point to - the chosen one, - - @item - automatic color highlighting of the various entities in Ada code. - @end itemize - - @subsection Glide Support for Writing Ada Code: - - @itemize @bullet - @item - switching between spec and body files with possible - autogeneration of body files, - - @item - automatic formating of subprograms parameter lists. - - @item - automatic smart indentation according to Ada syntax, - - @item - automatic completion of identifiers, - - @item - automatic casing of identifiers, keywords, and attributes, - - @item - insertion of statement templates, - - @item - filling comment paragraphs like filling normal text, - @end itemize - - For more information, please refer to the online Glide documentation - available in the Glide --> Help Menu. - - @node Converting Ada Files to html with gnathtml - @section Converting Ada Files to html with @code{gnathtml} - - @noindent - This @code{Perl} script allows Ada source files to be browsed using - standard Web browsers. For installation procedure, see the section - @xref{Installing gnathtml}. - - Ada reserved keywords are highlighted in a bold font and Ada comments in - a blue font. Unless your program was compiled with the gcc @option{-gnatx} - switch to suppress the generation of cross-referencing information, user - defined variables and types will appear in a different color; you will - be able to click on any identifier and go to its declaration. - - The command line is as follow: - @smallexample - $ perl gnathtml.pl [switches] ada-files - @end smallexample - - You can pass it as many Ada files as you want. @code{gnathtml} will generate - an html file for every ada file, and a global file called @file{index.htm}. - This file is an index of every identifier defined in the files. - - The available switches are the following ones : - - @table @code - @item -83 - @cindex @code{-83} (@code{gnathtml}) - Only the subset on the Ada 83 keywords will be highlighted, not the full - Ada 95 keywords set. - - @item -cc @var{color} - This option allows you to change the color used for comments. The default - value is green. The color argument can be any name accepted by html. - - @item -d - @cindex @code{-d} (@code{gnathtml}) - If the ada files depend on some other files (using for instance the - @code{with} command, the latter will also be converted to html. - Only the files in the user project will be converted to html, not the files - in the run-time library itself. - - @item -D - This command is the same as -d above, but @code{gnathtml} will also look - for files in the run-time library, and generate html files for them. - - @item -f - @cindex @code{-f} (@code{gnathtml}) - By default, gnathtml will generate html links only for global entities - ('with'ed units, global variables and types,...). If you specify the - @code{-f} on the command line, then links will be generated for local - entities too. - - @item -l @var{number} - @cindex @code{-l} (@code{gnathtml}) - If this switch is provided and @var{number} is not 0, then @code{gnathtml} - will number the html files every @var{number} line. - - @item -I @var{dir} - @cindex @code{-I} (@code{gnathtml}) - Specify a directory to search for library files (@file{.ali} files) and - source files. You can provide several -I switches on the command line, - and the directories will be parsed in the order of the command line. - - @item -o @var{dir} - @cindex @code{-o} (@code{gnathtml}) - Specify the output directory for html files. By default, gnathtml will - saved the generated html files in a subdirectory named @file{html/}. - - @item -p @var{file} - @cindex @code{-p} (@code{gnathtml}) - If you are using Emacs and the most recent Emacs Ada mode, which provides - a full Integrated Development Environment for compiling, checking, - running and debugging applications, you may be using @file{.adp} files - to give the directories where Emacs can find sources and object files. - - Using this switch, you can tell gnathtml to use these files. This allows - you to get an html version of your application, even if it is spread - over multiple directories. - - @item -sc @var{color} - @cindex @code{-sc} (@code{gnathtml}) - This option allows you to change the color used for symbol definitions. - The default value is red. The color argument can be any name accepted by html. - - @item -t @var{file} - @cindex @code{-t} (@code{gnathtml}) - This switch provides the name of a file. This file contains a list of - file names to be converted, and the effect is exactly as though they had - appeared explicitly on the command line. This - is the recommended way to work around the command line length limit on some - systems. - - @end table - - @node Installing gnathtml - @section Installing @code{gnathtml} - - @noindent - @code{Perl} needs to be installed on your machine to run this script. - @code{Perl} is freely available for almost every architecture and - Operating System via the Internet. - - On Unix systems, you may want to modify the first line of the script - @code{gnathtml}, to explicitly tell the Operating system where Perl - is. The syntax of this line is : - @smallexample - #!full_path_name_to_perl - @end smallexample - - @noindent - Alternatively, you may run the script using the following command line: - - @smallexample - $ perl gnathtml.pl [switches] files - @end smallexample - - - @node Running and Debugging Ada Programs - @chapter Running and Debugging Ada Programs - @cindex Debugging - - @noindent - This chapter discusses how to debug Ada programs. An incorrect Ada program - may be handled in three ways by the GNAT compiler: - - @enumerate - @item - The illegality may be a violation of the static semantics of Ada. In - that case GNAT diagnoses the constructs in the program that are illegal. - It is then a straightforward matter for the user to modify those parts of - the program. - - @item - The illegality may be a violation of the dynamic semantics of Ada. In - that case the program compiles and executes, but may generate incorrect - results, or may terminate abnormally with some exception. - - @item - When presented with a program that contains convoluted errors, GNAT - itself may terminate abnormally without providing full diagnostics on - the incorrect user program. - @end enumerate - - @menu - * The GNAT Debugger GDB:: - * Running GDB:: - * Introduction to GDB Commands:: - * Using Ada Expressions:: - * Calling User-Defined Subprograms:: - * Using the Next Command in a Function:: - * Ada Exceptions:: - * Ada Tasks:: - * Debugging Generic Units:: - * GNAT Abnormal Termination or Failure to Terminate:: - * Naming Conventions for GNAT Source Files:: - * Getting Internal Debugging Information:: - * Stack Traceback:: - @end menu - - @cindex Debugger - @findex gdb - - @node The GNAT Debugger GDB - @section The GNAT Debugger GDB - - @noindent - @code{GDB} is a general purpose, platform-independent debugger that - can be used to debug mixed-language programs compiled with @code{GCC}, - and in particular is capable of debugging Ada programs compiled with - GNAT. The latest versions of @code{GDB} are Ada-aware and can handle - complex Ada data structures. - - The manual @cite{Debugging with GDB} - contains full details on the usage of @code{GDB}, including a section on - its usage on programs. This manual should be consulted for full - details. The section that follows is a brief introduction to the - philosophy and use of @code{GDB}. - - When GNAT programs are compiled, the compiler optionally writes debugging - information into the generated object file, including information on - line numbers, and on declared types and variables. This information is - separate from the generated code. It makes the object files considerably - larger, but it does not add to the size of the actual executable that - will be loaded into memory, and has no impact on run-time performance. The - generation of debug information is triggered by the use of the - -g switch in the gcc or gnatmake command used to carry out - the compilations. It is important to emphasize that the use of these - options does not change the generated code. - - The debugging information is written in standard system formats that - are used by many tools, including debuggers and profilers. The format - of the information is typically designed to describe C types and - semantics, but GNAT implements a translation scheme which allows full - details about Ada types and variables to be encoded into these - standard C formats. Details of this encoding scheme may be found in - the file exp_dbug.ads in the GNAT source distribution. However, the - details of this encoding are, in general, of no interest to a user, - since @code{GDB} automatically performs the necessary decoding. - - When a program is bound and linked, the debugging information is - collected from the object files, and stored in the executable image of - the program. Again, this process significantly increases the size of - the generated executable file, but it does not increase the size of - the executable program itself. Furthermore, if this program is run in - the normal manner, it runs exactly as if the debug information were - not present, and takes no more actual memory. - - However, if the program is run under control of @code{GDB}, the - debugger is activated. The image of the program is loaded, at which - point it is ready to run. If a run command is given, then the program - will run exactly as it would have if @code{GDB} were not present. This - is a crucial part of the @code{GDB} design philosophy. @code{GDB} is - entirely non-intrusive until a breakpoint is encountered. If no - breakpoint is ever hit, the program will run exactly as it would if no - debugger were present. When a breakpoint is hit, @code{GDB} accesses - the debugging information and can respond to user commands to inspect - variables, and more generally to report on the state of execution. - - @node Running GDB - @section Running GDB - - @noindent - The debugger can be launched directly and simply from @code{glide} or - through its graphical interface: @code{gvd}. It can also be used - directly in text mode. Here is described the basic use of @code{GDB} - in text mode. All the commands described below can be used in the - @code{gvd} console window eventhough there is usually other more - graphical ways to achieve the same goals. - - @noindent - The command to run de graphical interface of the debugger is - @smallexample - $ gvd program - @end smallexample - - @noindent - The command to run @code{GDB} in text mode is - - @smallexample - $ gdb program - @end smallexample - - @noindent - where @code{program} is the name of the executable file. This - activates the debugger and results in a prompt for debugger commands. - The simplest command is simply @code{run}, which causes the program to run - exactly as if the debugger were not present. The following section - describes some of the additional commands that can be given to @code{GDB}. - - - @node Introduction to GDB Commands - @section Introduction to GDB Commands - - @noindent - @code{GDB} contains a large repertoire of commands. The manual - @cite{Debugging with GDB} - includes extensive documentation on the use - of these commands, together with examples of their use. Furthermore, - the command @var{help} invoked from within @code{GDB} activates a simple help - facility which summarizes the available commands and their options. - In this section we summarize a few of the most commonly - used commands to give an idea of what @code{GDB} is about. You should create - a simple program with debugging information and experiment with the use of - these @code{GDB} commands on the program as you read through the - following section. - - @table @code - @item set args @var{arguments} - The @var{arguments} list above is a list of arguments to be passed to - the program on a subsequent run command, just as though the arguments - had been entered on a normal invocation of the program. The @code{set args} - command is not needed if the program does not require arguments. - - @item run - The @code{run} command causes execution of the program to start from - the beginning. If the program is already running, that is to say if - you are currently positioned at a breakpoint, then a prompt will ask - for confirmation that you want to abandon the current execution and - restart. - - @item breakpoint @var{location} - The breakpoint command sets a breakpoint, that is to say a point at which - execution will halt and @code{GDB} will await further - commands. @var{location} is - either a line number within a file, given in the format @code{file:linenumber}, - or it is the name of a subprogram. If you request that a breakpoint be set on - a subprogram that is overloaded, a prompt will ask you to specify on which of - those subprograms you want to breakpoint. You can also - specify that all of them should be breakpointed. If the program is run - and execution encounters the breakpoint, then the program - stops and @code{GDB} signals that the breakpoint was encountered by - printing the line of code before which the program is halted. - - @item breakpoint exception @var{name} - A special form of the breakpoint command which breakpoints whenever - exception @var{name} is raised. - If @var{name} is omitted, - then a breakpoint will occur when any exception is raised. - - @item print @var{expression} - This will print the value of the given expression. Most simple - Ada expression formats are properly handled by @code{GDB}, so the expression - can contain function calls, variables, operators, and attribute references. - - @item continue - Continues execution following a breakpoint, until the next breakpoint or the - termination of the program. - - @item step - Executes a single line after a breakpoint. If the next statement is a subprogram - call, execution continues into (the first statement of) the - called subprogram. - - @item next - Executes a single line. If this line is a subprogram call, executes and - returns from the call. - - @item list - Lists a few lines around the current source location. In practice, it - is usually more convenient to have a separate edit window open with the - relevant source file displayed. Successive applications of this command - print subsequent lines. The command can be given an argument which is a - line number, in which case it displays a few lines around the specified one. - - @item backtrace - Displays a backtrace of the call chain. This command is typically - used after a breakpoint has occurred, to examine the sequence of calls that - leads to the current breakpoint. The display includes one line for each - activation record (frame) corresponding to an active subprogram. - - @item up - At a breakpoint, @code{GDB} can display the values of variables local - to the current frame. The command @code{up} can be used to - examine the contents of other active frames, by moving the focus up - the stack, that is to say from callee to caller, one frame at a time. - - @item down - Moves the focus of @code{GDB} down from the frame currently being - examined to the frame of its callee (the reverse of the previous command), - - @item frame @var{n} - Inspect the frame with the given number. The value 0 denotes the frame - of the current breakpoint, that is to say the top of the call stack. - - @end table - - The above list is a very short introduction to the commands that - @code{GDB} provides. Important additional capabilities, including conditional - breakpoints, the ability to execute command sequences on a breakpoint, - the ability to debug at the machine instruction level and many other - features are described in detail in @cite{Debugging with GDB}. - Note that most commands can be abbreviated - (for example, c for continue, bt for backtrace). - - @node Using Ada Expressions - @section Using Ada Expressions - @cindex Ada expressions - - @noindent - @code{GDB} supports a fairly large subset of Ada expression syntax, with some - extensions. The philosophy behind the design of this subset is - - @itemize @bullet - @item - That @code{GDB} should provide basic literals and access to operations for - arithmetic, dereferencing, field selection, indexing, and subprogram calls, - leaving more sophisticated computations to subprograms written into the - program (which therefore may be called from @code{GDB}). - - @item - That type safety and strict adherence to Ada language restrictions - are not particularly important to the @code{GDB} user. - - @item - That brevity is important to the @code{GDB} user. - @end itemize - - Thus, for brevity, the debugger acts as if there were - implicit @code{with} and @code{use} clauses in effect for all user-written - packages, thus making it unnecessary to fully qualify most names with - their packages, regardless of context. Where this causes ambiguity, - @code{GDB} asks the user's intent. - - For details on the supported Ada syntax, see @cite{Debugging with GDB}. - - @node Calling User-Defined Subprograms - @section Calling User-Defined Subprograms - - @noindent - An important capability of @code{GDB} is the ability to call user-defined - subprograms while debugging. This is achieved simply by entering - a subprogram call statement in the form: - - @smallexample - call subprogram-name (parameters) - @end smallexample - - @noindent - The keyword @code{call} can be omitted in the normal case where the - @code{subprogram-name} does not coincide with any of the predefined - @code{GDB} commands. - - The effect is to invoke the given subprogram, passing it the - list of parameters that is supplied. The parameters can be expressions and - can include variables from the program being debugged. The - subprogram must be defined - at the library level within your program, and @code{GDB} will call the - subprogram within the environment of your program execution (which - means that the subprogram is free to access or even modify variables - within your program). - - The most important use of this facility is in allowing the inclusion of - debugging routines that are tailored to particular data structures - in your program. Such debugging routines can be written to provide a suitably - high-level description of an abstract type, rather than a low-level dump - of its physical layout. After all, the standard - @code{GDB print} command only knows the physical layout of your - types, not their abstract meaning. Debugging routines can provide information - at the desired semantic level and are thus enormously useful. - - For example, when debugging GNAT itself, it is crucial to have access to - the contents of the tree nodes used to represent the program internally. - But tree nodes are represented simply by an integer value (which in turn - is an index into a table of nodes). - Using the @code{print} command on a tree node would simply print this integer - value, which is not very useful. But the PN routine (defined in file - treepr.adb in the GNAT sources) takes a tree node as input, and displays - a useful high level representation of the tree node, which includes the - syntactic category of the node, its position in the source, the integers - that denote descendant nodes and parent node, as well as varied - semantic information. To study this example in more detail, you might want to - look at the body of the PN procedure in the stated file. - - @node Using the Next Command in a Function - @section Using the Next Command in a Function - - @noindent - When you use the @code{next} command in a function, the current source - location will advance to the next statement as usual. A special case - arises in the case of a @code{return} statement. - - Part of the code for a return statement is the "epilog" of the function. - This is the code that returns to the caller. There is only one copy of - this epilog code, and it is typically associated with the last return - statement in the function if there is more than one return. In some - implementations, this epilog is associated with the first statement - of the function. - - The result is that if you use the @code{next} command from a return - statement that is not the last return statement of the function you - may see a strange apparent jump to the last return statement or to - the start of the function. You should simply ignore this odd jump. - The value returned is always that from the first return statement - that was stepped through. - - @node Ada Exceptions - @section Breaking on Ada Exceptions - @cindex Exceptions - - @noindent - You can set breakpoints that trip when your program raises - selected exceptions. - - @table @code - @item break exception - Set a breakpoint that trips whenever (any task in the) program raises - any exception. - - @item break exception @var{name} - Set a breakpoint that trips whenever (any task in the) program raises - the exception @var{name}. - - @item break exception unhandled - Set a breakpoint that trips whenever (any task in the) program raises an - exception for which there is no handler. - - @item info exceptions - @itemx info exceptions @var{regexp} - The @code{info exceptions} command permits the user to examine all defined - exceptions within Ada programs. With a regular expression, @var{regexp}, as - argument, prints out only those exceptions whose name matches @var{regexp}. - @end table - - @node Ada Tasks - @section Ada Tasks - @cindex Tasks - - @noindent - @code{GDB} allows the following task-related commands: - - @table @code - @item info tasks - This command shows a list of current Ada tasks, as in the following example: - - @smallexample - @iftex - @leftskip=0cm - @end iftex - (gdb) info tasks - ID TID P-ID Thread Pri State Name - 1 8088000 0 807e000 15 Child Activation Wait main_task - 2 80a4000 1 80ae000 15 Accept/Select Wait b - 3 809a800 1 80a4800 15 Child Activation Wait a - * 4 80ae800 3 80b8000 15 Running c - @end smallexample - - @noindent - In this listing, the asterisk before the first task indicates it to be the - currently running task. The first column lists the task ID that is used - to refer to tasks in the following commands. - - @item break @var{linespec} task @var{taskid} - @itemx break @var{linespec} task @var{taskid} if @dots{} - @cindex Breakpoints and tasks - These commands are like the @code{break @dots{} thread @dots{}}. - @var{linespec} specifies source lines. - - Use the qualifier @samp{task @var{taskid}} with a breakpoint command - to specify that you only want @code{GDB} to stop the program when a - particular Ada task reaches this breakpoint. @var{taskid} is one of the - numeric task identifiers assigned by @code{GDB}, shown in the first - column of the @samp{info tasks} display. - - If you do not specify @samp{task @var{taskid}} when you set a - breakpoint, the breakpoint applies to @emph{all} tasks of your - program. - - You can use the @code{task} qualifier on conditional breakpoints as - well; in this case, place @samp{task @var{taskid}} before the - breakpoint condition (before the @code{if}). - - @item task @var{taskno} - @cindex Task switching - - This command allows to switch to the task referred by @var{taskno}. In - particular, This allows to browse the backtrace of the specified - task. It is advised to switch back to the original task before - continuing execution otherwise the scheduling of the program may be - perturbated. - @end table - - @noindent - For more detailed information on the tasking support, see @cite{Debugging with GDB}. - - @node Debugging Generic Units - @section Debugging Generic Units - @cindex Debugging Generic Units - @cindex Generics - - @noindent - GNAT always uses code expansion for generic instantiation. This means that - each time an instantiation occurs, a complete copy of the original code is - made, with appropriate substitutions of formals by actuals. - - It is not possible to refer to the original generic entities in - @code{GDB}, but it is always possible to debug a particular instance of - a generic, by using the appropriate expanded names. For example, if we have - - @smallexample - @group - @cartouche - @b{procedure} g @b{is} - - @b{generic package} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer); - @b{end} k; - - @b{package body} k @b{is} - @b{procedure} kp (v1 : @b{in out} integer) @b{is} - @b{begin} - v1 := v1 + 1; - @b{end} kp; - @b{end} k; - - @b{package} k1 @b{is new} k; - @b{package} k2 @b{is new} k; - - var : integer := 1; - - @b{begin} - k1.kp (var); - k2.kp (var); - k1.kp (var); - k2.kp (var); - @b{end}; - @end cartouche - @end group - @end smallexample - - @noindent - Then to break on a call to procedure kp in the k2 instance, simply - use the command: - - @smallexample - (gdb) break g.k2.kp - @end smallexample - - @noindent - When the breakpoint occurs, you can step through the code of the - instance in the normal manner and examine the values of local variables, as for - other units. - - @node GNAT Abnormal Termination or Failure to Terminate - @section GNAT Abnormal Termination or Failure to Terminate - @cindex GNAT Abnormal Termination or Failure to Terminate - - @noindent - When presented with programs that contain serious errors in syntax - or semantics, - GNAT may on rare occasions experience problems in operation, such - as aborting with a - segmentation fault or illegal memory access, raising an internal - exception, terminating abnormally, or failing to terminate at all. - In such cases, you can activate - various features of GNAT that can help you pinpoint the construct in your - program that is the likely source of the problem. - - The following strategies are presented in increasing order of - difficulty, corresponding to your experience in using GNAT and your - familiarity with compiler internals. - - @enumerate - @item - Run @code{gcc} with the @option{-gnatf}. This first - switch causes all errors on a given line to be reported. In its absence, - only the first error on a line is displayed. - - The @option{-gnatdO} switch causes errors to be displayed as soon as they - are encountered, rather than after compilation is terminated. If GNAT - terminates prematurely or goes into an infinite loop, the last error - message displayed may help to pinpoint the culprit. - - @item - Run @code{gcc} with the @code{-v (verbose)} switch. In this mode, - @code{gcc} produces ongoing information about the progress of the - compilation and provides the name of each procedure as code is - generated. This switch allows you to find which Ada procedure was being - compiled when it encountered a code generation problem. - - @item - @cindex @option{-gnatdc} switch - Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific - switch that does for the front-end what @code{-v} does for the back end. - The system prints the name of each unit, either a compilation unit or - nested unit, as it is being analyzed. - @item - Finally, you can start - @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the - front-end of GNAT, and can be run independently (normally it is just - called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you - would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The - @code{where} command is the first line of attack; the variable - @code{lineno} (seen by @code{print lineno}), used by the second phase of - @code{gnat1} and by the @code{gcc} backend, indicates the source line at - which the execution stopped, and @code{input_file name} indicates the name of - the source file. - @end enumerate - - @node Naming Conventions for GNAT Source Files - @section Naming Conventions for GNAT Source Files - - @noindent - In order to examine the workings of the GNAT system, the following - brief description of its organization may be helpful: - - @itemize @bullet - @item - Files with prefix @file{sc} contain the lexical scanner. - - @item - All files prefixed with @file{par} are components of the parser. The - numbers correspond to chapters of the Ada 95 Reference Manual. For example, - parsing of select statements can be found in @file{par-ch9.adb}. - - @item - All files prefixed with @file{sem} perform semantic analysis. The - numbers correspond to chapters of the Ada standard. For example, all - issues involving context clauses can be found in @file{sem_ch10.adb}. In - addition, some features of the language require sufficient special processing - to justify their own semantic files: sem_aggr for aggregates, sem_disp for - dynamic dispatching, etc. - - @item - All files prefixed with @file{exp} perform normalization and - expansion of the intermediate representation (abstract syntax tree, or AST). - these files use the same numbering scheme as the parser and semantics files. - For example, the construction of record initialization procedures is done in - @file{exp_ch3.adb}. - - @item - The files prefixed with @file{bind} implement the binder, which - verifies the consistency of the compilation, determines an order of - elaboration, and generates the bind file. - - @item - The files @file{atree.ads} and @file{atree.adb} detail the low-level - data structures used by the front-end. - - @item - The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of - the abstract syntax tree as produced by the parser. - - @item - The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of - all entities, computed during semantic analysis. - - @item - Library management issues are dealt with in files with prefix - @file{lib}. - - @item - @findex Ada - @cindex Annex A - Ada files with the prefix @file{a-} are children of @code{Ada}, as - defined in Annex A. - - @item - @findex Interfaces - @cindex Annex B - Files with prefix @file{i-} are children of @code{Interfaces}, as - defined in Annex B. - - @item - @findex System - Files with prefix @file{s-} are children of @code{System}. This includes - both language-defined children and GNAT run-time routines. - - @item - @findex GNAT - Files with prefix @file{g-} are children of @code{GNAT}. These are useful - general-purpose packages, fully documented in their specifications. All - the other @file{.c} files are modifications of common @code{gcc} files. - @end itemize - - @node Getting Internal Debugging Information - @section Getting Internal Debugging Information - - @noindent - Most compilers have internal debugging switches and modes. GNAT - does also, except GNAT internal debugging switches and modes are not - secret. A summary and full description of all the compiler and binder - debug flags are in the file @file{debug.adb}. You must obtain the - sources of the compiler to see the full detailed effects of these flags. - - The switches that print the source of the program (reconstructed from - the internal tree) are of general interest for user programs, as are the - options to print - the full internal tree, and the entity table (the symbol table - information). The reconstructed source provides a readable version of the - program after the front-end has completed analysis and expansion, and is useful - when studying the performance of specific constructs. For example, constraint - checks are indicated, complex aggregates are replaced with loops and - assignments, and tasking primitives are replaced with run-time calls. - - @node Stack Traceback - @section Stack Traceback - @cindex traceback - @cindex stack traceback - @cindex stack unwinding - - @noindent - Traceback is a mechanism to display the sequence of subprogram calls that - leads to a specified execution point in a program. Often (but not always) - the execution point is an instruction at which an exception has been raised. - This mechanism is also known as @i{stack unwinding} because it obtains - its information by scanning the run-time stack and recovering the activation - records of all active subprograms. Stack unwinding is one of the most - important tools for program debugging. - - @noindent - The first entry stored in traceback corresponds to the deepest calling level, - that is to say the subprogram currently executing the instruction - from which we want to obtain the traceback. - - @noindent - Note that there is no runtime performance penalty when stack traceback - is enabled and no exception are raised during program execution. - - @menu - * Non-Symbolic Traceback:: - * Symbolic Traceback:: - @end menu - - @node Non-Symbolic Traceback - @subsection Non-Symbolic Traceback - @cindex traceback, non-symbolic - - @noindent - Note: this feature is not supported on all platforms. See - @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported - platforms. - - @menu - * Tracebacks From an Unhandled Exception:: - * Tracebacks From Exception Occurrences (non-symbolic):: - * Tracebacks From Anywhere in a Program (non-symbolic):: - @end menu - - @node Tracebacks From an Unhandled Exception - @subsubsection Tracebacks From an Unhandled Exception - - @noindent - A runtime non-symbolic traceback is a list of addresses of call instructions. - To enable this feature you must use the @code{-E} - @code{gnatbind}'s option. With this option a stack traceback is stored as part - of exception information. It is possible to retrieve this information using the - standard @code{Ada.Exception.Exception_Information} routine. - - @noindent - Let's have a look at a simple example: - - @smallexample - @cartouche - @group - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @noindent - As we see the traceback lists a sequence of addresses for the unhandled - exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to - guess that this exception come from procedure P1. To translate these - addresses into the source lines where the calls appear, the - @code{addr2line} tool, described below, is invaluable. The use of this tool - requires the program to be compiled with debug information. - - @smallexample - $ gnatmake -g stb -bargs -E - $ stb - - Execution terminated by unhandled exception - Exception name: CONSTRAINT_ERROR - Message: stb.adb:5 - Call stack traceback locations: - 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 - - $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 - 0x4011f1 0x77e892a4 - - 00401373 at d:/stb/stb.adb:5 - 0040138B at d:/stb/stb.adb:10 - 0040139C at d:/stb/stb.adb:14 - 00401335 at d:/stb/b~stb.adb:104 - 004011C4 at /build/.../crt1.c:200 - 004011F1 at /build/.../crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - @code{addr2line} has a number of other useful options: - - @table @code - @item --functions - to get the function name corresponding to any location - - @item --demangle=gnat - to use the @b{gnat} decoding mode for the function names. Note that - for binutils version 2.9.x the option is simply @code{--demangle}. - @end table - - @smallexample - $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b - 0x40139c 0x401335 0x4011c4 0x4011f1 - - 00401373 in stb.p1 at d:/stb/stb.adb:5 - 0040138B in stb.p2 at d:/stb/stb.adb:10 - 0040139C in stb at d:/stb/stb.adb:14 - 00401335 in main at d:/stb/b~stb.adb:104 - 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200 - 004011F1 in at /build/.../crt1.c:222 - @end smallexample - - @noindent - From this traceback we can see that the exception was raised in - @file{stb.adb} at line 5, which was reached from a procedure call in - @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file, - which contains the call to the main program. - @pxref{Running gnatbind}. The remaining entries are assorted runtime routines, - and the output will vary from platform to platform. - - @noindent - It is also possible to use @code{GDB} with these traceback addresses to debug - the program. For example, we can break at a given code location, as reported - in the stack traceback: - - @smallexample - $ gdb -nw stb - @noindent - Furthermore, this feature is not implemented inside Windows DLL. Only - the non-symbolic traceback is reported in this case. - - (gdb) break *0x401373 - Breakpoint 1 at 0x401373: file stb.adb, line 5. - @end smallexample - - @noindent - It is important to note that the stack traceback addresses - do not change when debug information is included. This is particularly useful - because it makes it possible to release software without debug information (to - minimize object size), get a field report that includes a stack traceback - whenever an internal bug occurs, and then be able to retrieve the sequence - of calls with the same program compiled with debug information. - - @node Tracebacks From Exception Occurrences (non-symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @noindent - Non-symbolic tracebacks are obtained by using the @code{-E} binder argument. - The stack traceback is attached to the exception information string, and can - be retrieved in an exception handler within the Ada program, by means of the - Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with Ada.Exceptions; - - procedure STB is - - use Ada; - use Ada.Exceptions; - - procedure P1 is - K : Positive := 1; - begin - K := K - 1; - exception - when E : others => - Text_IO.Put_Line (Exception_Information (E)); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @noindent - This program will output: - - @smallexample - $ stb - - Exception name: CONSTRAINT_ERROR - Message: stb.adb:12 - Call stack traceback locations: - 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 - @end smallexample - - @node Tracebacks From Anywhere in a Program (non-symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is also possible to retrieve a stack traceback from anywhere in a - program. For this you need to - use the @code{GNAT.Traceback} API. This package includes a procedure called - @code{Call_Chain} that computes a complete stack traceback, as well as useful - display procedures described below. It is not necessary to use the - @code{-E gnatbind} option in this case, because the stack traceback mechanism - is invoked explicitly. - - @noindent - In the following example we compute a traceback at a specific location in - the program, and we display it using @code{GNAT.Debug_Utilities.Image} to - convert addresses to strings: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Debug_Utilities; - - procedure STB is - - use Ada; - use GNAT; - use GNAT.Traceback; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - - Text_IO.Put ("In STB.P1 : "); - - for K in 1 .. Len loop - Text_IO.Put (Debug_Utilities.Image (TB (K))); - Text_IO.Put (' '); - end loop; - - Text_IO.New_Line; - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake stb - $ stb - - In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# - 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# - @end smallexample - - @node Symbolic Traceback - @subsection Symbolic Traceback - @cindex traceback, symbolic - - @noindent - A symbolic traceback is a stack traceback in which procedure names are - associated with each code location. - - @noindent - Note that this feature is not supported on all platforms. See - @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete - list of currently supported platforms. - - @noindent - Note that the symbolic traceback requires that the program be compiled - with debug information. If it is not compiled with debug information - only the non-symbolic information will be valid. - - @menu - * Tracebacks From Exception Occurrences (symbolic):: - * Tracebacks From Anywhere in a Program (symbolic):: - @end menu - - @node Tracebacks From Exception Occurrences (symbolic) - @subsubsection Tracebacks From Exception Occurrences - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback.Symbolic; - - procedure STB is - - procedure P1 is - begin - raise Constraint_Error; - end P1; - - procedure P2 is - begin - P1; - end P2; - - procedure P3 is - begin - P2; - end P3; - - begin - P3; - exception - when E : others => - Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); - end STB; - @end group - @end cartouche - @end smallexample - - @smallexample - $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl - $ stb - - 0040149F in stb.p1 at stb.adb:8 - 004014B7 in stb.p2 at stb.adb:13 - 004014CF in stb.p3 at stb.adb:18 - 004015DD in ada.stb at stb.adb:22 - 00401461 in main at b~stb.adb:168 - 004011C4 in __mingw_CRTStartup at crt1.c:200 - 004011F1 in mainCRTStartup at crt1.c:222 - 77E892A4 in ?? at ??:0 - @end smallexample - - @noindent - The exact sequence of linker options may vary from platform to platform. - The above @code{-largs} section is for Windows platforms. By contrast, - under Unix there is no need for the @code{-largs} section. - Differences across platforms are due to details of linker implementation. - - @node Tracebacks From Anywhere in a Program (symbolic) - @subsubsection Tracebacks From Anywhere in a Program - - @noindent - It is possible to get a symbolic stack traceback - from anywhere in a program, just as for non-symbolic tracebacks. - The first step is to obtain a non-symbolic - traceback, and then call @code{Symbolic_Traceback} to compute the symbolic - information. Here is an example: - - @smallexample - @cartouche - @group - with Ada.Text_IO; - with GNAT.Traceback; - with GNAT.Traceback.Symbolic; - - procedure STB is - - use Ada; - use GNAT.Traceback; - use GNAT.Traceback.Symbolic; - - procedure P1 is - TB : Tracebacks_Array (1 .. 10); - -- We are asking for a maximum of 10 stack frames. - Len : Natural; - -- Len will receive the actual number of stack frames returned. - begin - Call_Chain (TB, Len); - Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); - end P1; - - procedure P2 is - begin - P1; - end P2; - - begin - P2; - end STB; - @end group - @end cartouche - @end smallexample - - - @node Inline Assembler - @chapter Inline Assembler - - @noindent - If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program. First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT. However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler. The Inline Assembler approach offers a number of advantages, including the following: - - @itemize @bullet - @item No need to use non-Ada tools - @item Consistent interface over different targets - @item Automatic usage of the proper calling conventions - @item Access to Ada constants and variables - @item Definition of intrinsic routines - @item Possibility of inlining a subprogram comprising assembler code - @item Code optimizer can take Inline Assembler code into account - @end itemize - - This chapter presents a series of examples to show you how to use the Inline Assembler. Although it focuses on the Intel x86, the general approach applies also to other processors. It is assumed that you are familiar with Ada and with assembly language programming. - - @menu - * Basic Assembler Syntax:: - * A Simple Example of Inline Assembler:: - * Output Variables in Inline Assembler:: - * Input Variables in Inline Assembler:: - * Inlining Inline Assembler Code:: - * Other Asm Functionality:: - * A Complete Example:: - @end menu - - @c --------------------------------------------------------------------------- - @node Basic Assembler Syntax - @section Basic Assembler Syntax - - @noindent - The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a - language that descends from the AT&T Unix assembler @emph{as} (and which is often - referred to as ``AT&T syntax''). - The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions. - See the gcc @emph{as} and @emph{gas} (an @emph{as} macro - pre-processor) documentation for further information. - - @table @asis - @item Register names - gcc / @emph{as}: Prefix with ``%''; for example @code{%eax} - @* - Intel: No extra punctuation; for example @code{eax} - - @item Immediate operand - gcc / @emph{as}: Prefix with ``$''; for example @code{$4} - @* - Intel: No extra punctuation; for example @code{4} - - @item Address - gcc / @emph{as}: Prefix with ``$''; for example @code{$loc} - @* - Intel: No extra punctuation; for example @code{loc} - - @item Memory contents - gcc / @emph{as}: No extra punctuation; for example @code{loc} - @* - Intel: Square brackets; for example @code{[loc]} - - @item Register contents - gcc / @emph{as}: Parentheses; for example @code{(%eax)} - @* - Intel: Square brackets; for example @code{[eax]} - - @item Hexadecimal numbers - gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} - @* - Intel: Trailing ``h''; for example @code{A0h} - - @item Operand size - gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word - @* - Intel: Implicit, deduced by assembler; for example @code{mov} - - @item Instruction repetition - gcc / @emph{as}: Split into two lines; for example - @* - @code{rep} - @* - @code{stosl} - @* - Intel: Keep on one line; for example @code{rep stosl} - - @item Order of operands - gcc / @emph{as}: Source first; for example @code{movw $4, %eax} - @* - Intel: Destination first; for example @code{mov eax, 4} - @end table - - @c --------------------------------------------------------------------------- - @node A Simple Example of Inline Assembler - @section A Simple Example of Inline Assembler - - @noindent - The following example will generate a single assembly language statement, @code{nop}, which does nothing. Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility. - - @smallexample - @group - with System.Machine_Code; use System.Machine_Code; - procedure Nothing is - begin - Asm ("nop"); - end Nothing; - @end group - @end smallexample - - @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction. - @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions. - - The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}. - - Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}. You can build the executable in the usual way: - @smallexample - gnatmake nothing - @end smallexample - However, the interesting aspect of this example is not its run-time behavior but rather the - generated assembly code. To see this output, invoke the compiler as follows: - @smallexample - gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb} - @end smallexample - where the options are: - - @table @code - @item -c - compile only (no bind or link) - @item -S - generate assembler listing - @item -fomit-frame-pointer - do not set up separate stack frames - @item -gnatp - do not add runtime checks - @end table - - This gives a human-readable assembler version of the code. The resulting - file will have the same name as the Ada source file, but with a @code{.s} extension. - In our example, the file @file{nothing.s} has the following contents: - - @smallexample - @group - .file "nothing.adb" - gcc2_compiled.: - ___gnu_compiled_ada: - .text - .align 4 - .globl __ada_nothing - __ada_nothing: - #APP - nop - #NO_APP - jmp L1 - .align 2,0x90 - L1: - ret - @end group - @end smallexample - - The assembly code you included is clearly indicated by - the compiler, between the @code{#APP} and @code{#NO_APP} - delimiters. The character before the 'APP' and 'NOAPP' - can differ on different targets. For example, Linux uses '#APP' while - on NT you will see '/APP'. - - If you make a mistake in your assembler code (such as using the - wrong size modifier, or using a wrong operand for the instruction) GNAT - will report this error in a temporary file, which will be deleted when - the compilation is finished. Generating an assembler file will help - in such cases, since you can assemble this file separately using the - @emph{as} assembler that comes with gcc. - - Assembling the file using the command - - @smallexample - as @file{nothing.s} - @end smallexample - @noindent - will give you error messages whose lines correspond to the assembler - input file, so you can easily find and correct any mistakes you made. - If there are no errors, @emph{as} will generate an object file @file{nothing.out}. - - @c --------------------------------------------------------------------------- - @node Output Variables in Inline Assembler - @section Output Variables in Inline Assembler - - @noindent - The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements. - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags; - @end group - @end smallexample - - In order to have a nicely aligned assembly listing, we have separated - multiple assembler statements in the Asm template string with linefeed (ASCII.LF) - and horizontal tab (ASCII.HT) characters. The resulting section of the - assembly output file is: - - @smallexample - @group - #APP - pushfl - popl %eax - movl %eax, -40(%ebp) - #NO_APP - @end group - @end smallexample - - It would have been legal to write the Asm invocation as: - - @smallexample - Asm ("pushfl popl %%eax movl %%eax, %0") - @end smallexample - - but in the generated assembler file, this would come out as: - - @smallexample - #APP - pushfl popl %eax movl %eax, -40(%ebp) - #NO_APP - @end smallexample - - which is not so convenient for the human reader. - - We use Ada comments - at the end of each line to explain what the assembler instructions - actually do. This is a useful convention. - - When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign. Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}. In the generated assembly code, one of the percent signs will be stripped off. - - Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}. - An output variable is illustrated in - the third statement in the Asm template string: - @smallexample - movl %%eax, %0 - @end smallexample - The intent is to store the contents of the eax register in a variable that can be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization. The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable. - - Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}: - @smallexample - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end smallexample - - The output is defined by the @code{Asm_Output} attribute of the target type; the general format is - @smallexample - Type'Asm_Output (constraint_string, variable_name) - @end smallexample - - The constraint string directs the compiler how - to store/access the associated variable. In the example - @smallexample - Unsigned_32'Asm_Output ("=m", Flags); - @end smallexample - the @code{"m"} (memory) constraint tells the compiler that the variable - @code{Flags} should be stored in a memory variable, thus preventing - the optimizer from keeping it in a register. In contrast, - @smallexample - Unsigned_32'Asm_Output ("=r", Flags); - @end smallexample - uses the @code{"r"} (register) constraint, telling the compiler to - store the variable in a register. - - If the constraint is preceded by the equal character (@strong{=}), it tells the - compiler that the variable will be used to store data into it. - - In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer - to choose whatever it deems best. - - There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following: - - @table @code - @item = - output constraint - @item g - global (i.e. can be stored anywhere) - @item m - in memory - @item I - a constant - @item a - use eax - @item b - use ebx - @item c - use ecx - @item d - use edx - @item S - use esi - @item D - use edi - @item r - use one of eax, ebx, ecx or edx - @item q - use one of eax, ebx, ecx, edx, esi or edi - @end table - - The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string. - - You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer. Thus in - @smallexample - @group - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax" & LF & HT & -- load eax with flags - "movl %%eax, %0", -- store flags in variable - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - @end group - @end smallexample - @noindent - @code{%0} will be replaced in the expanded code by the appropriate operand, - whatever - the compiler decided for the @code{Flags} variable. - - In general, you may have any number of output variables: - @itemize @bullet - @item - Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. - @item - Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes - @end itemize - - For example: - @smallexample - @group - Asm ("movl %%eax, %0" & LF & HT & - "movl %%ebx, %1" & LF & HT & - "movl %%ecx, %2", - Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A - Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B - Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C - @end group - @end smallexample - @noindent - where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program. - - As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_2 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "popl %%eax", -- save flags in eax - Outputs => Unsigned_32'Asm_Output ("=a", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_2; - @end group - @end smallexample - - @noindent - The @code{"a"} constraint tells the compiler that the @code{Flags} - variable will come from the eax register. Here is the resulting code: - - @smallexample - @group - #APP - pushfl - popl %eax - #NO_APP - movl %eax,-40(%ebp) - @end group - @end smallexample - - @noindent - The compiler generated the store of eax into Flags after - expanding the assembler code. - - Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Get_Flags_3 is - Flags : Unsigned_32; - use ASCII; - begin - Asm ("pushfl" & LF & HT & -- push flags on stack - "pop %0", -- save flags in Flags - Outputs => Unsigned_32'Asm_Output ("=g", Flags)); - Put_Line ("Flags register:" & Flags'Img); - end Get_Flags_3; - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Input Variables in Inline Assembler - @section Input Variables in Inline Assembler - - @noindent - The example in this section illustrates how to specify the source operands for assembly language statements. The program simply increments its input value by 1: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Incr (Value); - Put_Line ("Value after is" & Value'Img); - end Increment; - @end group - @end smallexample - - The @code{Outputs} parameter to @code{Asm} specifies - that the result will be in the eax register and that it is to be stored in the @code{Result} - variable. - - The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an - @code{Asm_Input} attribute. The - @code{"="} constraint, indicating an output value, is not present. - - You can have multiple input variables, in the same way that you can have more - than one output variable. - - The parameter count (%0, %1) etc, now starts at the first input - statement, and continues with the output statements. - When both parameters use the same variable, the - compiler will treat them as the same %n operand, which is the case here. - - Just as the @code{Outputs} parameter causes the register to be stored into the - target variable after execution of the assembler statements, so does the - @code{Inputs} parameter cause its variable to be loaded into the register before execution - of the - assembler statements. - - Thus the effect of the @code{Asm} invocation is: - @enumerate - @item load the 32-bit value of @code{Value} into eax - @item execute the @code{incl %eax} instruction - @item store the contents of eax into the @code{Result} variable - @end enumerate - - The resulting assembler file (with @code{-O2} optimization) contains: - @smallexample - @group - _increment__incr.1: - subl $4,%esp - movl 8(%esp),%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - movl %ecx,(%esp) - addl $4,%esp - ret - @end group - @end smallexample - - @c --------------------------------------------------------------------------- - @node Inlining Inline Assembler Code - @section Inlining Inline Assembler Code - - @noindent - For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame) - can be significant, compared to the amount of code in the subprogram body. - A solution is to apply Ada's @code{Inline} pragma to the subprogram, - which directs the compiler to expand invocations of the subprogram at the point(s) - of call, instead of setting up a stack frame for out-of-line calls. - Here is the resulting program: - - @smallexample - @group - with Interfaces; use Interfaces; - with Ada.Text_IO; use Ada.Text_IO; - with System.Machine_Code; use System.Machine_Code; - procedure Increment_2 is - - function Incr (Value : Unsigned_32) return Unsigned_32 is - Result : Unsigned_32; - begin - Asm ("incl %0", - Inputs => Unsigned_32'Asm_Input ("a", Value), - Outputs => Unsigned_32'Asm_Output ("=a", Result)); - return Result; - end Incr; - pragma Inline (Increment); - - Value : Unsigned_32; - - begin - Value := 5; - Put_Line ("Value before is" & Value'Img); - Value := Increment (Value); - Put_Line ("Value after is" & Value'Img); - end Increment_2; - @end group - @end smallexample - - Compile the program with both optimization (@code{-O2}) and inlining - enabled (@option{-gnatpn} instead of @option{-gnatp}). - - The @code{Incr} function is still compiled as usual, but at the - point in @code{Increment} where our function used to be called: - - @smallexample - @group - pushl %edi - call _increment__incr.1 - @end group - @end smallexample - - @noindent - the code for the function body directly appears: - - @smallexample - @group - movl %esi,%eax - #APP - incl %eax - #NO_APP - movl %eax,%edx - @end group - @end smallexample - - @noindent - thus saving the overhead of stack frame setup and an out-of-line call. - - @c --------------------------------------------------------------------------- - @node Other Asm Functionality - @section Other @code{Asm} Functionality - - @noindent - This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations. - - @menu - * The Clobber Parameter:: - * The Volatile Parameter:: - @end menu - - @c --------------------------------------------------------------------------- - @node The Clobber Parameter - @subsection The @code{Clobber} Parameter - - @noindent - One of the dangers of intermixing assembly language and a compiled language such as Ada is - that the compiler needs to be aware of which registers are being used by the assembly code. - In some cases, such as the earlier examples, the constraint string is sufficient to - indicate register usage (e.g. "a" for the eax register). But more generally, the - compiler needs an explicit identification of the registers that are used by the Inline - Assembly statements. - - Using a register that the compiler doesn't know about - could be a side effect of an instruction (like @code{mull} - storing its result in both eax and edx). - It can also arise from explicit register usage in your - assembly code; for example: - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out)); - @end group - @end smallexample - @noindent - where the compiler (since it does not analyze the @code{Asm} template string) - does not know you are using the ebx register. - - In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, - to identify the registers that will be used by your assembly code: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx"); - @end group - @end smallexample - - The Clobber parameter is a static string expression specifying the - register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign. - Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"} - - The @code{Clobber} parameter has several additional uses: - @enumerate - @item Use the "register" name @code{cc} to indicate that flags might have changed - @item Use the "register" name @code{memory} if you changed a memory location - @end enumerate - - @c --------------------------------------------------------------------------- - @node The Volatile Parameter - @subsection The @code{Volatile} Parameter - @cindex Volatile parameter - - @noindent - Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects. - For example, when - an @code{Asm} invocation with an input variable is inside a loop, the compiler might move - the loading of the input variable outside the loop, regarding it as a - one-time initialization. - - If this effect is not desired, you can disable such optimizations by setting the - @code{Volatile} parameter to @code{True}; for example: - - @smallexample - @group - Asm ("movl %0, %%ebx" & LF & HT & - "movl %%ebx, %1", - Inputs => Unsigned_32'Asm_Input ("g", Var_In), - Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), - Clobber => "ebx", - Volatile => True); - @end group - @end smallexample - - By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs} - parameter. - - Although setting @code{Volatile} to @code{True} prevents unwanted optimizations, - it will also disable other optimizations that might be important for efficiency. - In general, you should set @code{Volatile} to @code{True} only if the compiler's - optimizations have created problems. - - @c --------------------------------------------------------------------------- - @node A Complete Example - @section A Complete Example - - @noindent - This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler - capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}. - The package declares a collection of functions that detect the properties of the 32-bit - x86 processor that is running the program. The main procedure invokes these functions - and displays the information. - - The Intel_CPU package could be enhanced by adding functions to - detect the type of x386 co-processor, the processor caching options and - special operations such as the SIMD extensions. - - Although the Intel_CPU package has been written for 32-bit Intel - compatible CPUs, it is OS neutral. It has been tested on DOS, - Windows/NT and Linux. - - @menu - * Check_CPU Procedure:: - * Intel_CPU Package Specification:: - * Intel_CPU Package Body:: - @end menu - - @c --------------------------------------------------------------------------- - @node Check_CPU Procedure - @subsection @code{Check_CPU} Procedure - @cindex Check_CPU procedure - - @smallexample - --------------------------------------------------------------------- - -- -- - -- Uses the Intel_CPU package to identify the CPU the program is -- - -- running on, and some of the features it supports. -- - -- -- - --------------------------------------------------------------------- - - with Intel_CPU; -- Intel CPU detection functions - with Ada.Text_IO; -- Standard text I/O - with Ada.Command_Line; -- To set the exit status - - procedure Check_CPU is - - Type_Found : Boolean := False; - -- Flag to indicate that processor was identified - - Features : Intel_CPU.Processor_Features; - -- The processor features - - Signature : Intel_CPU.Processor_Signature; - -- The processor type signature - - begin - - ----------------------------------- - -- Display the program banner. -- - ----------------------------------- - - Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name & - ": check Intel CPU version and features, v1.0"); - Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever"); - Ada.Text_IO.New_Line; - - ----------------------------------------------------------------------- - -- We can safely start with the assumption that we are on at least -- - -- a x386 processor. If the CPUID instruction is present, then we -- - -- have a later processor type. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Has_CPUID = False then - - -- No CPUID instruction, so we assume this is indeed a x386 - -- processor. We can still check if it has a FP co-processor. - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line - ("x386-type processor with a FP co-processor"); - else - Ada.Text_IO.Put_Line - ("x386-type processor without a FP co-processor"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check for CPUID - - ----------------------------------------------------------------------- - -- If CPUID is supported, check if this is a true Intel processor, -- - -- if it is not, display a warning. -- - ----------------------------------------------------------------------- - - if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then - Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor"); - Ada.Text_IO.Put_Line ("*** Some information may be incorrect"); - end if; -- check if Intel - - ---------------------------------------------------------------------- - -- With the CPUID instruction present, we can assume at least a -- - -- x486 processor. If the CPUID support level is < 1 then we have -- - -- to leave it at that. -- - ---------------------------------------------------------------------- - - if Intel_CPU.CPUID_Level < 1 then - - -- Ok, this is a x486 processor. we still can get the Vendor ID - Ada.Text_IO.Put_Line ("x486-type processor"); - Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID); - - -- We can also check if there is a FPU present - if Intel_CPU.Has_FPU then - Ada.Text_IO.Put_Line ("Floating-Point support"); - else - Ada.Text_IO.Put_Line ("No Floating-Point support"); - end if; -- check for FPU - - -- Program done - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - return; - - end if; -- check CPUID level - - --------------------------------------------------------------------- - -- With a CPUID level of 1 we can use the processor signature to -- - -- determine it's exact type. -- - --------------------------------------------------------------------- - - Signature := Intel_CPU.Signature; - - ---------------------------------------------------------------------- - -- Ok, now we go into a lot of messy comparisons to get the -- - -- processor type. For clarity, no attememt to try to optimize the -- - -- comparisons has been made. Note that since Intel_CPU does not -- - -- support getting cache info, we cannot distinguish between P5 -- - -- and Celeron types yet. -- - ---------------------------------------------------------------------- - - -- x486SL - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486SL processor"); - end if; - - -- x486DX2 Write-Back - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#0111# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor"); - end if; - - -- x486DX4 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 processor"); - end if; - - -- x486DX4 Overdrive - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0100# and - Signature.Model = 2#1000# then - Type_Found := True; - Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor"); - end if; - - -- Pentium (60, 66) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium processor (60, 66)"); - end if; - - -- Pentium (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive (60, 66) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)"); - end if; - - -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0010# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)"); - end if; - - -- Pentium OverDrive processor for x486 processor-based systems - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor for x486 processor-based systems"); - end if; - - -- Pentium processor with MMX technology (166, 200) - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium processor with MMX technology (166, 200)"); - end if; - - -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133) - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0101# and - Signature.Model = 2#0100# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium OverDrive processor with MMX " & - "technology for Pentium processor (75, 90, 100, 120, 133)"); - end if; - - -- Pentium Pro processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0001# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro processor"); - end if; - - -- Pentium II processor, model 3 - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium II processor, model 3"); - end if; - - -- Pentium II processor, model 5 or Celeron processor - if Signature.Processor_Type = 2#00# and - Signature.Family = 2#0110# and - Signature.Model = 2#0101# then - Type_Found := True; - Ada.Text_IO.Put_Line - ("Pentium II processor, model 5 or Celeron processor"); - end if; - - -- Pentium Pro OverDrive processor - if Signature.Processor_Type = 2#01# and - Signature.Family = 2#0110# and - Signature.Model = 2#0011# then - Type_Found := True; - Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor"); - end if; - - -- If no type recognized, we have an unknown. Display what - -- we _do_ know - if Type_Found = False then - Ada.Text_IO.Put_Line ("Unknown processor"); - end if; - - ----------------------------------------- - -- Display processor stepping level. -- - ----------------------------------------- - - Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img); - - --------------------------------- - -- Display vendor ID string. -- - --------------------------------- - - Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID); - - ------------------------------------ - -- Get the processors features. -- - ------------------------------------ - - Features := Intel_CPU.Features; - - ----------------------------- - -- Check for a FPU unit. -- - ----------------------------- - - if Features.FPU = True then - Ada.Text_IO.Put_Line ("Floating-Point unit available"); - else - Ada.Text_IO.Put_Line ("no Floating-Point unit"); - end if; -- check for FPU - - -------------------------------- - -- List processor features. -- - -------------------------------- - - Ada.Text_IO.Put_Line ("Supported features: "); - - -- Virtual Mode Extension - if Features.VME = True then - Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension"); - end if; - - -- Debugging Extension - if Features.DE = True then - Ada.Text_IO.Put_Line (" DE - Debugging Extension"); - end if; - - -- Page Size Extension - if Features.PSE = True then - Ada.Text_IO.Put_Line (" PSE - Page Size Extension"); - end if; - - -- Time Stamp Counter - if Features.TSC = True then - Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter"); - end if; - - -- Model Specific Registers - if Features.MSR = True then - Ada.Text_IO.Put_Line (" MSR - Model Specific Registers"); - end if; - - -- Physical Address Extension - if Features.PAE = True then - Ada.Text_IO.Put_Line (" PAE - Physical Address Extension"); - end if; - - -- Machine Check Extension - if Features.MCE = True then - Ada.Text_IO.Put_Line (" MCE - Machine Check Extension"); - end if; - - -- CMPXCHG8 instruction supported - if Features.CX8 = True then - Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction"); - end if; - - -- on-chip APIC hardware support - if Features.APIC = True then - Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support"); - end if; - - -- Fast System Call - if Features.SEP = True then - Ada.Text_IO.Put_Line (" SEP - Fast System Call"); - end if; - - -- Memory Type Range Registers - if Features.MTRR = True then - Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers"); - end if; - - -- Page Global Enable - if Features.PGE = True then - Ada.Text_IO.Put_Line (" PGE - Page Global Enable"); - end if; - - -- Machine Check Architecture - if Features.MCA = True then - Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture"); - end if; - - -- Conditional Move Instruction Supported - if Features.CMOV = True then - Ada.Text_IO.Put_Line - (" CMOV - Conditional Move Instruction Supported"); - end if; - - -- Page Attribute Table - if Features.PAT = True then - Ada.Text_IO.Put_Line (" PAT - Page Attribute Table"); - end if; - - -- 36-bit Page Size Extension - if Features.PSE_36 = True then - Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension"); - end if; - - -- MMX technology supported - if Features.MMX = True then - Ada.Text_IO.Put_Line (" MMX - MMX technology supported"); - end if; - - -- Fast FP Save and Restore - if Features.FXSR = True then - Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore"); - end if; - - --------------------- - -- Program done. -- - --------------------- - - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success); - - exception - - when others => - Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); - raise; - - end Check_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Specification - @subsection @code{Intel_CPU} Package Specification - @cindex Intel_CPU package specification - - @smallexample - ------------------------------------------------------------------------- - -- -- - -- file: intel_cpu.ads -- - -- -- - -- ********************************************* -- - -- * WARNING: for 32-bit Intel processors only * -- - -- ********************************************* -- - -- -- - -- This package contains a number of subprograms that are useful in -- - -- determining the Intel x86 CPU (and the features it supports) on -- - -- which the program is running. -- - -- -- - -- The package is based upon the information given in the Intel -- - -- Application Note AP-485: "Intel Processor Identification and the -- - -- CPUID Instruction" as of April 1998. This application note can be -- - -- found on www.intel.com. -- - -- -- - -- It currently deals with 32-bit processors only, will not detect -- - -- features added after april 1998, and does not guarantee proper -- - -- results on Intel-compatible processors. -- - -- -- - -- Cache info and x386 fpu type detection are not supported. -- - -- -- - -- This package does not use any privileged instructions, so should -- - -- work on any OS running on a 32-bit Intel processor. -- - -- -- - ------------------------------------------------------------------------- - - with Interfaces; use Interfaces; - -- for using unsigned types - - with System.Machine_Code; use System.Machine_Code; - -- for using inline assembler code - - with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; - -- for inserting control characters - - package Intel_CPU is - - ---------------------- - -- Processor bits -- - ---------------------- - - subtype Num_Bits is Natural range 0 .. 31; - -- the number of processor bits (32) - - -------------------------- - -- Processor register -- - -------------------------- - - -- define a processor register type for easy access to - -- the individual bits - - type Processor_Register is array (Num_Bits) of Boolean; - pragma Pack (Processor_Register); - for Processor_Register'Size use 32; - - ------------------------- - -- Unsigned register -- - ------------------------- - - -- define a processor register type for easy access to - -- the individual bytes - - type Unsigned_Register is - record - L1 : Unsigned_8; - H1 : Unsigned_8; - L2 : Unsigned_8; - H2 : Unsigned_8; - end record; - - for Unsigned_Register use - record - L1 at 0 range 0 .. 7; - H1 at 0 range 8 .. 15; - L2 at 0 range 16 .. 23; - H2 at 0 range 24 .. 31; - end record; - - for Unsigned_Register'Size use 32; - - --------------------------------- - -- Intel processor vendor ID -- - --------------------------------- - - Intel_Processor : constant String (1 .. 12) := "GenuineIntel"; - -- indicates an Intel manufactured processor - - ------------------------------------ - -- Processor signature register -- - ------------------------------------ - - -- a register type to hold the processor signature - - type Processor_Signature is - record - Stepping : Natural range 0 .. 15; - Model : Natural range 0 .. 15; - Family : Natural range 0 .. 15; - Processor_Type : Natural range 0 .. 3; - Reserved : Natural range 0 .. 262143; - end record; - - for Processor_Signature use - record - Stepping at 0 range 0 .. 3; - Model at 0 range 4 .. 7; - Family at 0 range 8 .. 11; - Processor_Type at 0 range 12 .. 13; - Reserved at 0 range 14 .. 31; - end record; - - for Processor_Signature'Size use 32; - - ----------------------------------- - -- Processor features register -- - ----------------------------------- - - -- a processor register to hold the processor feature flags - - type Processor_Features is - record - FPU : Boolean; -- floating point unit on chip - VME : Boolean; -- virtual mode extension - DE : Boolean; -- debugging extension - PSE : Boolean; -- page size extension - TSC : Boolean; -- time stamp counter - MSR : Boolean; -- model specific registers - PAE : Boolean; -- physical address extension - MCE : Boolean; -- machine check extension - CX8 : Boolean; -- cmpxchg8 instruction - APIC : Boolean; -- on-chip apic hardware - Res_1 : Boolean; -- reserved for extensions - SEP : Boolean; -- fast system call - MTRR : Boolean; -- memory type range registers - PGE : Boolean; -- page global enable - MCA : Boolean; -- machine check architecture - CMOV : Boolean; -- conditional move supported - PAT : Boolean; -- page attribute table - PSE_36 : Boolean; -- 36-bit page size extension - Res_2 : Natural range 0 .. 31; -- reserved for extensions - MMX : Boolean; -- MMX technology supported - FXSR : Boolean; -- fast FP save and restore - Res_3 : Natural range 0 .. 127; -- reserved for extensions - end record; - - for Processor_Features use - record - FPU at 0 range 0 .. 0; - VME at 0 range 1 .. 1; - DE at 0 range 2 .. 2; - PSE at 0 range 3 .. 3; - TSC at 0 range 4 .. 4; - MSR at 0 range 5 .. 5; - PAE at 0 range 6 .. 6; - MCE at 0 range 7 .. 7; - CX8 at 0 range 8 .. 8; - APIC at 0 range 9 .. 9; - Res_1 at 0 range 10 .. 10; - SEP at 0 range 11 .. 11; - MTRR at 0 range 12 .. 12; - PGE at 0 range 13 .. 13; - MCA at 0 range 14 .. 14; - CMOV at 0 range 15 .. 15; - PAT at 0 range 16 .. 16; - PSE_36 at 0 range 17 .. 17; - Res_2 at 0 range 18 .. 22; - MMX at 0 range 23 .. 23; - FXSR at 0 range 24 .. 24; - Res_3 at 0 range 25 .. 31; - end record; - - for Processor_Features'Size use 32; - - ------------------- - -- Subprograms -- - ------------------- - - function Has_FPU return Boolean; - -- return True if a FPU is found - -- use only if CPUID is not supported - - function Has_CPUID return Boolean; - -- return True if the processor supports the CPUID instruction - - function CPUID_Level return Natural; - -- return the CPUID support level (0, 1 or 2) - -- can only be called if the CPUID instruction is supported - - function Vendor_ID return String; - -- return the processor vendor identification string - -- can only be called if the CPUID instruction is supported - - function Signature return Processor_Signature; - -- return the processor signature - -- can only be called if the CPUID instruction is supported - - function Features return Processor_Features; - -- return the processors features - -- can only be called if the CPUID instruction is supported - - private - - ------------------------ - -- EFLAGS bit names -- - ------------------------ - - ID_Flag : constant Num_Bits := 21; - -- ID flag bit - - end Intel_CPU; - @end smallexample - - @c --------------------------------------------------------------------------- - @node Intel_CPU Package Body - @subsection @code{Intel_CPU} Package Body - @cindex Intel_CPU package body - - @smallexample - package body Intel_CPU is - - --------------------------- - -- Detect FPU presence -- - --------------------------- - - -- There is a FPU present if we can set values to the FPU Status - -- and Control Words. - - function Has_FPU return Boolean is - - Register : Unsigned_16; - -- processor register to store a word - - begin - - -- check if we can change the status word - Asm ( - - -- the assembler code - "finit" & LF & HT & -- reset status word - "movw $0x5A5A, %%ax" & LF & HT & -- set value status word - "fnstsw %0" & LF & HT & -- save status word - "movw %%ax, %0", -- store status word - - -- output stored in Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register), - - -- tell compiler that we used eax - Clobber => "eax"); - - -- if the status word is zero, there is no FPU - if Register = 0 then - return False; -- no status word - end if; -- check status word value - - -- check if we can get the control word - Asm ( - - -- the assembler code - "fnstcw %0", -- save the control word - - -- output into Register - -- register must be a memory location - Outputs => Unsigned_16'Asm_output ("=m", Register)); - - -- check the relevant bits - if (Register and 16#103F#) /= 16#003F# then - return False; -- no control word - end if; -- check control word value - - -- FPU found - return True; - - end Has_FPU; - - -------------------------------- - -- Detect CPUID instruction -- - -------------------------------- - - -- The processor supports the CPUID instruction if it is possible - -- to change the value of ID flag bit in the EFLAGS register. - - function Has_CPUID return Boolean is - - Original_Flags, Modified_Flags : Processor_Register; - -- EFLAG contents before and after changing the ID flag - - begin - - -- try flipping the ID flag in the EFLAGS register - Asm ( - - -- the assembler code - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %%eax" & LF & HT & -- pop EFLAGS into eax - "movl %%eax, %0" & LF & HT & -- save EFLAGS content - "xor $0x200000, %%eax" & LF & HT & -- flip ID flag - "push %%eax" & LF & HT & -- push EFLAGS on stack - "popfl" & LF & HT & -- load EFLAGS register - "pushfl" & LF & HT & -- push EFLAGS on stack - "pop %1", -- save EFLAGS content - - -- output values, may be anything - -- Original_Flags is %0 - -- Modified_Flags is %1 - Outputs => - (Processor_Register'Asm_output ("=g", Original_Flags), - Processor_Register'Asm_output ("=g", Modified_Flags)), - - -- tell compiler eax is destroyed - Clobber => "eax"); - - -- check if CPUID is supported - if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then - return True; -- ID flag was modified - else - return False; -- ID flag unchanged - end if; -- check for CPUID - - end Has_CPUID; - - ------------------------------- - -- Get CPUID support level -- - ------------------------------- - - function CPUID_Level return Natural is - - Level : Unsigned_32; - -- returned support level - - begin - - -- execute CPUID, storing the results in the Level register - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero is stored in eax - -- returning the support level in eax - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- eax is stored in Level - Outputs => Unsigned_32'Asm_output ("=a", Level), - - -- tell compiler ebx, ecx and edx registers are destroyed - Clobber => "ebx, ecx, edx"); - - -- return the support level - return Natural (Level); - - end CPUID_Level; - - -------------------------------- - -- Get CPU Vendor ID String -- - -------------------------------- - - -- The vendor ID string is returned in the ebx, ecx and edx register - -- after executing the CPUID instruction with eax set to zero. - -- In case of a true Intel processor the string returned is - -- "GenuineIntel" - - function Vendor_ID return String is - - Ebx, Ecx, Edx : Unsigned_Register; - -- registers containing the vendor ID string - - Vendor_ID : String (1 .. 12); - -- the vendor ID string - - begin - - -- execute CPUID, storing the results in the processor registers - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- zero stored in eax - -- vendor ID string returned in ebx, ecx and edx - Inputs => Unsigned_32'Asm_input ("a", 0), - - -- ebx is stored in Ebx - -- ecx is stored in Ecx - -- edx is stored in Edx - Outputs => (Unsigned_Register'Asm_output ("=b", Ebx), - Unsigned_Register'Asm_output ("=c", Ecx), - Unsigned_Register'Asm_output ("=d", Edx))); - - -- now build the vendor ID string - Vendor_ID( 1) := Character'Val (Ebx.L1); - Vendor_ID( 2) := Character'Val (Ebx.H1); - Vendor_ID( 3) := Character'Val (Ebx.L2); - Vendor_ID( 4) := Character'Val (Ebx.H2); - Vendor_ID( 5) := Character'Val (Edx.L1); - Vendor_ID( 6) := Character'Val (Edx.H1); - Vendor_ID( 7) := Character'Val (Edx.L2); - Vendor_ID( 8) := Character'Val (Edx.H2); - Vendor_ID( 9) := Character'Val (Ecx.L1); - Vendor_ID(10) := Character'Val (Ecx.H1); - Vendor_ID(11) := Character'Val (Ecx.L2); - Vendor_ID(12) := Character'Val (Ecx.H2); - - -- return string - return Vendor_ID; - - end Vendor_ID; - - ------------------------------- - -- Get processor signature -- - ------------------------------- - - function Signature return Processor_Signature is - - Result : Processor_Signature; - -- processor signature returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one is stored in eax - -- processor signature returned in eax - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- eax is stored in Result - Outputs => Processor_Signature'Asm_output ("=a", Result), - - -- tell compiler that ebx, ecx and edx are also destroyed - Clobber => "ebx, ecx, edx"); - - -- return processor signature - return Result; - - end Signature; - - ------------------------------ - -- Get processor features -- - ------------------------------ - - function Features return Processor_Features is - - Result : Processor_Features; - -- processor features returned - - begin - - -- execute CPUID, storing the results in the Result variable - Asm ( - - -- the assembler code - "cpuid", -- execute CPUID - - -- one stored in eax - -- processor features returned in edx - Inputs => Unsigned_32'Asm_input ("a", 1), - - -- edx is stored in Result - Outputs => Processor_Features'Asm_output ("=d", Result), - - -- tell compiler that ebx and ecx are also destroyed - Clobber => "ebx, ecx"); - - -- return processor signature - return Result; - - end Features; - - end Intel_CPU; - @end smallexample - @c END OF INLINE ASSEMBLER CHAPTER - @c =============================== - - @node Microsoft Windows Topics - @chapter Microsoft Windows Topics - @cindex Windows NT - @cindex Windows 95 - @cindex Windows 98 - - @noindent - This chapter describes topics that are specific to the Microsoft Windows - platforms (NT, 95 and 98). - - @menu - * Using GNAT on Windows:: - * GNAT Setup Tool:: - * CONSOLE and WINDOWS subsystems:: - * Temporary Files:: - * Mixed-Language Programming on Windows:: - * Windows Calling Conventions:: - * Introduction to Dynamic Link Libraries (DLLs):: - * Using DLLs with GNAT:: - * Building DLLs with GNAT:: - * GNAT and Windows Resources:: - * Debugging a DLL:: - * GNAT and COM/DCOM Objects:: - @end menu - - @node Using GNAT on Windows - @section Using GNAT on Windows - - @noindent - One of the strengths of the GNAT technology is that its tool set - (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the - @code{gdb} debugger, etc.) is used in the same way regardless of the - platform. - - On Windows this tool set is complemented by a number of Microsoft-specific - tools that have been provided to facilitate interoperability with Windows - when this is required. With these tools: - - @itemize @bullet - - @item - You can build applications using the @code{CONSOLE} or @code{WINDOWS} - subsystems. - - @item - You can use any Dynamically Linked Library (DLL) in your Ada code (both - relocatable and non-relocatable DLLs are supported). - - @item - You can build Ada DLLs for use in other applications. These applications - can be written in a language other than Ada (e.g., C, C++, etc). Again both - relocatable and non-relocatable Ada DLLs are supported. - - @item - You can include Windows resources in your Ada application. - - @item - You can use or create COM/DCOM objects. - @end itemize - - @noindent - Immediately below are listed all known general GNAT-for-Windows restrictions. - Other restrictions about specific features like Windows Resources and DLLs - are listed in separate sections below. - - @itemize @bullet - - @item - It is not possible to use @code{GetLastError} and @code{SetLastError} - when tasking, protected records, or exceptions are used. In these - cases, in order to implement Ada semantics, the GNAT run-time system - calls certain Win32 routines that set the last error variable to 0 upon - success. It should be possible to use @code{GetLastError} and - @code{SetLastError} when tasking, protected record, and exception - features are not used, but it is not guaranteed to work. - @end itemize - - @node GNAT Setup Tool - @section GNAT Setup Tool - @cindex GNAT Setup Tool - @cindex Setup Tool - @cindex gnatreg - - @menu - * Command-line arguments:: - * Creating a network installation of GNAT:: - * Registering and unregistering additional libraries:: - @end menu - - @noindent - GNAT installation on Windows is using the Windows registry in order to - locate proper executables and standard libraries. GNAT setup tool, called - @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific - registry entries, allowing to create network GNAT installations, modify the - locations of GNAT components, as well as register and unregister additional - libraries for use with GNAT. - - @node Command-line arguments - @subsection Command-line arguments - - @noindent - @code{gnatreg [switches] [parameter]} - - @noindent - Specifying no arguments causes gnatreg to display current configuration. - - @noindent - The switches understood by gnatreg are: - @table @asis - @item -h - print the help message - @item -a - add a standard library - @item -r - remove a standard library - @item -f - force creation of keys if they don't exist - @item -q - be quiet/terse - @end table - - @node Creating a network installation of GNAT - @subsection Creating a network installation of GNAT - - @noindent - Make sure the system on which GNAT is installed is accessible from the - current machine. - - Use the command - - @code{@ @ @ gnatreg -f \\server\sharename\path} - - in order to setup the registry entries on a current machine. - - For example, if GNAT is installed in @file{\GNAT} directory of a share location - called @file{c-drive} on a machine @file{LOKI}, the command that can be used on - other machines to allow the remote use of GNAT is, - - @code{@ @ @ gnatreg -f \\loki\c-drive\gnat} - - Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable. - - Be aware that every compilation using the network installation results in the - transfer of large amounts of data across the network and may cause serious - performance penalty. - - @node Registering and unregistering additional libraries - @subsection Registering and unregistering additional libraries - - @noindent - To register a standard library use a command: - - @code{@ @ @ gnatreg -a =} - - For example: - - @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada} - - The libraries registered in this manner will be treated like standard libraries - by the compiler (i.e. they don't have to be specified in -I and -l switches to - various GNAT tools). - - To unregister a library, enter - @code{ gnatreg -r } - - e.g., - @code{ gnatreg -r WIN32ADA} - - @node CONSOLE and WINDOWS subsystems - @section CONSOLE and WINDOWS subsystems - @cindex CONSOLE Subsystem - @cindex WINDOWS Subsystem - @cindex -mwindows - - @noindent - Under Windows there is two main subsystems. The @code{CONSOLE} subsystem - (which is the default subsystem) will always create a console when - launching the application. This is not something desirable when the - application has a Windows GUI. To get rid of this console the - application must be using the @code{WINDOWS} subsystem. To do so - the @code{-mwindows} linker option must be specified. - - @smallexample - $ gnatmake winprog -largs -mwindows - @end smallexample - - @node Temporary Files - @section Temporary Files - @cindex Temporary files - - @noindent - It is possible to control where temporary files gets created by setting - the TMP environment variable. The file will be created: - - @itemize - @item Under the directory pointed to by the TMP environment variable if - this directory exists. - - @item Under c:\temp, if the TMP environment variable is not set (or not - pointing to a directory) and if this directory exists. - - @item Under the current working directory otherwise. - @end itemize - - @noindent - This allows you to determine exactly where the temporary - file will be created. This is particularly useful in networked - environments where you may not have write access to some - directories. - - @node Mixed-Language Programming on Windows - @section Mixed-Language Programming on Windows - - @noindent - Developing pure Ada applications on Windows is no different than on - other GNAT-supported platforms. However, when developing or porting an - application that contains a mix of Ada and C/C++, the choice of your - Windows C/C++ development environment conditions your overall - interoperability strategy. - - If you use @code{gcc} to compile the non-Ada part of your application, - there are no Windows-specific restrictions that affect the overall - interoperability with your Ada code. If you plan to use - Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of - the following limitations: - - @itemize @bullet - @item - You cannot link your Ada code with an object or library generated with - Microsoft tools if these use the @code{.tls} section (Thread Local - Storage section) since the GNAT linker does not yet support this section. - - @item - You cannot link your Ada code with an object or library generated with - Microsoft tools if these use I/O routines other than those provided in - the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time - uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O - libraries can cause a conflict with @code{msvcrt.dll} services. For - instance Visual C++ I/O stream routines conflict with those in - @code{msvcrt.dll}. - @end itemize - - @noindent - If you do want to use the Microsoft tools for your non-Ada code and hit one - of the above limitations, you have two choices: - - @enumerate - @item - Encapsulate your non Ada code in a DLL to be linked with your Ada - application. In this case, use the Microsoft or whatever environment to - build the DLL and use GNAT to build your executable - (@pxref{Using DLLs with GNAT}). - - @item - Or you can encapsulate your Ada code in a DLL to be linked with the - other part of your application. In this case, use GNAT to build the DLL - (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever - environment to build your executable. - @end enumerate - - @node Windows Calling Conventions - @section Windows Calling Conventions - @findex Stdcall - @findex APIENTRY - - @menu - * C Calling Convention:: - * Stdcall Calling Convention:: - * DLL Calling Convention:: - @end menu - - @noindent - When a subprogram @code{F} (caller) calls a subprogram @code{G} - (callee), there are several ways to push @code{G}'s parameters on the - stack and there are several possible scenarios to clean up the stack - upon @code{G}'s return. A calling convention is an agreed upon software - protocol whereby the responsibilities between the caller (@code{F}) and - the callee (@code{G}) are clearly defined. Several calling conventions - are available for Windows: - - @itemize @bullet - @item - @code{C} (Microsoft defined) - - @item - @code{Stdcall} (Microsoft defined) - - @item - @code{DLL} (GNAT specific) - @end itemize - - @node C Calling Convention - @subsection @code{C} Calling Convention - - @noindent - This is the default calling convention used when interfacing to C/C++ - routines compiled with either @code{gcc} or Microsoft Visual C++. - - In the @code{C} calling convention subprogram parameters are pushed on the - stack by the caller from right to left. The caller itself is in charge of - cleaning up the stack after the call. In addition, the name of a routine - with @code{C} calling convention is mangled by adding a leading underscore. - - The name to use on the Ada side when importing (or exporting) a routine - with @code{C} calling convention is the name of the routine. For - instance the C function: - - @smallexample - int get_val (long); - @end smallexample - - @noindent - should be imported from Ada as follows: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (C, Get_Val, External_Name => "get_val"); - @end group - @end smallexample - - @noindent - Note that in this particular case the @code{External_Name} parameter could - have been omitted since, when missing, this parameter is taken to be the - name of the Ada entity in lower case. When the @code{Link_Name} parameter - is missing, as in the above example, this parameter is set to be the - @code{External_Name} with a leading underscore. - - When importing a variable defined in C, you should always use the @code{C} - calling convention unless the object containing the variable is part of a - DLL (in which case you should use the @code{DLL} calling convention, - @pxref{DLL Calling Convention}). - - @node Stdcall Calling Convention - @subsection @code{Stdcall} Calling Convention - - @noindent - This convention, which was the calling convention used for Pascal - programs, is used by Microsoft for all the routines in the Win32 API for - efficiency reasons. It must be used to import any routine for which this - convention was specified. - - In the @code{Stdcall} calling convention subprogram parameters are pushed - on the stack by the caller from right to left. The callee (and not the - caller) is in charge of cleaning the stack on routine exit. In addition, - the name of a routine with @code{Stdcall} calling convention is mangled by - adding a leading underscore (as for the @code{C} calling convention) and a - trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in - bytes) of the parameters passed to the routine. - - The name to use on the Ada side when importing a C routine with a - @code{Stdcall} calling convention is the name of the C routine. The leading - underscore and trailing @code{@@}@code{@i{nn}} are added automatically by - the compiler. For instance the Win32 function: - - @smallexample - @b{APIENTRY} int get_val (long); - @end smallexample - - @noindent - should be imported from Ada as follows: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (Stdcall, Get_Val); - -- @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4" - @end group - @end smallexample - - @noindent - As for the @code{C} calling convention, when the @code{External_Name} - parameter is missing, it is taken to be the name of the Ada entity in lower - case. If instead of writing the above import pragma you write: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val"); - @end group - @end smallexample - - @noindent - then the imported routine is @code{_retrieve_val@@4}. However, if instead - of specifying the @code{External_Name} parameter you specify the - @code{Link_Name} as in the following example: - - @smallexample - @group - @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int; - @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val"); - @end group - @end smallexample - - @noindent - then the imported routine is @code{retrieve_val@@4}, that is, there is no - trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always - added at the end of the @code{Link_Name} by the compiler. - - @noindent - Note, that in some special cases a DLL's entry point name lacks a trailing - @code{@@}@code{@i{nn}} while the exported name generated for a call has it. - The @code{gnatdll} tool, which creates the import library for the DLL, is able - to handle those cases (see the description of the switches in - @pxref{Using gnatdll} section). - - @node DLL Calling Convention - @subsection @code{DLL} Calling Convention - - @noindent - This convention, which is GNAT-specific, must be used when you want to - import in Ada a variables defined in a DLL. For functions and procedures - this convention is equivalent to the @code{Stdcall} convention. As an - example, if a DLL contains a variable defined as: - - @smallexample - int my_var; - @end smallexample - - @noindent - then, to access this variable from Ada you should write: - - @smallexample - @group - My_Var : Interfaces.C.int; - @b{pragma} Import (DLL, My_Var); - @end group - @end smallexample - - The remarks concerning the @code{External_Name} and @code{Link_Name} - parameters given in the previous sections equally apply to the @code{DLL} - calling convention. - - @node Introduction to Dynamic Link Libraries (DLLs) - @section Introduction to Dynamic Link Libraries (DLLs) - @findex DLL - - @noindent - A Dynamically Linked Library (DLL) is a library that can be shared by - several applications running under Windows. A DLL can contain any number of - routines and variables. - - One advantage of DLLs is that you can change and enhance them without - forcing all the applications that depend on them to be relinked or - recompiled. However, you should be aware than all calls to DLL routines are - slower since, as you will understand below, such calls are indirect. - - To illustrate the remainder of this section, suppose that an application - wants to use the services of a DLL @file{API.dll}. To use the services - provided by @file{API.dll} you must statically link against an import - library which contains a jump table with an entry for each routine and - variable exported by the DLL. In the Microsoft world this import library is - called @file{API.lib}. When using GNAT this import library is called either - @file{libAPI.a} or @file{libapi.a} (names are case insensitive). - - After you have statically linked your application with the import library - and you run your application, here is what happens: - - @enumerate - @item - Your application is loaded into memory. - - @item - The DLL @file{API.dll} is mapped into the address space of your - application. This means that: - - @itemize @bullet - @item - The DLL will use the stack of the calling thread. - - @item - The DLL will use the virtual address space of the calling process. - - @item - The DLL will allocate memory from the virtual address space of the calling - process. - - @item - Handles (pointers) can be safely exchanged between routines in the DLL - routines and routines in the application using the DLL. - @end itemize - - @item - The entries in the @file{libAPI.a} or @file{API.lib} jump table which is - part of your application are initialized with the addresses of the routines - and variables in @file{API.dll}. - - @item - If present in @file{API.dll}, routines @code{DllMain} or - @code{DllMainCRTStartup} are invoked. These routines typically contain - the initialization code needed for the well-being of the routines and - variables exported by the DLL. - @end enumerate - - @noindent - There is an additional point which is worth mentioning. In the Windows - world there are two kind of DLLs: relocatable and non-relocatable - DLLs. Non-relocatable DLLs can only be loaded at a very specific address - in the target application address space. If the addresses of two - non-relocatable DLLs overlap and these happen to be used by the same - application, a conflict will occur and the application will run - incorrectly. Hence, when possible, it is always preferable to use and - build relocatable DLLs. Both relocatable and non-relocatable DLLs are - supported by GNAT. - - As a side note, an interesting difference between Microsoft DLLs and - Unix shared libraries, is the fact that on most Unix systems all public - routines are exported by default in a Unix shared library, while under - Windows the exported routines must be listed explicitly in a definition - file (@pxref{The Definition File}). - - @node Using DLLs with GNAT - @section Using DLLs with GNAT - - @menu - * Creating an Ada Spec for the DLL Services:: - * Creating an Import Library:: - @end menu - - @noindent - To use the services of a DLL, say @file{API.dll}, in your Ada application - you must have: - - @enumerate - @item - The Ada spec for the routines and/or variables you want to access in - @file{API.dll}. If not available this Ada spec must be built from the C/C++ - header files provided with the DLL. - - @item - The import library (@file{libAPI.a} or @file{API.lib}). As previously - mentioned an import library is a statically linked library containing the - import table which will be filled at load time to point to the actual - @file{API.dll} routines. Sometimes you don't have an import library for the - DLL you want to use. The following sections will explain how to build one. - - @item - The actual DLL, @file{API.dll}. - @end enumerate - - @noindent - Once you have all the above, to compile an Ada application that uses the - services of @file{API.dll} and whose main subprogram is @code{My_Ada_App}, - you simply issue the command - - @smallexample - $ gnatmake my_ada_app -largs -lAPI - @end smallexample - - @noindent - The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command - tells the GNAT linker to look first for a library named @file{API.lib} - (Microsoft-style name) and if not found for a library named @file{libAPI.a} - (GNAT-style name). Note that if the Ada package spec for @file{API.dll} - contains the following pragma - - @smallexample - @b{pragma} Linker_Options ("-lAPI"); - @end smallexample - - @noindent - you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake} - command. - - If any one of the items above is missing you will have to create it - yourself. The following sections explain how to do so using as an - example a fictitious DLL called @file{API.dll}. - - @node Creating an Ada Spec for the DLL Services - @subsection Creating an Ada Spec for the DLL Services - - @noindent - A DLL typically comes with a C/C++ header file which provides the - definitions of the routines and variables exported by the DLL. The Ada - equivalent of this header file is a package spec that contains definitions - for the imported entities. If the DLL you intend to use does not come with - an Ada spec you have to generate one such spec yourself. For example if - the header file of @file{API.dll} is a file @file{api.h} containing the - following two definitions: - - @smallexample - @group - @cartouche - int some_var; - int get (char *); - @end cartouche - @end group - @end smallexample - - @noindent - then the equivalent Ada spec could be: - - @smallexample - @group - @cartouche - @b{with} Interfaces.C.Strings; - @b{package} API @b{is} - @b{use} Interfaces; - - Some_Var : C.int; - @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int; - - @b{private} - @b{pragma} Import (C, Get); - @b{pragma} Import (DLL, Some_Var); - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - Note that a variable is @strong{always imported with a DLL convention}. A - function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For - subprograms, the @code{DLL} convention is a synonym of @code{Stdcall} - (@pxref{Windows Calling Conventions}). - - @node Creating an Import Library - @subsection Creating an Import Library - @cindex Import library - - @menu - * The Definition File:: - * GNAT-Style Import Library:: - * Microsoft-Style Import Library:: - @end menu - - @noindent - If a Microsoft-style import library @file{API.lib} or a GNAT-style - import library @file{libAPI.a} is available with @file{API.dll} you - can skip this section. Otherwise read on. - - @node The Definition File - @subsubsection The Definition File - @cindex Definition file - @findex .def - - @noindent - As previously mentioned, and unlike Unix systems, the list of symbols - that are exported from a DLL must be provided explicitly in Windows. - The main goal of a definition file is precisely that: list the symbols - exported by a DLL. A definition file (usually a file with a @code{.def} - suffix) has the following structure: - - @smallexample - @group - @cartouche - [LIBRARY @i{name}] - [DESCRIPTION @i{string}] - EXPORTS - @i{symbol1} - @i{symbol2} - ... - @end cartouche - @end group - @end smallexample - - @table @code - @item LIBRARY @i{name} - This section, which is optional, gives the name of the DLL. - - @item DESCRIPTION @i{string} - This section, which is optional, gives a description string that will be - embedded in the import library. - - @item EXPORTS - This section gives the list of exported symbols (procedures, functions or - variables). For instance in the case of @file{API.dll} the @code{EXPORTS} - section of @file{API.def} looks like: - - @smallexample - @group - @cartouche - EXPORTS - some_var - get - @end cartouche - @end group - @end smallexample - @end table - - @noindent - Note that you must specify the correct suffix (@code{@@}@code{@i{nn}}) - (@pxref{Windows Calling Conventions}) for a Stdcall - calling convention function in the exported symbols list. - - @noindent - There can actually be other sections in a definition file, but these - sections are not relevant to the discussion at hand. - - @node GNAT-Style Import Library - @subsubsection GNAT-Style Import Library - - @noindent - To create a static import library from @file{API.dll} with the GNAT tools - you should proceed as follows: - - @enumerate - @item - Create the definition file @file{API.def} (@pxref{The Definition File}). - For that use the @code{dll2def} tool as follows: - - @smallexample - $ dll2def API.dll > API.def - @end smallexample - - @noindent - @code{dll2def} is a very simple tool: it takes as input a DLL and prints - to standard output the list of entry points in the DLL. Note that if - some routines in the DLL have the @code{Stdcall} convention - (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn} - suffix then you'll have to edit @file{api.def} to add it. - - @noindent - Here are some hints to find the right @code{@@}@i{nn} suffix. - - @enumerate - @item - If you have the Microsoft import library (.lib), it is possible to get - the right symbols by using Microsoft @code{dumpbin} tool (see the - corresponding Microsoft documentation for further details). - - @smallexample - $ dumpbin /exports api.lib - @end smallexample - - @item - If you have a message about a missing symbol at link time the compiler - tells you what symbol is expected. You just have to go back to the - definition file and add the right suffix. - @end enumerate - - @item - Build the import library @code{libAPI.a}, using @code{gnatdll} - (@pxref{Using gnatdll}) as follows: - - @smallexample - $ gnatdll -e API.def -d API.dll - @end smallexample - - @noindent - @code{gnatdll} takes as input a definition file @file{API.def} and the - name of the DLL containing the services listed in the definition file - @file{API.dll}. The name of the static import library generated is - computed from the name of the definition file as follows: if the - definition file name is @i{xyz}@code{.def}, the import library name will - be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option - @code{-e} could have been removed because the name of the definition - file (before the "@code{.def}" suffix) is the same as the name of the - DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}). - @end enumerate - - @node Microsoft-Style Import Library - @subsubsection Microsoft-Style Import Library - - @noindent - With GNAT you can either use a GNAT-style or Microsoft-style import - library. A Microsoft import library is needed only if you plan to make an - Ada DLL available to applications developed with Microsoft - tools (@pxref{Mixed-Language Programming on Windows}). - - To create a Microsoft-style import library for @file{API.dll} you - should proceed as follows: - - @enumerate - @item - Create the definition file @file{API.def} from the DLL. For this use either - the @code{dll2def} tool as described above or the Microsoft @code{dumpbin} - tool (see the corresponding Microsoft documentation for further details). - - @item - Build the actual import library using Microsoft's @code{lib} utility: - - @smallexample - $ lib -machine:IX86 -def:API.def -out:API.lib - @end smallexample - - @noindent - If you use the above command the definition file @file{API.def} must - contain a line giving the name of the DLL: - - @smallexample - LIBRARY "API" - @end smallexample - - @noindent - See the Microsoft documentation for further details about the usage of - @code{lib}. - @end enumerate - - @node Building DLLs with GNAT - @section Building DLLs with GNAT - @cindex DLLs, building - - @menu - * Limitations When Using Ada DLLs from Ada:: - * Exporting Ada Entities:: - * Ada DLLs and Elaboration:: - * Ada DLLs and Finalization:: - * Creating a Spec for Ada DLLs:: - * Creating the Definition File:: - * Using gnatdll:: - @end menu - - @noindent - This section explains how to build DLLs containing Ada code. These DLLs - will be referred to as Ada DLLs in the remainder of this section. - - The steps required to build an Ada DLL that is to be used by Ada as well as - non-Ada applications are as follows: - - @enumerate - @item - You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or - @code{Stdcall} calling convention to avoid any Ada name mangling for the - entities exported by the DLL (@pxref{Exporting Ada Entities}). You can - skip this step if you plan to use the Ada DLL only from Ada applications. - - @item - Your Ada code must export an initialization routine which calls the routine - @code{adainit} generated by @code{gnatbind} to perform the elaboration of - the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization - routine exported by the Ada DLL must be invoked by the clients of the DLL - to initialize the DLL. - - @item - When useful, the DLL should also export a finalization routine which calls - routine @code{adafinal} generated by @code{gnatbind} to perform the - finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}). - The finalization routine exported by the Ada DLL must be invoked by the - clients of the DLL when the DLL services are no further needed. - - @item - You must provide a spec for the services exported by the Ada DLL in each - of the programming languages to which you plan to make the DLL available. - - @item - You must provide a definition file listing the exported entities - (@pxref{The Definition File}). - - @item - Finally you must use @code{gnatdll} to produce the DLL and the import - library (@pxref{Using gnatdll}). - @end enumerate - - @node Limitations When Using Ada DLLs from Ada - @subsection Limitations When Using Ada DLLs from Ada - - @noindent - When using Ada DLLs from Ada applications there is a limitation users - should be aware of. Because on Windows the GNAT run time is not in a DLL of - its own, each Ada DLL includes a part of the GNAT run time. Specifically, - each Ada DLL includes the services of the GNAT run time that are necessary - to the Ada code inside the DLL. As a result, when an Ada program uses an - Ada DLL there are two independent GNAT run times: one in the Ada DLL and - one in the main program. - - It is therefore not possible to exchange GNAT run-time objects between the - Ada DLL and the main Ada program. Example of GNAT run-time objects are file - handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects - types, etc. - - It is completely safe to exchange plain elementary, array or record types, - Windows object handles, etc. - - @node Exporting Ada Entities - @subsection Exporting Ada Entities - @cindex Export table - - @noindent - Building a DLL is a way to encapsulate a set of services usable from any - application. As a result, the Ada entities exported by a DLL should be - exported with the @code{C} or @code{Stdcall} calling conventions to avoid - any Ada name mangling. Please note that the @code{Stdcall} convention - should only be used for subprograms, not for variables. As an example here - is an Ada package @code{API}, spec and body, exporting two procedures, a - function, and a variable: - - @smallexample - @group - @cartouche - @b{with} Interfaces.C; @b{use} Interfaces; - @b{package} API @b{is} - Count : C.int := 0; - @b{function} Factorial (Val : C.int) @b{return} C.int; - - @b{procedure} Initialize_API; - @b{procedure} Finalize_API; - -- @i{Initialization & Finalization routines. More in the next section.} - @b{private} - @b{pragma} Export (C, Initialize_API); - @b{pragma} Export (C, Finalize_API); - @b{pragma} Export (C, Count); - @b{pragma} Export (C, Factorial); - @b{end} API; - @end cartouche - @end group - @end smallexample - - @smallexample - @group - @cartouche - @b{package body} API @b{is} - @b{function} Factorial (Val : C.int) @b{return} C.int @b{is} - Fact : C.int := 1; - @b{begin} - Count := Count + 1; - @b{for} K @b{in} 1 .. Val @b{loop} - Fact := Fact * K; - @b{end loop}; - @b{return} Fact; - @b{end} Factorial; - - @b{procedure} Initialize_API @b{is} - @b{procedure} Adainit; - @b{pragma} Import (C, Adainit); - @b{begin} - Adainit; - @b{end} Initialize_API; - - @b{procedure} Finalize_API @b{is} - @b{procedure} Adafinal; - @b{pragma} Import (C, Adafinal); - @b{begin} - Adafinal; - @b{end} Finalize_API; - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - If the Ada DLL you are building will only be used by Ada applications - you do not have to export Ada entities with a @code{C} or @code{Stdcall} - convention. As an example, the previous package could be written as - follows: - - @smallexample - @group - @cartouche - @b{package} API @b{is} - Count : Integer := 0; - @b{function} Factorial (Val : Integer) @b{return} Integer; - - @b{procedure} Initialize_API; - @b{procedure} Finalize_API; - -- @i{Initialization and Finalization routines.} - @b{end} API; - @end cartouche - @end group - @end smallexample - - @smallexample - @group - @cartouche - @b{package body} API @b{is} - @b{function} Factorial (Val : Integer) @b{return} Integer @b{is} - Fact : Integer := 1; - @b{begin} - Count := Count + 1; - @b{for} K @b{in} 1 .. Val @b{loop} - Fact := Fact * K; - @b{end loop}; - @b{return} Fact; - @b{end} Factorial; - - ... - -- @i{The remainder of this package body is unchanged.} - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - Note that if you do not export the Ada entities with a @code{C} or - @code{Stdcall} convention you will have to provide the mangled Ada names - in the definition file of the Ada DLL - (@pxref{Creating the Definition File}). - - @node Ada DLLs and Elaboration - @subsection Ada DLLs and Elaboration - @cindex DLLs and elaboration - - @noindent - The DLL that you are building contains your Ada code as well as all the - routines in the Ada library that are needed by it. The first thing a - user of your DLL must do is elaborate the Ada code - (@pxref{Elaboration Order Handling in GNAT}). - - To achieve this you must export an initialization routine - (@code{Initialize_API} in the previous example), which must be invoked - before using any of the DLL services. This elaboration routine must call - the Ada elaboration routine @code{adainit} generated by the GNAT binder - (@pxref{Binding with Non-Ada Main Programs}). See the body of - @code{Initialize_Api} for an example. Note that the GNAT binder is - automatically invoked during the DLL build process by the @code{gnatdll} - tool (@pxref{Using gnatdll}). - - When a DLL is loaded, Windows systematically invokes a routine called - @code{DllMain}. It would therefore be possible to call @code{adainit} - directly from @code{DllMain} without having to provide an explicit - initialization routine. Unfortunately, it is not possible to call - @code{adainit} from the @code{DllMain} if your program has library level - tasks because access to the @code{DllMain} entry point is serialized by - the system (that is, only a single thread can execute "through" it at a - time), which means that the GNAT run time will deadlock waiting for the - newly created task to complete its initialization. - - @node Ada DLLs and Finalization - @subsection Ada DLLs and Finalization - @cindex DLLs and finalization - - @noindent - When the services of an Ada DLL are no longer needed, the client code should - invoke the DLL finalization routine, if available. The DLL finalization - routine is in charge of releasing all resources acquired by the DLL. In the - case of the Ada code contained in the DLL, this is achieved by calling - routine @code{adafinal} generated by the GNAT binder - (@pxref{Binding with Non-Ada Main Programs}). - See the body of @code{Finalize_Api} for an - example. As already pointed out the GNAT binder is automatically invoked - during the DLL build process by the @code{gnatdll} tool - (@pxref{Using gnatdll}). - - @code{-g} - @cindex @code{-g} (@code{gnatdll}) - @* - Generate debugging information. This information is stored in the object - file and copied from there to the final DLL file by the linker, - where it can be read by the debugger. You must use the - @code{-g} switch if you plan on using the debugger or the symbolic - stack traceback. - - @node Creating a Spec for Ada DLLs - @subsection Creating a Spec for Ada DLLs - - @noindent - To use the services exported by the Ada DLL from another programming - language (e.g. C), you have to translate the specs of the exported Ada - entities in that language. For instance in the case of @code{API.dll}, - the corresponding C header file could look like: - - @smallexample - @group - @cartouche - extern int *__imp__count; - #define count (*__imp__count) - int factorial (int); - @end cartouche - @end group - @end smallexample - - @noindent - It is important to understand that when building an Ada DLL to be used by - other Ada applications, you need two different specs for the packages - contained in the DLL: one for building the DLL and the other for using - the DLL. This is because the @code{DLL} calling convention is needed to - use a variable defined in a DLL, but when building the DLL, the variable - must have either the @code{Ada} or @code{C} calling convention. As an - example consider a DLL comprising the following package @code{API}: - - @smallexample - @group - @cartouche - @b{package} API @b{is} - Count : Integer := 0; - ... - -- @i{Remainder of the package omitted.} - @b{end} API; - @end cartouche - @end group - @end smallexample - - @noindent - After producing a DLL containing package @code{API}, the spec that - must be used to import @code{API.Count} from Ada code outside of the - DLL is: - - @smallexample - @group - @cartouche - @b{package} API @b{is} - Count : Integer; - @b{pragma} Import (DLL, Count); - @b{end} API; - @end cartouche - @end group - @end smallexample - - @node Creating the Definition File - @subsection Creating the Definition File - - @noindent - The definition file is the last file needed to build the DLL. It lists - the exported symbols. As an example, the definition file for a DLL - containing only package @code{API} (where all the entities are exported - with a @code{C} calling convention) is: - - @smallexample - @group - @cartouche - EXPORTS - count - factorial - finalize_api - initialize_api - @end cartouche - @end group - @end smallexample - - @noindent - If the @code{C} calling convention is missing from package @code{API}, - then the definition file contains the mangled Ada names of the above - entities, which in this case are: - - @smallexample - @group - @cartouche - EXPORTS - api__count - api__factorial - api__finalize_api - api__initialize_api - @end cartouche - @end group - @end smallexample - - @node Using gnatdll - @subsection Using @code{gnatdll} - @findex gnatdll - - @menu - * gnatdll Example:: - * gnatdll behind the Scenes:: - * Using dlltool:: - @end menu - - @noindent - @code{gnatdll} is a tool to automate the DLL build process once all the Ada - and non-Ada sources that make up your DLL have been compiled. - @code{gnatdll} is actually in charge of two distinct tasks: build the - static import library for the DLL and the actual DLL. The form of the - @code{gnatdll} command is - - @smallexample - @cartouche - $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}] - @end cartouche - @end smallexample - - @noindent - where @i{list-of-files} is a list of ALI and object files. The object - file list must be the exact list of objects corresponding to the non-Ada - sources whose services are to be included in the DLL. The ALI file list - must be the exact list of ALI files for the corresponding Ada sources - whose services are to be included in the DLL. If @i{list-of-files} is - missing, only the static import library is generated. - - @noindent - You may specify any of the following switches to @code{gnatdll}: - - @table @code - @item -a[@var{address}] - @cindex @code{-a} (@code{gnatdll}) - Build a non-relocatable DLL at @var{address}. If @var{address} is not - specified the default address @var{0x11000000} will be used. By default, - when this switch is missing, @code{gnatdll} builds relocatable DLL. We - advise the reader to build relocatable DLL. - - @item -b @var{address} - @cindex @code{-b} (@code{gnatdll}) - Set the relocatable DLL base address. By default the address is - @var{0x11000000}. - - @item -d @var{dllfile} - @cindex @code{-d} (@code{gnatdll}) - @var{dllfile} is the name of the DLL. This switch must be present for - @code{gnatdll} to do anything. The name of the generated import library is - obtained algorithmically from @var{dllfile} as shown in the following - example: if @var{dllfile} is @code{xyz.dll}, the import library name is - @code{libxyz.a}. The name of the definition file to use (if not specified - by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in - the following example: if @var{dllfile} is @code{xyz.dll}, the definition - file used is @code{xyz.def}. - - @item -e @var{deffile} - @cindex @code{-e} (@code{gnatdll}) - @var{deffile} is the name of the definition file. - - @item -h - @cindex @code{-h} (@code{gnatdll}) - Help mode. Displays @code{gnatdll} switch usage information. - - @item -Idir - Direct @code{gnatdll} to search the @var{dir} directory for source and - object files needed to build the DLL. - (@pxref{Search Paths and the Run-Time Library (RTL)}). - - @item -k - Removes the @code{@@}@i{nn} suffix from the import library's exported - names. You must specified this option if you want to use a - @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix - has been removed. This is the case for most of the Windows NT DLL for - example. This option has no effect when @code{-n} option is specified. - - @item -l @var{file} - @cindex @code{-l} (@code{gnatdll}) - The list of ALI and object files used to build the DLL are listed in - @var{file}, instead of being given in the command line. Each line in - @var{file} contains the name of an ALI or object file. - - @item -n - @cindex @code{-n} (@code{gnatdll}) - No Import. Do not create the import library. - - @item -q - @cindex @code{-q} (@code{gnatdll}) - Quiet mode. Do not display unnecessary messages. - - @item -v - @cindex @code{-v} (@code{gnatdll}) - Verbose mode. Display extra information. - - @item -largs @var{opts} - @cindex @code{-largs} (@code{gnatdll}) - Linker options. Pass @var{opts} to the linker. - @end table - - @node gnatdll Example - @subsubsection @code{gnatdll} Example - - @noindent - As an example the command to build a relocatable DLL from @file{api.adb} - once @file{api.adb} has been compiled and @file{api.def} created is - - @smallexample - $ gnatdll -d api.dll api.ali - @end smallexample - - @noindent - The above command creates two files: @file{libapi.a} (the import - library) and @file{api.dll} (the actual DLL). If you want to create - only the DLL, just type: - - @smallexample - $ gnatdll -d api.dll -n api.ali - @end smallexample - - @noindent - Alternatively if you want to create just the import library, type: - - @smallexample - $ gnatdll -d api.dll - @end smallexample - - @node gnatdll behind the Scenes - @subsubsection @code{gnatdll} behind the Scenes - - @noindent - This section details the steps involved in creating a DLL. @code{gnatdll} - does these steps for you. Unless you are interested in understanding what - goes on behind the scenes, you should skip this section. - - We use the previous example of a DLL containing the Ada package @code{API}, - to illustrate the steps necessary to build a DLL. The starting point is a - set of objects that will make up the DLL and the corresponding ALI - files. In the case of this example this means that @file{api.o} and - @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does - the following: - - @enumerate - @item - @code{gnatdll} builds the base file (@file{api.base}). A base file gives - the information necessary to generate relocation information for the - DLL. - - @smallexample - @group - $ gnatbind -n api - $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base - @end group - @end smallexample - - @noindent - In addition to the base file, the @code{gnatlink} command generates an - output file @file{api.jnk} which can be discarded. The @code{-mdll} switch - asks @code{gnatlink} to generate the routines @code{DllMain} and - @code{DllMainCRTStartup} that are called by the Windows loader when the DLL - is loaded into memory. - - @item - @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the - export table (@file{api.exp}). The export table contains the relocation - information in a form which can be used during the final link to ensure - that the Windows loader is able to place the DLL anywhere in memory. - - @smallexample - @group - $ dlltool --dllname api.dll --def api.def --base-file api.base \ - --output-exp api.exp - @end group - @end smallexample - - @item - @code{gnatdll} builds the base file using the new export table. Note that - @code{gnatbind} must be called once again since the binder generated file - has been deleted during the previous call to @code{gnatlink}. - - @smallexample - @group - $ gnatbind -n api - $ gnatlink api -o api.jnk api.exp -mdll - -Wl,--base-file,api.base - @end group - @end smallexample - - @item - @code{gnatdll} builds the new export table using the new base file and - generates the DLL import library @file{libAPI.a}. - - @smallexample - @group - $ dlltool --dllname api.dll --def api.def --base-file api.base \ - --output-exp api.exp --output-lib libAPI.a - @end group - @end smallexample - - @item - Finally @code{gnatdll} builds the relocatable DLL using the final export - table. - - @smallexample - @group - $ gnatbind -n api - $ gnatlink api api.exp -o api.dll -mdll - @end group - @end smallexample - @end enumerate - - @node Using dlltool - @subsubsection Using @code{dlltool} - - @noindent - @code{dlltool} is the low-level tool used by @code{gnatdll} to build - DLLs and static import libraries. This section summarizes the most - common @code{dlltool} switches. The form of the @code{dlltool} command - is - - @smallexample - $ dlltool [@var{switches}] - @end smallexample - - @noindent - @code{dlltool} switches include: - - @table @code - @item --base-file @var{basefile} - Read the base file @var{basefile} generated by the linker. This switch - is used to create a relocatable DLL. - - @item --def @var{deffile} - Read the definition file. - - @item --dllname @var{name} - Gives the name of the DLL. This switch is used to embed the name of the - DLL in the static import library generated by @code{dlltool} with switch - @code{--output-lib}. - - @item -k - Kill @code{@@}@i{nn} from exported names - (@pxref{Windows Calling Conventions} - for a discussion about @code{Stdcall}-style symbols. - - @item --help - Prints the @code{dlltool} switches with a concise description. - - @item --output-exp @var{exportfile} - Generate an export file @var{exportfile}. The export file contains the - export table (list of symbols in the DLL) and is used to create the DLL. - - @item --output-lib @i{libfile} - Generate a static import library @var{libfile}. - - @item -v - Verbose mode. - - @item --as @i{assembler-name} - Use @i{assembler-name} as the assembler. The default is @code{as}. - @end table - - @node GNAT and Windows Resources - @section GNAT and Windows Resources - @cindex Resources, windows - - @menu - * Building Resources:: - * Compiling Resources:: - * Using Resources:: - * Limitations:: - @end menu - - @noindent - Resources are an easy way to add Windows specific objects to your - application. The objects that can be added as resources include: - - @itemize @bullet - @item - menus - - @item - accelerators - - @item - dialog boxes - - @item - string tables - - @item - bitmaps - - @item - cursors - - @item - icons - - @item - fonts - @end itemize - - @noindent - This section explains how to build, compile and use resources. - - @node Building Resources - @subsection Building Resources - @cindex Resources, building - - @noindent - A resource file is an ASCII file. By convention resource files have an - @file{.rc} extension. - The easiest way to build a resource file is to use Microsoft tools - such as @code{imagedit.exe} to build bitmaps, icons and cursors and - @code{dlgedit.exe} to build dialogs. - It is always possible to build an @file{.rc} file yourself by writing a - resource script. - - It is not our objective to explain how to write a resource file. A - complete description of the resource script language can be found in the - Microsoft documentation. - - @node Compiling Resources - @subsection Compiling Resources - @findex rc - @findex rcl - @findex res2coff - @cindex Resources, compiling - - @noindent - This section describes how to build a GNAT-compatible (COFF) object file - containing the resources. This is done using the Resource Compiler - @code{rcl} as follows: - - @smallexample - $ rcl -i myres.rc -o myres.o - @end smallexample - - @noindent - By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc} - file. You can specify an alternate preprocessor (usually named - @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of - all possible options may be obtained by entering the command @code{rcl} - with no parameters. - - It is also possible to use the Microsoft resource compiler @code{rc.exe} - to produce a @file{.res} file (binary resource file). See the - corresponding Microsoft documentation for further details. In this case - you need to use @code{res2coff} to translate the @file{.res} file to a - GNAT-compatible object file as follows: - - @smallexample - $ res2coff -i myres.res -o myres.o - @end smallexample - - @node Using Resources - @subsection Using Resources - @cindex Resources, using - - @noindent - To include the resource file in your program just add the - GNAT-compatible object file for the resource(s) to the linker - arguments. With @code{gnatmake} this is done by using the @code{-largs} - option: - - @smallexample - $ gnatmake myprog -largs myres.o - @end smallexample - - @node Limitations - @subsection Limitations - @cindex Resources, limitations - - @noindent - In this section we describe the current limitations together with - suggestions for workarounds. - - @itemize @bullet - @item - @code{rcl} does not handle the @code{RCINCLUDE} directive. - @* - Workaround: replace @code{RCINCLUDE} by an @code{#include} directive. - - @item - @code{rcl} does not handle the brackets as block delimiters. - @* - Workaround: replace character '@{' by @code{BEGIN} and '@}' by - @code{END}. Note that Microsoft's @code{rc} handles both forms of block - delimiters. - - @item - @code{rcl} does not handle @code{TypeLib} resources. This type of - resource is used to build COM, DCOM or ActiveX objects. - @* - Workaround: use @code{rc}, the Microsoft resource compiler. - - @item - It is not possible to use @code{strip} to remove the debugging symbols - from a program with resources. - @* - Workaround: use linker option @code{-s} to strip debugging symbols from - the final executable. - @end itemize - - @node Debugging a DLL - @section Debugging a DLL - @cindex DLL debugging - - @menu - * The Program and the DLL Are Built with GCC/GNAT:: - * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT:: - @end menu - - @noindent - Debugging a DLL is similar to debugging a standard program. But - we have to deal with two different executable parts: the DLL and the - program that uses it. We have the following four possibilities: - - @enumerate 1 - @item - The program and the DLL are built with @code{GCC/GNAT}. - @item - The program is built with foreign tools and the DLL is built with - @code{GCC/GNAT}. - @item - The program is built with @code{GCC/GNAT} and the DLL is built with - foreign tools. - @item - @end enumerate - - @noindent - In this section we address only cases one and two above. - There is no point in trying to debug - a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging - information in it. To do so you must use a debugger compatible with the - tools suite used to build the DLL. - - @node The Program and the DLL Are Built with GCC/GNAT - @subsection The Program and the DLL Are Built with GCC/GNAT - - @noindent - This is the simplest case. Both the DLL and the program have @code{GDB} - compatible debugging information. It is then possible to break anywhere in - the process. Let's suppose here that the main procedure is named - @code{ada_main} and that in the DLL there is an entry point named - @code{ada_dll}. - - @noindent - The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and - program must have been built with the debugging information (see GNAT -g - switch). Here are the step-by-step instructions for debugging it: - - @enumerate 1 - @item Launch @code{GDB} on the main program. - - @smallexample - $ gdb -nw ada_main - @end smallexample - - @item Break on the main procedure and run the program. - - @smallexample - (gdb) break ada_main - (gdb) run - @end smallexample - - @noindent - This step is required to be able to set a breakpoint inside the DLL. As long - as the program is not run, the DLL is not loaded. This has the - consequence that the DLL debugging information is also not loaded, so it is not - possible to set a breakpoint in the DLL. - - @item Set a breakpoint inside the DLL - - @smallexample - (gdb) break ada_dll - (gdb) run - @end smallexample - - @end enumerate - - @noindent - At this stage a breakpoint is set inside the DLL. From there on - you can use the standard approach to debug the whole program - (@pxref{Running and Debugging Ada Programs}). - - @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT - @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT - - @menu - * Debugging the DLL Directly:: - * Attaching to a Running Process:: - @end menu - - @noindent - In this case things are slightly more complex because it is not possible to - start the main program and then break at the beginning to load the DLL and the - associated DLL debugging information. It is not possible to break at the - beginning of the program because there is no @code{GDB} debugging information, - and therefore there is no direct way of getting initial control. This - section addresses this issue by describing some methods that can be used - to break somewhere in the DLL to debug it. - - @noindent - First suppose that the main procedure is named @code{main} (this is for - example some C code built with Microsoft Visual C) and that there is a - DLL named @code{test.dll} containing an Ada entry point named - @code{ada_dll}. - - @noindent - The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have - been built with debugging information (see GNAT -g option). - - @node Debugging the DLL Directly - @subsubsection Debugging the DLL Directly - - @enumerate 1 - @item - Launch the debugger on the DLL. - - @smallexample - $ gdb -nw test.dll - @end smallexample - - @item Set a breakpoint on a DLL subroutine. - - @smallexample - (gdb) break ada_dll - @end smallexample - - @item - Specify the executable file to @code{GDB}. - - @smallexample - (gdb) exec-file main.exe - @end smallexample - - @item - Run the program. - - @smallexample - (gdb) run - @end smallexample - - @noindent - This will run the program until it reaches the breakpoint that has been - set. From that point you can use the standard way to debug a program - as described in (@pxref{Running and Debugging Ada Programs}). - - @end enumerate - - @noindent - It is also possible to debug the DLL by attaching to a running process. - - @node Attaching to a Running Process - @subsubsection Attaching to a Running Process - @cindex DLL debugging, attach to process - - @noindent - With @code{GDB} it is always possible to debug a running process by - attaching to it. It is possible to debug a DLL this way. The limitation - of this approach is that the DLL must run long enough to perform the - attach operation. It may be useful for instance to insert a time wasting - loop in the code of the DLL to meet this criterion. - - @enumerate 1 - - @item Launch the main program @file{main.exe}. - - @smallexample - $ main - @end smallexample - - @item Use the Windows @i{Task Manager} to find the process ID. Let's say - that the process PID for @file{main.exe} is 208. - - @item Launch gdb. - - @smallexample - $ gdb -nw - @end smallexample - - @item Attach to the running process to be debugged. - - @smallexample - (gdb) attach 208 - @end smallexample - - @item Load the process debugging information. - - @smallexample - (gdb) symbol-file main.exe - @end smallexample - - @item Break somewhere in the DLL. - - @smallexample - (gdb) break ada_dll - @end smallexample - - @item Continue process execution. - - @smallexample - (gdb) continue - @end smallexample - - @end enumerate - - @noindent - This last step will resume the process execution, and stop at - the breakpoint we have set. From there you can use the standard - approach to debug a program as described in - (@pxref{Running and Debugging Ada Programs}). - - @node GNAT and COM/DCOM Objects - @section GNAT and COM/DCOM Objects - @findex COM - @findex DCOM - - @noindent - This section is temporarily left blank. - - @ignore - @reread - ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ?????????????????????? - - @node gnatreg : Registry Tool for NT - @section @code{gnatreg} : Registry Tool for NT - @findex gnatreg - @cindex Registry - - @menu - * Changing the GNAT compiler to Use:: - * Adding/Changing a Library Path:: - * Removing a Library Path:: - * List Current Configuration:: - @end menu - - @noindent - This tool can be used to switch from one compiler to another and to manage - the list of directories where GNAT must look to find packages. It is - also a convenient way to do network installation of GNAT. - - The form of the @code{gnatreg} command is - - @smallexample - $ gnatreg [@var{-hqcarf}] parameter - @end smallexample - - @noindent - Commons options are - - @table @code - - @item -h - print a usage message. - - @item -q - quiet/terse - display nothing, just do the job. - - @item -f - force mode - create the registry keys if they do not - exist. @code{gnatreg} will exit with an error if this option is omitted - and some registry keys are not setup correctly. - - @end table - - @subsection Changing the GNAT compiler to use - - @smallexample - $ gnatreg c:\gnatpro - @end smallexample - - @noindent - This will setup the registry to use the GNAT compiler that has been - installed under c:\gnatpro. @code{gnatreg} check that this directory contain - effectively a GNAT compiler. If you want to setup a network installation - and if GNAT has never been installed on this computer you'll have to use - the -f option. - - @subsection Adding/Changing a library path - - @smallexample - $ gnatreg -a COMPNT=c:\ada\components - @end smallexample - - @noindent - Add the directory c:\ada\components to the list of standards libraries. When - running gnatmake the option -Ic:\ada\components is added automatically to the - command line. - - The directory c:\ada\components is associated with the name COMPNT. This - name will be used to remove the library path. - - @subsection Removing a library path - - @smallexample - $ gnatreg -r COMPNT - @end smallexample - - @noindent - Remove the library path named COMPNT. - - @subsection List current configuration - - @smallexample - $ gnatreg -c - @end smallexample - - @noindent - @code{gnatreg} will display the GNAT and AdaGIDE path used and - all the standards libraries and their associated names that have been set. - - @end ignore - - - - @node Performance Considerations - @chapter Performance Considerations - @cindex Performance - - @noindent - The GNAT system provides a number of options that allow a trade-off - between - - @itemize @bullet - @item - performance of the generated code - - @item - speed of compilation - - @item - minimization of dependences and recompilation - - @item - the degree of run-time checking. - @end itemize - - @noindent - The defaults (if no options are selected) aim at improving the speed - of compilation and minimizing dependences, at the expense of performance - of the generated code: - - @itemize @bullet - @item - no optimization - - @item - no inlining of subprogram calls - - @item - all run-time checks enabled except overflow and elaboration checks - @end itemize - - @noindent - These options are suitable for most program development purposes. This - chapter describes how you can modify these choices, and also provides - some guidelines on debugging optimized code. - - @menu - * Controlling Run-Time Checks:: - * Optimization Levels:: - * Debugging Optimized Code:: - * Inlining of Subprograms:: - @end menu - - @node Controlling Run-Time Checks - @section Controlling Run-Time Checks - - @noindent - By default, GNAT generates all run-time checks, except arithmetic overflow - checking for integer operations and checks for access before elaboration on - subprogram calls. The latter are not required in default mode, because all - necessary checking is done at compile time. - @cindex @option{-gnatp} (@code{gcc}) - @cindex @option{-gnato} (@code{gcc}) - Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to - be modified. @xref{Run-Time Checks}. - - Our experience is that the default is suitable for most development - purposes. - - We treat integer overflow specially because these - are quite expensive and in our experience are not as important as other - run-time checks in the development process. Note that division by zero - is not considered an overflow check, and divide by zero checks are - generated where required by default. - - Elaboration checks are off by default, and also not needed by default, since - GNAT uses a static elaboration analysis approach that avoids the need for - run-time checking. This manual contains a full chapter discussing the issue - of elaboration checks, and if the default is not satisfactory for your use, - you should read this chapter. - - For validity checks, the minimal checks required by the Ada Reference - Manual (for case statements and assignments to array elements) are on - by default. These can be suppressed by use of the @option{-gnatVn} switch. - Note that in Ada 83, there were no validity checks, so if the Ada 83 mode - is acceptable (or when comparing GNAT performance with an Ada 83 compiler), - it may be reasonable to routinely use @option{-gnatVn}. Validity checks - are also suppressed entirely if @option{-gnatp} is used. - - @cindex Overflow checks - @cindex Checks, overflow - @findex Suppress - @findex Unsuppress - @cindex pragma Suppress - @cindex pragma Unsuppress - Note that the setting of the switches controls the default setting of - the checks. They may be modified using either @code{pragma Suppress} (to - remove checks) or @code{pragma Unsuppress} (to add back suppressed - checks) in the program source. - - @node Optimization Levels - @section Optimization Levels - @cindex @code{-O} (@code{gcc}) - - @noindent - The default is optimization off. This results in the fastest compile - times, but GNAT makes absolutely no attempt to optimize, and the - generated programs are considerably larger and slower than when - optimization is enabled. You can use the - @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3, - on the @code{gcc} command line to control the optimization level: - - @table @code - @item -O0 - no optimization (the default) - - @item -O1 - medium level optimization - - @item -O2 - full optimization - - @item -O3 - full optimization, and also attempt automatic inlining of small - subprograms within a unit (@pxref{Inlining of Subprograms}). - @end table - - Higher optimization levels perform more global transformations on the - program and apply more expensive analysis algorithms in order to generate - faster and more compact code. The price in compilation time, and the - resulting improvement in execution time, - both depend on the particular application and the hardware environment. - You should experiment to find the best level for your application. - - Note: Unlike some other compilation systems, @code{gcc} has - been tested extensively at all optimization levels. There are some bugs - which appear only with optimization turned on, but there have also been - bugs which show up only in @emph{unoptimized} code. Selecting a lower - level of optimization does not improve the reliability of the code - generator, which in practice is highly reliable at all optimization - levels. - - Note regarding the use of @code{-O3}: The use of this optimization level - is generally discouraged with GNAT, since it often results in larger - executables which run more slowly. See further discussion of this point - in @pxref{Inlining of Subprograms}. - - @node Debugging Optimized Code - @section Debugging Optimized Code - - @noindent - Since the compiler generates debugging tables for a compilation unit before - it performs optimizations, the optimizing transformations may invalidate some - of the debugging data. You therefore need to anticipate certain - anomalous situations that may arise while debugging optimized code. This - section describes the most common cases. - - @enumerate - @item - @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC - bouncing back and forth in the code. This may result from any of the following - optimizations: - - @itemize @bullet - @item - @i{Common subexpression elimination:} using a single instance of code for a - quantity that the source computes several times. As a result you - may not be able to stop on what looks like a statement. - - @item - @i{Invariant code motion:} moving an expression that does not change within a - loop, to the beginning of the loop. - - @item - @i{Instruction scheduling:} moving instructions so as to - overlap loads and stores (typically) with other code, or in - general to move computations of values closer to their uses. Often - this causes you to pass an assignment statement without the assignment - happening and then later bounce back to the statement when the - value is actually needed. Placing a breakpoint on a line of code - and then stepping over it may, therefore, not always cause all the - expected side-effects. - @end itemize - - @item - @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two - identical pieces of code are merged and the program counter suddenly - jumps to a statement that is not supposed to be executed, simply because - it (and the code following) translates to the same thing as the code - that @emph{was} supposed to be executed. This effect is typically seen in - sequences that end in a jump, such as a @code{goto}, a @code{return}, or - a @code{break} in a C @code{switch} statement. - - @item - @i{The "roving variable":} The symptom is an unexpected value in a variable. - There are various reasons for this effect: - - @itemize @bullet - @item - In a subprogram prologue, a parameter may not yet have been moved to its - "home". - - @item - A variable may be dead, and its register re-used. This is - probably the most common cause. - - @item - As mentioned above, the assignment of a value to a variable may - have been moved. - - @item - A variable may be eliminated entirely by value propagation or - other means. In this case, GCC may incorrectly generate debugging - information for the variable - @end itemize - - @noindent - In general, when an unexpected value appears for a local variable or parameter - you should first ascertain if that value was actually computed by - your program, as opposed to being incorrectly reported by the debugger. - Record fields or - array elements in an object designated by an access value - are generally less of a problem, once you have ascertained that the access value - is sensible. - Typically, this means checking variables in the preceding code and in the - calling subprogram to verify that the value observed is explainable from other - values (one must apply the procedure recursively to those - other values); or re-running the code and stopping a little earlier - (perhaps before the call) and stepping to better see how the variable obtained - the value in question; or continuing to step @emph{from} the point of the - strange value to see if code motion had simply moved the variable's - assignments later. - @end enumerate - - @node Inlining of Subprograms - @section Inlining of Subprograms - - @noindent - A call to a subprogram in the current unit is inlined if all the - following conditions are met: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else that @code{gcc} - cannot support in inlined subprograms. - - @item - The call occurs after the definition of the body of the subprogram. - - @item - @cindex pragma Inline - @findex Inline - Either @code{pragma Inline} applies to the subprogram or it is - small and automatic inlining (optimization level @code{-O3}) is - specified. - @end itemize - - @noindent - Calls to subprograms in @code{with}'ed units are normally not inlined. - To achieve this level of inlining, the following conditions must all be - true: - - @itemize @bullet - @item - The optimization level is at least @code{-O1}. - - @item - The called subprogram is suitable for inlining: It must be small enough - and not contain nested subprograms or anything else @code{gcc} cannot - support in inlined subprograms. - - @item - The call appears in a body (not in a package spec). - - @item - There is a @code{pragma Inline} for the subprogram. - - @item - @cindex @option{-gnatn} (@code{gcc}) - The @code{-gnatn} switch - is used in the @code{gcc} command line - @end itemize - - Note that specifying the @option{-gnatn} switch causes additional - compilation dependencies. Consider the following: - - @smallexample - @group - @cartouche - @b{package} R @b{is} - @b{procedure} Q; - @b{pragma} Inline (Q); - @b{end} R; - @b{package body} R @b{is} - ... - @b{end} R; - - @b{with} R; - @b{procedure} Main @b{is} - @b{begin} - ... - R.Q; - @b{end} Main; - @end cartouche - @end group - @end smallexample - - @noindent - With the default behavior (no @option{-gnatn} switch specified), the - compilation of the @code{Main} procedure depends only on its own source, - @file{main.adb}, and the spec of the package in file @file{r.ads}. This - means that editing the body of @code{R} does not require recompiling - @code{Main}. - - On the other hand, the call @code{R.Q} is not inlined under these - circumstances. If the @option{-gnatn} switch is present when @code{Main} - is compiled, the call will be inlined if the body of @code{Q} is small - enough, but now @code{Main} depends on the body of @code{R} in - @file{r.adb} as well as on the spec. This means that if this body is edited, - the main program must be recompiled. Note that this extra dependency - occurs whether or not the call is in fact inlined by @code{gcc}. - - The use of front end inlining with @option{-gnatN} generates similar - additional dependencies. - - @cindex @code{-fno-inline} (@code{gcc}) - Note: The @code{-fno-inline} switch - can be used to prevent - all inlining. This switch overrides all other conditions and ensures - that no inlining occurs. The extra dependences resulting from - @option{-gnatn} will still be active, even if - this switch is used to suppress the resulting inlining actions. - - Note regarding the use of @code{-O3}: There is no difference in inlining - behavior between @code{-O2} and @code{-O3} for subprograms with an explicit - pragma @code{Inline} assuming the use of @option{-gnatn} - or @option{-gnatN} (the switches that activate inlining). If you have used - pragma @code{Inline} in appropriate cases, then it is usually much better - to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which - in this case only has the effect of inlining subprograms you did not - think should be inlined. We often find that the use of @code{-O3} slows - down code by performing excessive inlining, leading to increased instruction - cache pressure from the increased code size. So the bottom line here is - that you should not automatically assume that @code{-O3} is better than - @code{-O2}, and indeed you should use @code{-O3} only if tests show that - it actually improves performance. - - - @include fdl.texi - @c GNU Free Documentation License - - @node Index,,GNU Free Documentation License, Top - @unnumbered Index - - @printindex cp - - @contents - - @bye --- 0 ---- diff -Nrc3pad gcc-3.4.0/gcc/ada/Make-lang.in gcc-3.4.1/gcc/ada/Make-lang.in *** gcc-3.4.0/gcc/ada/Make-lang.in 2004-01-31 00:45:25.000000000 +0000 --- gcc-3.4.1/gcc/ada/Make-lang.in 2004-06-09 09:20:41.000000000 +0000 *************** ada.tags: force *** 442,488 **** # Generate documentation. - # - # The generated Texinfo files for the User Guide are stored in $(srcdir). - # - # ??? There is some ugliness here in that the aforementioned generated - # documentation files depend on executables in the build tree. Since the - # source directory is supposed to be read only it is difficult to ship a source - # tree with the documentation already generated such that "make" will not - # attempt to rebuild them. - # - # As a compromise this only will execute with --enable-maintainer mode. - # - # If gnu make 3.80 is ever made a requirement to build, then this could be - # avoided using an order-only dependency: - # - # $(srcdir)/ada/gnat_ug_unx.texi: \ - # ada/gnat_ug.texi ada/ug_words | ada/doctools/xgnatug$(build_exeext) ! ifndef MAINT ! ada/doctools/xgnatug$(build_exeext): ada/xgnatug.adb -$(MKDIR) ada/doctools ! cp $^ ada/doctools ! cd ada/doctools && gnatmake -q xgnatug ! ! $(srcdir)/ada/gnat_ug_unx.texi : ada/doctools/xgnatug$(build_exeext) \ ! $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words ! ada/doctools/xgnatug unx $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words $(srcdir)/ada/gnat_ug_unx.texi ! ! $(srcdir)/ada/gnat_ug_vms.texi : ada/doctools/xgnatug$(build_exeext) \ ! $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words ! ada/doctools/xgnatug vms $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words $(srcdir)/ada/gnat_ug_vms.texi ! ! $(srcdir)/ada/gnat_ug_vxw.texi : ada/doctools/xgnatug$(build_exeext) \ ! $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words ! ada/doctools/xgnatug vxworks $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words $(srcdir)/ada/gnat_ug_vxw.texi ! $(srcdir)/ada/gnat_ug_wnt.texi : ada/doctools/xgnatug$(build_exeext) \ ! $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words ! ada/doctools/xgnatug wnt $(srcdir)/ada/gnat_ug.texi $(srcdir)/ada/ug_words $(srcdir)/ada/gnat_ug_wnt.texi ! endif ! doc/gnat_ug_unx.info: $(srcdir)/ada/gnat_ug_unx.texi \ $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi if [ x$(BUILD_INFO) = xinfo ]; then \ rm -f $(@)*; \ --- 442,458 ---- # Generate documentation. ! ada/doctools/xgnatugn$(build_exeext): ada/xgnatugn.adb -$(MKDIR) ada/doctools ! $(CP) $^ ada/doctools ! cd ada/doctools && gnatmake -q xgnatugn ! doc/gnat_ugn_unw.texi : ada/doctools/xgnatugn$(build_exeext) \ ! $(srcdir)/ada/gnat_ugn.texi $(srcdir)/ada/ug_words ! ada/doctools/xgnatugn unw $(srcdir)/ada/gnat_ugn.texi $(srcdir)/ada/ug_words doc/gnat_ugn_unw.texi ! doc/gnat_ugn_unw.info: doc/gnat_ugn_unw.texi \ $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi if [ x$(BUILD_INFO) = xinfo ]; then \ rm -f $(@)*; \ *************** doc/gnat_ug_unx.info: $(srcdir)/ada/gnat *** 490,519 **** -I$(srcdir)/ada -o $@ $<; \ else true; fi - doc/gnat_ug_vms.info: $(srcdir)/ada/gnat_ug_vms.texi \ - $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi - if [ x$(BUILD_INFO) = xinfo ]; then \ - rm -f $(@)*; \ - $(MAKEINFO) $(MAKEINFOFLAGS) -I$(docdir)/include \ - -I$(srcdir)/ada -o $@ $<; \ - else true; fi - - doc/gnat_ug_vxw.info: $(srcdir)/ada/gnat_ug_vxw.texi \ - $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi - if [ x$(BUILD_INFO) = xinfo ]; then \ - rm -f $(@)*; \ - $(MAKEINFO) $(MAKEINFOFLAGS) -I$(docdir)/include \ - -I$(srcdir)/ada -o $@ $<; \ - else true; fi - - doc/gnat_ug_wnt.info: $(srcdir)/ada/gnat_ug_wnt.texi \ - $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi - if [ x$(BUILD_INFO) = xinfo ]; then \ - rm -f $(@)*; \ - $(MAKEINFO) $(MAKEINFOFLAGS) -I$(docdir)/include \ - -I$(srcdir)/ada -o$@ $<; \ - else true; fi - doc/gnat_rm.info: ada/gnat_rm.texi $(docdir)/include/fdl.texi \ $(docdir)/include/gcc-common.texi if [ x$(BUILD_INFO) = xinfo ]; then \ --- 460,465 ---- *************** doc/gnat-style.info: ada/gnat-style.texi *** 529,566 **** -I$(srcdir)/ada -o $@ $<; \ else true; fi ! ADA_INFOFILES = doc/gnat_ug_vms.info doc/gnat_ug_wnt.info \ ! doc/gnat_ug_unx.info doc/gnat_ug_vxw.info \ doc/gnat_rm.info doc/gnat-style.info ada.info: $(ADA_INFOFILES) ada.srcinfo: $(ADA_INFOFILES) ! -cp -p $^ $(srcdir)/doc ! install-info:: $(DESTDIR)$(infodir)/gnat_ug_vms.info \ ! $(DESTDIR)$(infodir)/gnat_ug_wnt.info \ ! $(DESTDIR)$(infodir)/gnat_ug_unx.info \ ! $(DESTDIR)$(infodir)/gnat_ug_vxw.info \ $(DESTDIR)$(infodir)/gnat_rm.info \ $(DESTDIR)$(infodir)/gnat-style.info ! dvi:: doc/gnat_ug_vms.dvi doc/gnat_ug_wnt.dvi doc/gnat_ug_unx.dvi \ ! doc/gnat_ug_vxw.dvi doc/gnat_rm.dvi doc/gnat-style.dvi ! ! doc/gnat_ug_unx.dvi: $(srcdir)/ada/gnat_ug_unx.texi \ ! $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi ! $(TEXI2DVI) -c -I $(abs_docdir)/include -o $@ $< ! ! doc/gnat_ug_vms.dvi: $(srcdir)/ada/gnat_ug_vms.texi \ ! $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi ! $(TEXI2DVI) -c -I $(abs_docdir)/include -o $@ $< ! ! doc/gnat_ug_vxw.dvi: $(srcdir)/ada/gnat_ug_vxw.texi \ ! $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi ! $(TEXI2DVI) -c -I $(abs_docdir)/include -o $@ $< ! doc/gnat_ug_wnt.dvi: $(srcdir)/ada/gnat_ug_wnt.texi \ $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi $(TEXI2DVI) -c -I $(abs_docdir)/include -o $@ $< --- 475,496 ---- -I$(srcdir)/ada -o $@ $<; \ else true; fi ! ADA_INFOFILES = doc/gnat_ugn_unw.info \ doc/gnat_rm.info doc/gnat-style.info ada.info: $(ADA_INFOFILES) ada.srcinfo: $(ADA_INFOFILES) ! -$(CP) $^ $(srcdir)/doc ! install-info:: $(DESTDIR)$(infodir)/gnat_ugn_unw.info \ $(DESTDIR)$(infodir)/gnat_rm.info \ $(DESTDIR)$(infodir)/gnat-style.info ! dvi:: doc/gnat_ugn_unw.dvi \ ! doc/gnat_rm.dvi doc/gnat-style.dvi ! doc/gnat_ugn_unw.dvi: doc/gnat_ugn_unw.texi \ $(docdir)/include/fdl.texi $(docdir)/include/gcc-common.texi $(TEXI2DVI) -c -I $(abs_docdir)/include -o $@ $< diff -Nrc3pad gcc-3.4.0/gcc/ada/ug_words gcc-3.4.1/gcc/ada/ug_words *** gcc-3.4.0/gcc/ada/ug_words 2002-04-21 07:10:12.000000000 +0000 --- gcc-3.4.1/gcc/ada/ug_words 2004-06-09 09:20:44.000000000 +0000 *************** *** 1,134 **** ! Ada_Switches ^ Ada_Qualifiers ! b_ ^ B_ ! b~ ^ B$ ! cc1 ^ CC1 ! Cc1 ^ CC1 ! Default_Switches ^ Default_Qualifiers ! emacs ^ EMACS ! Emacs ^ EMACS ! gdb ^ GDB ! Gdb ^ GDB ! gnat1 ^ GNAT1 ! Gnat1 ^ GNAT1 ! gnatbind ^ GNAT BIND ! Gnatbind ^ GNAT BIND ! gnatchop ^ GNAT CHOP ! Gnatchop ^ GNAT CHOP ! gnatelim ^ GNAT ELIM ! Gnatelim ^ GNAT ELIM ! gnatf ^ GNAT XREF ! Gnatf ^ GNAT XREF ! gnatfind ^ GNAT FIND ! Gnatfind ^ GNAT FIND ! gnatkr ^ GNAT KRUNCH ! Gnatkr ^ GNAT KRUNCH ! gnatlbr ^ GNAT LIBRARY ! Gnatlbr ^ GNAT LIBRARY ! gnatlink ^ GNAT LINK ! Gnatlink ^ GNAT LINK ! gnatls ^ GNAT LIST ! Gnatls ^ GNAT LIST ! gnatmake ^ GNAT MAKE ! Gnatmake ^ GNAT MAKE ! gnatprep ^ GNAT PREPROCESS ! Gnatprep ^ GNAT PREPROCESS ! gnatpsta ^ GNAT STANDARD ! Gnatpsta ^ GNAT STANDARD ! gnatstub ^ GNAT STUB ! Gnatstub ^ GNAT STUB ! gnatxref ^ GNAT XREF ! Gnatxref ^ GNAT XREF ! gcc ^ GNAT COMPILE ! gcc -c ^ GNAT COMPILE ! -gnata ^ /CHECKS=ASSERTIONS ! -gnatb ^ /WARNINGS=BRIEF ! -gnatc ^ /NOLOAD ! -gnatdc ^ /TRACE_UNITS ! -gnatdO ^ /REPORT_ERRORS=IMMEDIATE ! -gnatC ^ /COMPRESS_NAMES ! -gnatD ^ /XDEBUG ! -gnatE ^ /CHECKS=ELABORATION ! -gnatf ^ /REPORT_ERRORS=FULL ! -gnatF ^ /UPPERCASE_EXTERNALS ! -gnatg ^ /STYLE=GNAT ! -gnatG ^ /EXPAND_SOURCE ! -gnatk ^ /FILE_NAME_MAX_LENGTH ! -gnatl ^ /LIST ! -gnatm ^ /ERROR_LIMIT ! -gnatm2 ^ /ERROR_LIMIT=2 ! -gnatn ^ /INLINE=PRAGMA ! -gnato ^ /CHECKS=OVERFLOW ! -gnatp ^ /CHECKS=SUPPRESS_ALL ! -gnatP ^ /POLLING_ENABLE ! -gnatr ^ /STYLE=REFERENCE_MANUAL ! -gnatR ^ /REPRESENTATION_INFO ! -gnatR0 ^ /REPRESENTATION_INFO=NONE ! -gnatR1 ^ /REPRESENTATION_INFO=ARRAYS ! -gnatR2 ^ /REPRESENTATION_INFO=OBJECTS ! -gnatR3 ^ /REPRESENTATION_INFO=SYMBOLIC ! -gnatq ^ /TRY_SEMANTICS ! -gnatQ ^ /FORCE_ALI ! -gnats ^ /SYNTAX_ONLY ! -gnatt ^ /TREE_OUTPUT ! -gnatu ^ /UNITS_LIST ! -gnatU ^ /UNIQUE_ERROR_TAG ! -gnatv ^ /REPORT_ERRORS=VERBOSE ! -gnatV ^ /VALIDITY_CHECKING ! -gnatV0 ^ /VALIDITY_CHECKING=NONE ! -gnatVd ^ /VALIDITY_CHECKING=RM ! -gnatVf ^ /VALIDITY_CHECKING=FULL ! -gnatwa ^ /WARNINGS=OPTIONAL ! -gnatwA ^ /WARNINGS=NOOPTIONAL ! -gnatwb ^ /WARNINGS=BIASED_ROUNDING ! -gnatwB ^ /WARNINGS=NOBIASED_ROUNDING ! -gnatwc ^ /WARNINGS=CONDITIONALS ! -gnatwC ^ /WARNINGS=NOCONDITIONALS ! -gnatwd ^ /WARNINGS=IMPLICIT_DEREFERENCE ! -gnatwD ^ /WARNINGS=NOIMPLICIT_DEREFERENCE ! -gnatwe ^ /WARNINGS=ERROR ! -gnatwf ^ /WARNINGS=UNREFERENCED_FORMALS ! -gnatwF ^ /WARNINGS=NOUNREFERENCED_FORMALS ! -gnatwh ^ /WARNINGS=HIDING ! -gnatwH ^ /WARNINGS=NOHIDING ! -gnatwi ^ /WARNINGS=IMPLEMENTATION ! -gnatwI ^ /WARNINGS=NOIMPLEMENTATION ! -gnatwl ^ /WARNINGS=ELABORATION ! -gnatwL ^ /WARNINGS=NOELABORATION ! -gnatwo ^ /WARNINGS=OVERLAYS ! -gnatwO ^ /WARNINGS=NOOVERLAYS ! -gnatwr ^ /WARNINGS=REDUNDANT ! -gnatwR ^ /WARNINGS=NOREDUNDANT ! -gnatws ^ /WARNINGS=SUPPRESS ! -gnatwu ^ /WARNINGS=UNUSED ! -gnatwU ^ /WARNINGS=NOUNUSED ! -gnatW8 ^ /WIDE_CHARACTER_ENCODING=UTF8 ! -gnatW? ^ /WIDE_CHARACTER_ENCODING=? ! -gnaty ^ /STYLE= ! -gnatzr ^ /DISTRIBUTION_STUBS=RECEIVER ! -gnatzs ^ /DISTRIBUTION_STUBS=SENDER ! -gnat83 ^ /83 ! -gnat95 ^ /95 ! -gnatx ^ /XREF=SUPPRESS ! -gnatX ^ /EXTENSIONS_ALLOWED ! --RTS ^ /RUNTIME_SYSTEM ! mode_switches ^ mode_qualifiers ! switch ^ qualifier ! switches ^ qualifiers ! Switch ^ Qualifier ! Switches ^ Qualifiers ! switch-related ^ qualifier-related ! stdout ^ SYS$OUTPUT ! stderr ^ SYS$ERROR ! -bargs ^ /BINDER_QUALIFIERS ! -cargs ^ /COMPILER_QUALIFIERS ! -largs ^ /LINKER_QUALIFIERS ! -aIDIR ^ /SOURCE_SEARCH=direc ! -aODIR ^ /OBJECT_SEARCH=direc ! -IDIR ^ /SEARCH=direc ! -nostdinc ^ /NOSTD_INCLUDES ! -nostdlib ^ /NOSTD_LIBRARIES ! -pFILE ^ /PROJECT=file ! -O0 ^ /OPTIMIZE=NONE ! -O1 ^ /OPTIMIZE=SOME ! -O2 ^ /OPTIMIZE=ALL ! -O3 ^ /OPTIMIZE=INLINING --- 1,173 ---- ! b_ ^ B_ ! b~ ^ B$ ! cc1 ^ CC1 ! Cc1 ^ CC1 ! emacs ^ EMACS ! Emacs ^ EMACS ! gdb ^ GDB ! Gdb ^ GDB ! gnat1 ^ GNAT1 ! Gnat1 ^ GNAT1 ! gnatbind ^ GNAT BIND ! Gnatbind ^ GNAT BIND ! gnatchop ^ GNAT CHOP ! Gnatchop ^ GNAT CHOP ! gnatclean ^ GNAT CLEAN ! Gnatclean ^ GNAT CLEAN ! gnatelim ^ GNAT ELIM ! Gnatelim ^ GNAT ELIM ! gnatf ^ GNAT XREF ! Gnatf ^ GNAT XREF ! gnatfind ^ GNAT FIND ! Gnatfind ^ GNAT FIND ! gnatkr ^ GNAT KRUNCH ! Gnatkr ^ GNAT KRUNCH ! gnatlbr ^ GNAT LIBRARY ! Gnatlbr ^ GNAT LIBRARY ! gnatlink ^ GNAT LINK ! Gnatlink ^ GNAT LINK ! gnatls ^ GNAT LIST ! Gnatls ^ GNAT LIST ! gnatmake ^ GNAT MAKE ! Gnatmake ^ GNAT MAKE ! gnatname ^ GNAT NAME ! Gnatname ^ GNAT NAME ! gnatpp ^ GNAT PRETTY ! Gnatpp ^ GNAT PRETTY ! gnatprep ^ GNAT PREPROCESS ! Gnatprep ^ GNAT PREPROCESS ! gnatpsta ^ GNAT STANDARD ! Gnatpsta ^ GNAT STANDARD ! gnatstub ^ GNAT STUB ! Gnatstub ^ GNAT STUB ! gnatxref ^ GNAT XREF ! Gnatxref ^ GNAT XREF ! gcc ^ GNAT COMPILE ! gcc -c ^ GNAT COMPILE ! -fno-inline ^ /INLINE=SUPPRESS ! -fstack-check ^ /CHECKS=STACK ! -gnata ^ /CHECKS=ASSERTIONS ! -gnatA ^ /NO_GNAT_ADC ! -gnatb ^ /REPORT_ERRORS=BRIEF ! -gnatc ^ /NOLOAD ! -gnatdc ^ /TRACE_UNITS ! -gnatdO ^ /REPORT_ERRORS=IMMEDIATE ! -gnatC ^ /COMPRESS_NAMES ! -gnatD ^ /XDEBUG ! -gnatec ^ /CONFIGURATION_PRAGMAS_FILE ! -gnateD ^ /SYMBOL_PREPROCESSING ! -gnatef ^ /FULL_PATH_IN_BRIEF_MESSAGES ! -gnatem ^ /MAPPING_FILE ! -gnatep ^ /DATA_PREPROCESSING ! -gnatE ^ /CHECKS=ELABORATION ! -gnatf ^ /REPORT_ERRORS=FULL ! -gnatF ^ /UPPERCASE_EXTERNALS ! -gnatg ^ /STYLE_CHECKS=GNAT ! -gnatG ^ /EXPAND_SOURCE ! -gnatk ^ /FILE_NAME_MAX_LENGTH ! -gnatl ^ /LIST ! -gnatL ^ /LONGJMP_SETJMP ! -gnatm ^ /ERROR_LIMIT ! -gnatm2 ^ /ERROR_LIMIT=2 ! -gnatn ^ /INLINE=PRAGMA ! -gnatN ^ /INLINE=FULL ! -gnato ^ /CHECKS=OVERFLOW ! -gnatp ^ /CHECKS=SUPPRESS_ALL ! -gnatP ^ /POLLING ! -gnatR ^ /REPRESENTATION_INFO ! -gnatR0 ^ /REPRESENTATION_INFO=NONE ! -gnatR1 ^ /REPRESENTATION_INFO=ARRAYS ! -gnatR2 ^ /REPRESENTATION_INFO=OBJECTS ! -gnatR3 ^ /REPRESENTATION_INFO=SYMBOLIC ! -gnatq ^ /TRY_SEMANTICS ! -gnatQ ^ /FORCE_ALI ! -gnats ^ /SYNTAX_ONLY ! -gnatS ^ /PRINT_STANDARD ! -gnatt ^ /TREE_OUTPUT ! -gnatu ^ /UNITS_LIST ! -gnatU ^ /UNIQUE_ERROR_TAG ! -gnatv ^ /REPORT_ERRORS=VERBOSE ! -gnatV ^ /VALIDITY_CHECKING ! -gnatVa ^ /VALIDITY_CHECKING=ALL ! -gnatVc ^ /VALIDITY_CHECKING=COPIES ! -gnatVd ^ /VALIDITY_CHECKING=DEFAULT ! -gnatVD ^ /VALIDITY_CHECKING=NODEFAULT ! -gnatVf ^ /VALIDITY_CHECKING=FLOATS ! -gnatVi ^ /VALIDITY_CHECKING=IN_PARAMS ! -gnatVm ^ /VALIDITY_CHECKING=MOD_PARAMS ! -gnatVn ^ /VALIDITY_CHECKING=NONE ! -gnatVo ^ /VALIDITY_CHECKING=OPERANDS ! -gnatVp ^ /VALIDITY_CHECKING=PARAMETERS ! -gnatVr ^ /VALIDITY_CHECKING=RETURNS ! -gnatVs ^ /VALIDITY_CHECKING=SUBSCRIPTS ! -gnatVt ^ /VALIDITY_CHECKING=TESTS ! -gnatw ^ /WARNINGS ! -gnatwa ^ /WARNINGS=OPTIONAL ! -gnatwA ^ /WARNINGS=NOOPTIONAL ! -gnatwc ^ /WARNINGS=CONDITIONALS ! -gnatwC ^ /WARNINGS=NOCONDITIONALS ! -gnatwd ^ /WARNINGS=IMPLICIT_DEREFERENCE ! -gnatwD ^ /WARNINGS=NOIMPLICIT_DEREFERENCE ! -gnatwe ^ /WARNINGS=ERRORS ! -gnatwf ^ /WARNINGS=UNREFERENCED_FORMALS ! -gnatwF ^ /WARNINGS=NOUNREFERENCED_FORMALS ! -gnatwg ^ /WARNINGS=UNRECOGNIZED_PRAGMAS ! -gnatwG ^ /WARNINGS=NOUNRECOGNIZED_PRAGMAS ! -gnatwh ^ /WARNINGS=HIDING ! -gnatwH ^ /WARNINGS=NOHIDING ! -gnatwi ^ /WARNINGS=IMPLEMENTATION ! -gnatwI ^ /WARNINGS=NOIMPLEMENTATION ! -gnatwj ^ /WARNINGS=OBSOLESCENT ! -gnatwJ ^ /WARNINGS=NOOBSOLESCENT ! -gnatwk ^ /WARNINGS=CONSTANT_VARIABLES ! -gnatwK ^ /WARNINGS=NOCONSTANT_VARIABLES ! -gnatwl ^ /WARNINGS=ELABORATION ! -gnatwL ^ /WARNINGS=NOELABORATION ! -gnatwm ^ /WARNINGS=MODIFIED_UNREF ! -gnatwM ^ /WARNINGS=NOMODIFIED_UNREF ! -gnatwn ^ /WARNINGS=NORMAL ! -gnatwo ^ /WARNINGS=OVERLAYS ! -gnatwO ^ /WARNINGS=NOOVERLAYS ! -gnatwp ^ /WARNINGS=INEFFECTIVE_INLINE ! -gnatwP ^ /WARNINGS=NOINEFFECTIVE_INLINE ! -gnatwr ^ /WARNINGS=REDUNDANT ! -gnatwR ^ /WARNINGS=NOREDUNDANT ! -gnatws ^ /WARNINGS=SUPPRESS ! -gnatwu ^ /WARNINGS=UNUSED ! -gnatwU ^ /WARNINGS=NOUNUSED ! -gnatwv ^ /WARNINGS=VARIABLES_UNINITIALIZED ! -gnatwV ^ /WARNINGS=NOVARIABLES_UNINITIALIZED ! -gnatwx ^ /WARNINGS=IMPORT_EXPORT_PRAGMAS ! -gnatwX ^ /WARNINGS=NOIMPORT_EXPORT_PRAGMAS ! -gnatwz ^ /WARNINGS=UNCHECKED_CONVERSIONS ! -gnatwZ ^ /WARNINGS=NOUNCHECKED_CONVERSIONS ! -gnatW8 ^ /WIDE_CHARACTER_ENCODING=UTF8 ! -gnatW? ^ /WIDE_CHARACTER_ENCODING=? ! -gnaty ^ /STYLE_CHECKS ! -gnatZ ^ /ZERO_COST_EXCEPTIONS ! -gnatzc ^ /DISTRIBUTION_STUBS=CALLER ! -gnatzr ^ /DISTRIBUTION_STUBS=RECEIVER ! -gnat83 ^ /83 ! -gnatx ^ /XREF=SUPPRESS ! -gnatX ^ /EXTENSIONS_ALLOWED ! --RTS ^ /RUNTIME_SYSTEM ! switch ^ qualifier ! switches ^ qualifiers ! Switch ^ Qualifier ! Switches ^ Qualifiers ! stdout ^ SYS$OUTPUT ! stderr ^ SYS$ERROR ! -bargs ^ /BINDER_QUALIFIERS ! -cargs ^ /COMPILER_QUALIFIERS ! -largs ^ /LINKER_QUALIFIERS ! -margs ^ /MAKE_QUALIFIERS ! -aIDIR ^ /SOURCE_SEARCH=direc ! -aODIR ^ /OBJECT_SEARCH=direc ! -IDIR ^ /SEARCH=direc ! -nostdinc ^ /NOSTD_INCLUDES ! -nostdlib ^ /NOSTD_LIBRARIES ! -pFILE ^ /PROJECT=file ! -O0 ^ /OPTIMIZE=NONE ! -O1 ^ /OPTIMIZE=SOME ! -O2 ^ /OPTIMIZE=ALL ! -O3 ^ /OPTIMIZE=INLINING diff -Nrc3pad gcc-3.4.0/gcc/ada/xgnatug.adb gcc-3.4.1/gcc/ada/xgnatug.adb *** gcc-3.4.0/gcc/ada/xgnatug.adb 2002-04-21 07:10:12.000000000 +0000 --- gcc-3.4.1/gcc/ada/xgnatug.adb 1970-01-01 00:00:00.000000000 +0000 *************** *** 1,1247 **** - ------------------------------------------------------------------------------ - -- -- - -- GNAT SYSTEM UTILITIES -- - -- -- - -- X G N A T U G -- - -- -- - -- B o d y -- - -- -- - -- Copyright (C) 2002 Free Software Foundation, Inc. -- - -- -- - -- GNAT is free software; you can redistribute it and/or modify it under -- - -- terms of the GNU General Public License as published by the Free Soft- -- - -- ware Foundation; either version 2, or (at your option) any later ver- -- - -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- - -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- - -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- - -- for more details. You should have received a copy of the GNU General -- - -- Public License distributed with GNAT; see file COPYING. If not, write -- - -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- - -- MA 02111-1307, USA. -- - -- -- - ------------------------------------------------------------------------------ - - -- This utility is used to process the source of gnat_ug.texi to make a - -- version suitable for running through standard Texinfo processor. It takes - -- three arguments. The first one is the target type of the manual, which - -- can be one of: - -- - -- unx GNU - -- vms OpenVMS - -- wnt Mirosoft Windows - -- vxworks Embedded Platforms - -- - -- The second parameter is the file name of the Texinfo file to be - -- preprocessed. - -- - -- The third parameter is the name of the word list. This file is used for - -- rewriting the VMS edition. Each line contains a word mapping: The source - -- word in the first column, the target words in the second column. The - -- columns are separated by a '^' character. When preprocessing for VMS, the - -- first word is replaced with the second. (Words consist of letters, - -- digits, and the four characters "?-_~". A sequence of multiple words can - -- be replaced if they listed in the first column, separated by a single - -- space character. If multiple words are to be replaced, there has to be - -- replacement for each prefix.) - -- - -- The fourth parameter is the name of the output file. It defaults to - -- gnat_ug_unx.texi, gnat_ug_vms.texi, gnat_ug_wnt.texi or gnat_ug_vxw.texi, - -- depending on the target. - -- - -- The following steps are performed: - -- - -- In VMS mode - -- - -- Any occurrences of ^alpha^beta^ are replaced by beta. The sequence - -- must fit on a single line, and there can only be one occurrence on a - -- line. - -- - -- Any occurrences of a word in the Ug_Words list are replaced by the - -- appropriate vms equivalents. Note that replacements do not occur - -- within ^alpha^beta^ sequences. - -- - -- Any occurence of [filename].extension, where extension one of the - -- following: - -- - -- "o", "ads", "adb", "ali", "ada", "atb", "ats", "adc", "c" - -- - -- - -- replaced by the appropriate VMS names (all upper case with .o - -- replaced .OBJ). Note that replacements do not occur within - -- ^alpha^beta^ sequences. - -- - -- In UNX, VXWORKS or WNT mode - -- - -- Any occurrences of ^alpha^beta^ are replaced by alpha. The sequence - -- must fit on a single line. - -- - -- In all modes - -- - -- The sequence ^^^ is replaced by a single ^. This escape sequence - -- must be used if the literal character ^ is to appear in the - -- output. A line containing this escape sequence may not also contain - -- a ^alpha^beta^ sequence. - -- - -- Recognize @ifset and @ifclear (this is because we have menu problems - -- if we let makeinfo handle the ifset/ifclear pairs - - with Ada.Command_Line; use Ada.Command_Line; - with Ada.Strings; use Ada.Strings; - with Ada.Strings.Fixed; use Ada.Strings.Fixed; - with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; - with Ada.Strings.Maps; use Ada.Strings.Maps; - with Ada.Strings.Maps.Constants; use Ada.Strings.Maps.Constants; - with Ada.Text_IO; use Ada.Text_IO; - with GNAT.Spitbol; use GNAT.Spitbol; - with GNAT.Spitbol.Table_VString; use GNAT.Spitbol.Table_VString; - - procedure Xgnatug is - - procedure Usage; - -- Print usage information. Invoked if an invalid command line is - -- encountered. - - Output_File : File_Type; - -- The preprocessed output is written to this file. - - type Input_File is record - Name : VString; - Data : File_Type; - Line : Natural := 0; - end record; - -- Records information on an input file. Name and Line are used - -- in error messages, Line is updated automatically by Get_Line. - - function Get_Line (Input : access Input_File) return String; - -- Returns a line from Input and performs the necessary - -- line-oriented checks (length, character set, trailing spaces). - - Have_Errors : Boolean := False; - procedure Error - (Input : Input_File; - At_Character : Natural; - Message : String); - procedure Error - (Input : Input_File; - Message : String); - -- Prints a message reporting an error on line Input.Line. If - -- At_Character is not 0, indicate the exact character at which - -- the error occurs. - - procedure Warning - (Input : Input_File; - At_Character : Natural; - Message : String); - procedure Warning - (Input : Input_File; - Message : String); - -- Like Error, but just print a warning message. - - Dictionary_File : aliased Input_File; - procedure Read_Dictionary_File; - -- Dictionary_File is opened using the name given on the command - -- line. It contains the replacements for the Ug_Words list. - -- Read_Dictionary_File reads Dictionary_File and fills the - -- Ug_Words table. - - Source_File : aliased Input_File; - procedure Process_Source_File; - -- Source_File is opened using the name given on the command line. - -- It contains the Texinfo source code. Process_Source_File - -- performs the necessary replacements. - - type Target_Type is (VMS, WNT, UNX, VXWORKS); - Target : Target_Type; - -- The target for which preprocessing is performed: VMS, Windows, - -- GNU, and embedded platforms ("UNX" and "VXWORKS" are misnomers). - -- The Target avariable is initialized using the command line. - - Valid_Characters : constant Character_Set - := To_Set (Span => (' ', '~')); - -- This array controls which characters are permitted in the input - -- file (after line breaks have been removed). Valid characters - -- are all printable ASCII characters and the space character. - - Word_Characters : constant Character_Set - := (To_Set (Ranges => (('0', '9'), ('a', 'z'), ('A', 'Z'))) - or To_Set ("?-_~")); - -- The characters which are permitted in words. Other (valid) - -- characters are assumed to be delimiters between words. Note that - -- this set has to include all characters of the source words of the - -- Ug_Words dictionary. - - Reject_Trailing_Spaces : constant Boolean := True; - -- Controls whether Xgnatug rejects superfluous space characters - -- at the end of lines. - - Maximum_Line_Length : constant Positive := 2000; - Fatal_Line_Length_Limit : constant Positive := 5000; - Fatal_Line_Length : exception; - -- If Maximum_Line_Length is exceeded in an input file, an error - -- message is printed. If Fatal_Line_Length is exceeded, - -- execution terminates with a Fatal_Line_Length exception. - - VMS_Escape_Character : constant Character := '^'; - -- The character used to mark VMS alternatives (^alpha^beta^). - - Extensions : GNAT.Spitbol.Table_VString.Table (20); - procedure Initialize_Extensions; - -- This table records extensions and their replacement for - -- rewriting filenames in the VMS version of the manual. - - function Is_Extension (Extension : String) return Boolean; - function Get_Replacement_Extension (Extension : String) return String; - -- These functions query the replacement table. Is_Extension - -- checks if the given string is a known extension. - -- Get_Replacement returns the replacement extension. - - Ug_Words : GNAT.Spitbol.Table_VString.Table (200); - function Is_Known_Word (Word : String) return Boolean; - function Get_Replacement_Word (Word : String) return String; - -- The Ug_Words table lists replacement words for the VMS version - -- of the manual. Is_Known_Word and Get_Replacement_Word query - -- this table. The table is filled using Read_Dictionary_File. - - function Rewrite_Source_Line (Line : String) return String; - -- This subprogram takes a line and rewrites it according to Target. - -- It relies on information in Source_File to generate error messages. - - type Conditional is (Set, Clear); - procedure Push_Conditional (Cond : Conditional; Flag : Target_Type); - procedure Pop_Conditional (Cond : Conditional); - -- These subprograms deal with conditional processing (@ifset/@ifclear). - -- They rely on information in Source_File to generate error messages. - - function Currently_Excluding return Boolean; - -- Returns true if conditional processing directives imply that the - -- current line should not be included in the output. - - function VMS_Context_Determined return Boolean; - -- Returns true if, in the current conditional preprocessing context, we - -- always have a VMS or a non-VMS version, regardless of the value of - -- Target. - - procedure Check_No_Pending_Conditional; - -- Checks that all preprocessing directives have been properly matched by - -- their @end counterpart. If this is not the case, print an error - -- message. - - -- The following definitions implement a stack to track the conditional - -- preprocessing context. - - type Conditional_Context is record - Starting_Line : Positive; - Cond : Conditional; - Flag : Target_Type; - Excluding : Boolean; - end record; - - Conditional_Stack_Depth : constant := 3; - Conditional_Stack : array (1 .. Conditional_Stack_Depth) - of Conditional_Context; - Conditional_TOS : Natural := 0; - -- Pointer to the Top Of Stack for Conditional_Stack. - - ----------------------------------- - -- Implementation of Subprograms -- - ----------------------------------- - - ----------- - -- Usage -- - ----------- - - procedure Usage is - begin - Put_Line (Standard_Error, - "usage: xgnatug TARGET SOURCE DICTIONARY [OUTFILE]"); - New_Line; - Put_Line (Standard_Error, "TARGET is one of:"); - for T in Target_Type'Range loop - Put_Line (Standard_Error, " " & Target_Type'Image (T)); - end loop; - New_Line; - Put_Line (Standard_Error, "SOURCE is the source file to process."); - New_Line; - Put_Line (Standard_Error, "DICTIONARY is the name of a file " - & "that contains word replacements"); - Put_Line (Standard_Error, "for the VMS version."); - New_Line; - Put_Line (Standard_Error, - "OUT-FILE, if present, is the output file to be created;"); - Put_Line (Standard_Error, - "If OUT-FILE is absent, the output file is one of " & - "gnat_ug_unx.texi, "); - Put_Line (Standard_Error, - "gnat_ug_vms.texi, gnat_ug_wnt.texi or gnat_ug_vxw.texi, " & - "depending on TARGET."); - end Usage; - - -------------- - -- Get_Line -- - -------------- - - function Get_Line (Input : access Input_File) return String is - Line_Buffer : String (1 .. Fatal_Line_Length_Limit); - Last : Natural; - - begin - Input.Line := Input.Line + 1; - Get_Line (Input.Data, Line_Buffer, Last); - if Last = Line_Buffer'Last then - Error (Input.all, "line exceeds fatal line length limit"); - raise Fatal_Line_Length; - end if; - - declare - Line : String renames Line_Buffer (Line_Buffer'First .. Last); - - begin - for J in Line'Range loop - if not Is_In (Line (J), Valid_Characters) then - Error (Input.all, J, "invalid character"); - exit; - end if; - end loop; - - if Line'Length > Maximum_Line_Length then - Warning (Input.all, Maximum_Line_Length + 1, "line too long"); - end if; - - if Reject_Trailing_Spaces - and then Line'Length > 0 - and then Line (Line'Last) = ' ' - then - Error (Input.all, Line'Last, "trailing space character"); - end if; - - return Trim (Line, Right); - end; - end Get_Line; - - ----------- - -- Error -- - ----------- - - procedure Error - (Input : Input_File; - Message : String) - is - begin - Error (Input, 0, Message); - end Error; - - procedure Error - (Input : Input_File; - At_Character : Natural; - Message : String) - is - Line_Image : constant String := Integer'Image (Input.Line); - At_Character_Image : constant String := Integer'Image (At_Character); - -- These variables are required because we have to drop the leading - -- space character. - - begin - Have_Errors := True; - if At_Character > 0 then - Put_Line (Standard_Error, - S (Input.Name) & ':' - & Line_Image (Line_Image'First + 1 .. Line_Image'Last) & ':' - & At_Character_Image (At_Character_Image'First + 1 - .. At_Character_Image'Last) - & ": " - & Message); - else - Put_Line (Standard_Error, - S (Input.Name) & ':' - & Line_Image (Line_Image'First + 1 .. Line_Image'Last) - & ": " - & Message); - end if; - end Error; - - ------------- - -- Warning -- - ------------- - - procedure Warning - (Input : Input_File; - Message : String) - is - begin - Warning (Input, 0, Message); - end Warning; - - procedure Warning - (Input : Input_File; - At_Character : Natural; - Message : String) - is - Line_Image : constant String := Integer'Image (Input.Line); - At_Character_Image : constant String := Integer'Image (At_Character); - -- These variables are required because we have to drop the leading - -- space character. - - begin - if At_Character > 0 then - Put_Line (Standard_Error, - S (Input.Name) & ':' - & Line_Image (Line_Image'First + 1 .. Line_Image'Last) & ':' - & At_Character_Image (At_Character_Image'First + 1 - .. At_Character_Image'Last) - & ": warning: " - & Message); - else - Put_Line (Standard_Error, - S (Input.Name) & ':' - & Line_Image (Line_Image'First + 1 .. Line_Image'Last) - & ": warning: " - & Message); - end if; - end Warning; - - -------------------------- - -- Read_Dictionary_File -- - -------------------------- - - procedure Read_Dictionary_File is - begin - while not End_Of_File (Dictionary_File.Data) loop - declare - Line : String := Get_Line (Dictionary_File'Access); - Split : Natural := Index (Line, (1 => VMS_Escape_Character)); - - begin - if Line'Length = 0 then - Error (Dictionary_File, "empty line in dictionary file"); - elsif Line (Line'First) = ' ' then - Error (Dictionary_File, 1, "line starts with space character"); - elsif Split = 0 then - Error (Dictionary_File, "line does not contain " - & VMS_Escape_Character & " character"); - else - declare - Source : constant String - := Trim (Line (1 .. Split - 1), Both); - Target : constant String - := Trim (Line (Split + 1 .. Line'Last), Both); - Two_Spaces : constant Natural - := Index (Source, " "); - Non_Word_Character : constant Natural - := Index (Source, Word_Characters or To_Set (" "), - Outside); - - begin - if Two_Spaces /= 0 then - Error (Dictionary_File, Two_Spaces, - "multiple space characters in source word"); - end if; - - if Non_Word_Character /= 0 then - Error (Dictionary_File, Non_Word_Character, - "illegal character in source word"); - end if; - - if Source'Length = 0 then - Error (Dictionary_File, "source is empty"); - elsif Target'Length = 0 then - Error (Dictionary_File, "target is empty"); - else - Set (Ug_Words, Source, V (Target)); - - -- Ensure that if Source is a sequence of words - -- "WORD1 WORD2 ...", we already have a mapping for - -- "WORD1". - - for J in Source'Range loop - if Source (J) = ' ' then - declare - Prefix : String renames Source (Source'First - .. J - 1); - - begin - if not Is_Known_Word (Prefix) then - Error (Dictionary_File, - "prefix '" & Prefix - & "' not known at this point"); - end if; - end; - end if; - end loop; - end if; - end; - end if; - end; - end loop; - end Read_Dictionary_File; - - ------------------------- - -- Process_Source_Line -- - ------------------------- - - function Rewrite_Source_Line (Line : String) return String is - - -- We use a simple lexer to split the line into tokens: - -- - -- Word consisting entirely of Word_Characters - -- VMS_Alternative ^alpha^beta^ replacement (but not ^^^) - -- Space a space character - -- Other everything else (sequence of non-word characters) - -- VMS_Error incomplete VMS alternative - -- End_Of_Line no more characters on this line - -- - -- A sequence of three VMS_Escape_Characters is automatically - -- collapsed to an Other token. - - type Token_Span is record - First, Last : Positive; - end record; - -- The character range covered by a token in Line. - - type Token_Kind is (End_Of_Line, Word, Other, - VMS_Alternative, VMS_Error); - type Token_Record (Kind : Token_Kind := End_Of_Line) is record - First : Positive; - case Kind is - when Word | Other => - Span : Token_Span; - when VMS_Alternative => - Non_VMS, VMS : Token_Span; - when VMS_Error | End_Of_Line => - null; - end case; - end record; - - Input_Position : Positive := Line'First; - Token : Token_Record; - -- The position of the next character to be processed by Next_Token. - - procedure Next_Token; - -- Returns the next token in Line, starting at Input_Position. - - Rewritten_Line : VString; - -- Collects the line as it is rewritten. - - procedure Rewrite_Word; - -- The current token is assumed to be a Word. When processing the VMS - -- version of the manual, additional tokens are gathered to check if - -- we have a file name or a sequence of known words. - - procedure Maybe_Rewrite_Extension; - -- The current token is assumed to be Other. When processing the VMS - -- version of the manual and the token represents a single dot ".", - -- the following word is rewritten according to the rules for - -- extensions. - - VMS_Token_Seen : Boolean := False; - -- This is set to true if a VMS_Alternative has been encountered, or a - -- ^^^ token. - - procedure Next_Token is - Remaining_Line : String renames Line (Input_Position .. Line'Last); - Last_Character : Natural; - - begin - if Remaining_Line'Length = 0 then - Token := (End_Of_Line, Remaining_Line'First); - return; - end if; - - -- ^alpha^beta^, the VMS_Alternative case. - - if Remaining_Line (Remaining_Line'First) = VMS_Escape_Character then - declare - VMS_Second_Character, VMS_Third_Character : Natural; - - begin - if VMS_Token_Seen then - Error (Source_File, Remaining_Line'First, - "multiple " & VMS_Escape_Character - & " characters on a single line"); - else - VMS_Token_Seen := True; - end if; - - -- Find the second and third escape character. If one of - -- them is not present, generate an error token. - - VMS_Second_Character - := Index (Remaining_Line (Remaining_Line'First + 1 - .. Remaining_Line'Last), - (1 => VMS_Escape_Character)); - if VMS_Second_Character = 0 then - Input_Position := Remaining_Line'Last + 1; - Token := (VMS_Error, Remaining_Line'First); - return; - end if; - - VMS_Third_Character - := Index (Remaining_Line (VMS_Second_Character + 1 - .. Remaining_Line'Last), - (1 => VMS_Escape_Character)); - if VMS_Third_Character = 0 then - Input_Position := Remaining_Line'Last + 1; - Token := (VMS_Error, Remaining_Line'First); - return; - end if; - - -- Consume all the characters we are about to include in - -- the token. - - Input_Position := VMS_Third_Character + 1; - - -- Check if we are in a ^^^ situation, and return an Other - -- token in this case. - - if Remaining_Line'First + 1 = VMS_Second_Character - and then Remaining_Line'First + 2 = VMS_Third_Character - then - Token := (Other, Remaining_Line'First, - (Remaining_Line'First, Remaining_Line'First)); - return; - end if; - - Token := (VMS_Alternative, Remaining_Line'First, - (Remaining_Line'First + 1, VMS_Second_Character - 1), - (VMS_Second_Character + 1, VMS_Third_Character - 1)); - return; - end; - end if; -- VMS_Alternative - - -- The Word case. Search for characters not in Word_Characters. - -- We have found a word if the first non-word character is not - -- the first character in Remaining_Line, i.e. if Remaining_Line - -- starts with a word character. - - Last_Character := Index (Remaining_Line, Word_Characters, Outside); - if Last_Character /= Remaining_Line'First then - - - -- If we haven't found a character which is not in - -- Word_Characters, all remaining characters are part of the - -- current Word token. - - if Last_Character = 0 then - Last_Character := Remaining_Line'Last + 1; - end if; - - Input_Position := Last_Character; - Token := (Word, Remaining_Line'First, - (Remaining_Line'First, Last_Character - 1)); - return; - end if; - - -- Remaining characters are in the Other category. To speed - -- up processing, we collect them together if there are several - -- of them. - - Input_Position := Last_Character + 1; - Token := (Other, Remaining_Line'First, - (Remaining_Line'First, Last_Character)); - end Next_Token; - - procedure Rewrite_Word is - First_Word : String - renames Line (Token.Span.First .. Token.Span.Last); - - begin - -- We do not perform any error checking below, so we can just skip - -- all processing for the non-VMS version. - - if Target /= VMS then - Append (Rewritten_Line, First_Word); - Next_Token; - return; - end if; - - if Is_Known_Word (First_Word) then - - -- If we have a word from the dictionary, we look for the - -- longest possible sequence we can rewrite. - - declare - Seq : Token_Span := Token.Span; - Lost_Space : Boolean := False; - - begin - Next_Token; - loop - if Token.Kind = Other - and then Line (Token.Span.First .. Token.Span.Last) = " " - then - Next_Token; - if Token.Kind /= Word - or else not Is_Known_Word (Line (Seq.First - .. Token.Span.Last)) - then - -- When we reach this point, the following - -- conditions are true: - -- - -- Seq is a known word. - -- The previous token was a space character. - -- Seq extended to the current token is not a - -- known word. - - Lost_Space := True; - exit; - - else - - -- Extend Seq to cover the current (known) word. - - Seq.Last := Token.Span.Last; - Next_Token; - end if; - - else - -- When we reach this point, the following conditions - -- are true: - -- - -- Seq is a known word. - -- The previous token was a word. - -- The current token is not a space character. - - exit; - end if; - end loop; - - -- Rewrite Seq, and add the lost space if necessary. - - Append (Rewritten_Line, - Get_Replacement_Word (Line (Seq.First .. Seq.Last))); - if Lost_Space then - Append (Rewritten_Line, ' '); - end if; - - -- The unknown token will be processed during the - -- next iteration of the main loop. - return; - end; - end if; - - Next_Token; - if Token.Kind = Other - and then Line (Token.Span.First .. Token.Span.Last) = "." - then - - -- Deal with extensions. - - Next_Token; - if Token.Kind = Word - and then Is_Extension (Line (Token.Span.First - .. Token.Span.Last)) - then - -- We have discovered a file extension. Convert the file - -- name to upper case. - - Append (Rewritten_Line, - Translate (First_Word, Upper_Case_Map) & '.'); - Append (Rewritten_Line, - Get_Replacement_Extension - (Line (Token.Span.First .. Token.Span.Last))); - Next_Token; - else - -- We already have: Word ".", followed by an unknown - -- token. - - Append (Rewritten_Line, First_Word & '.'); - - -- The unknown token will be processed during the next - -- iteration of the main loop. - end if; - - - else - -- We have an unknown Word, followed by an unknown token. - -- The unknown token will be processed by the outer loop. - - Append (Rewritten_Line, First_Word); - end if; - end Rewrite_Word; - - procedure Maybe_Rewrite_Extension is - begin - -- Again, we need no special processing in the non-VMS case. - - if Target = VMS - and then Line (Token.Span.First .. Token.Span.Last) = "." - then - -- This extension is not preceded by a word, otherwise - -- Rewrite_Word would have handled it. - - Next_Token; - if Token.Kind = Word - and then Is_Extension (Line (Token.Span.First - .. Token.Span.Last)) - then - Append (Rewritten_Line, '.' & Get_Replacement_Extension - (Line (Token.Span.First .. Token.Span.Last))); - Next_Token; - else - Append (Rewritten_Line, '.'); - end if; - else - Append (Rewritten_Line, Line (Token.Span.First - .. Token.Span.Last)); - Next_Token; - end if; - end Maybe_Rewrite_Extension; - - -- Start of processing for Process_Source_Line - - begin - -- The following parser recognizes the following special token - -- sequences: - -- - -- Word "." Word rewrite as file name if second word is extension - -- Word " " Word rewrite as a single word using Ug_Words table - - Next_Token; - loop - case Token.Kind is - when End_Of_Line => - exit; - - when Word => - Rewrite_Word; - - when Other => - Maybe_Rewrite_Extension; - - when VMS_Alternative => - if VMS_Context_Determined then - Warning (Source_File, Token.First, - "VMS alternative already determined " - & "by conditionals"); - end if; - if Target = VMS then - Append (Rewritten_Line, Line (Token.VMS.First - .. Token.VMS.Last)); - else - Append (Rewritten_Line, Line (Token.Non_VMS.First - .. Token.Non_VMS.Last)); - end if; - Next_Token; - - when VMS_Error => - Error (Source_File, Token.First, "invalid VMS alternative"); - Next_Token; - end case; - end loop; - return S (Rewritten_Line); - end Rewrite_Source_Line; - - ------------------------- - -- Process_Source_File -- - ------------------------- - - procedure Process_Source_File is - Ifset : constant String := "@ifset "; - Ifclear : constant String := "@ifclear "; - Endsetclear : constant String := "@end "; - -- Strings to be recognized for conditional processing. - - begin - while not End_Of_File (Source_File.Data) loop - declare - Line : constant String := Get_Line (Source_File'Access); - Rewritten : constant String := Rewrite_Source_Line (Line); - -- We unconditionally rewrite the line so that we can check the - -- syntax of all lines, and not only those which are actually - -- included in the output. - - Have_Conditional : Boolean := False; - -- True if we have encountered a conditional preprocessing - -- directive. - Cond : Conditional; - -- The kind of the directive. - Flag : Target_Type; - -- Its flag. - - begin - -- If the line starts with @ifset or @ifclear, we try to convert - -- the following flag to one of our target types. If we fail, - -- Have_Conditional remains False. - - if Line'Length >= Ifset'Length - and then Line (1 .. Ifset'Length) = Ifset - then - Cond := Set; - declare - Arg : constant String - := Trim (Line (Ifset'Length + 1 .. Line'Last), Both); - - begin - Flag := Target_Type'Value (Arg); - if Translate (Target_Type'Image (Flag), Lower_Case_Map) - /= Arg - then - Error (Source_File, "flag has to be lowercase"); - end if; - Have_Conditional := True; - exception - when Constraint_Error => - Error (Source_File, "unknown flag for '@ifset'"); - end; - - elsif Line'Length >= Ifclear'Length - and then Line (1 .. Ifclear'Length) = Ifclear - then - Cond := Clear; - declare - Arg : constant String - := Trim (Line (Ifclear'Length + 1 .. Line'Last), Both); - - begin - Flag := Target_Type'Value (Arg); - if Translate (Target_Type'Image (Flag), Lower_Case_Map) - /= Arg - then - Error (Source_File, "flag has to be lowercase"); - end if; - Have_Conditional := True; - exception - when Constraint_Error => - Error (Source_File, "unknown flag for '@ifclear'"); - end; - end if; - - if Have_Conditional then - -- We create a new conditional context and suppress the - -- directive in the output. - - Push_Conditional (Cond, Flag); - - elsif Line'Length >= Endsetclear'Length - and then Line (1 .. Endsetclear'Length) = Endsetclear - then - -- The '@end ifset'/'@end ifclear' case is handled here. We - -- have to pop the conditional context. - - declare - First, Last : Natural; - begin - Find_Token (Source => Line (Endsetclear'Length + 1 - .. Line'Length), - Set => Letter_Set, - Test => Inside, - First => First, - Last => Last); - if Last = 0 then - Error (Source_File, "'@end' without argument"); - else - if Line (First .. Last) = "ifset" then - Have_Conditional := True; - Cond := Set; - elsif Line (First .. Last) = "ifclear" then - Have_Conditional := True; - Cond := Clear; - end if; - - if Have_Conditional then - Pop_Conditional (Cond); - end if; - - -- We fall through to the ordinary case for other @end - -- directives. - end if; -- @end without argument - end; - end if; -- Have_Conditional - - if not Have_Conditional then - -- The ordinary case. - if not Currently_Excluding then - Put_Line (Output_File, Rewritten); - end if; - end if; - end; - end loop; - Check_No_Pending_Conditional; - end Process_Source_File; - - --------------------------- - -- Initialize_Extensions -- - --------------------------- - - procedure Initialize_Extensions is - - procedure Add (Extension : String); - -- Adds an extension which is replaced with itself (in upper - -- case). - - procedure Add (Extension, Replacement : String); - -- Adds an extension with a custom replacement. - - procedure Add (Extension : String) is - begin - Add (Extension, Translate (Extension, Upper_Case_Map)); - end Add; - - procedure Add (Extension, Replacement : String) is - begin - Set (Extensions, Extension, V (Replacement)); - end Add; - - -- Start of processing for Initialize_Extensions - - begin - -- To avoid performance degradation, increase the constant in the - -- definition of Extensions above if you add more extensions here. - - Add ("o", "OBJ"); - Add ("ads"); - Add ("adb"); - Add ("ali"); - Add ("ada"); - Add ("atb"); - Add ("ats"); - Add ("adc"); - Add ("c"); - end Initialize_Extensions; - - ------------------ - -- Is_Extension -- - ------------------ - - function Is_Extension (Extension : String) return Boolean is - begin - return Present (Extensions, Extension); - end Is_Extension; - - ------------------------------- - -- Get_Replacement_Extension -- - ------------------------------- - - function Get_Replacement_Extension (Extension : String) return String is - begin - return S (Get (Extensions, Extension)); - end Get_Replacement_Extension; - - ------------------- - -- Is_Known_Word -- - ------------------- - - function Is_Known_Word (Word : String) return Boolean is - begin - return Present (Ug_Words, Word); - end Is_Known_Word; - - -------------------------- - -- Get_Replacement_Word -- - -------------------------- - - function Get_Replacement_Word (Word : String) return String is - begin - return S (Get (Ug_Words, Word)); - end Get_Replacement_Word; - - ---------------------- - -- Push_Conditional -- - ---------------------- - - procedure Push_Conditional (Cond : Conditional; Flag : Target_Type) is - Will_Exclude : Boolean; - begin - -- If we are already in an excluding context, inherit this property, - -- otherwise calculate it from scratch. - - if Conditional_TOS > 0 - and then Conditional_Stack (Conditional_TOS).Excluding - then - Will_Exclude := True; - else - case Cond is - when Set => - Will_Exclude := Flag /= Target; - when Clear => - Will_Exclude := Flag = Target; - end case; - end if; - - -- Check if the current directive is pointless because of a previous, - -- enclosing directive. - - for J in 1 .. Conditional_TOS loop - if Conditional_Stack (J).Flag = Flag then - Warning (Source_File, "directive without effect because of line" - & Integer'Image (Conditional_Stack (J).Starting_Line)); - end if; - end loop; - Conditional_TOS := Conditional_TOS + 1; - Conditional_Stack (Conditional_TOS) - := (Starting_Line => Source_File.Line, - Cond => Cond, - Flag => Flag, - Excluding => Will_Exclude); - end Push_Conditional; - - --------------------- - -- Pop_Conditional -- - --------------------- - - procedure Pop_Conditional (Cond : Conditional) is - begin - if Conditional_TOS > 0 then - case Cond is - when Set => - if Conditional_Stack (Conditional_TOS).Cond /= Set then - Error (Source_File, - "'@end ifset' does not match '@ifclear' at line" - & Integer'Image (Conditional_Stack - (Conditional_TOS).Starting_Line)); - end if; - when Clear => - if Conditional_Stack (Conditional_TOS).Cond /= Clear then - Error (Source_File, - "'@end ifclear' does not match '@ifset' at line" - & Integer'Image (Conditional_Stack - (Conditional_TOS).Starting_Line)); - end if; - end case; - Conditional_TOS := Conditional_TOS - 1; - else - case Cond is - when Set => - Error (Source_File, - "'@end ifset' without corresponding '@ifset'"); - when Clear => - Error (Source_File, - "'@end ifclear' without corresponding '@ifclear'"); - end case; - end if; - end Pop_Conditional; - - ------------------------- - -- Currently_Excluding -- - ------------------------- - - function Currently_Excluding return Boolean is - begin - return Conditional_TOS > 0 - and then Conditional_Stack (Conditional_TOS).Excluding; - end Currently_Excluding; - - ---------------------------- - -- VMS_Context_Determined -- - ---------------------------- - - function VMS_Context_Determined return Boolean is - begin - for J in 1 .. Conditional_TOS loop - if Conditional_Stack (J).Flag = VMS then - return True; - end if; - end loop; - return False; - end VMS_Context_Determined; - - ---------------------------------- - -- Check_No_Pending_Conditional -- - ---------------------------------- - - procedure Check_No_Pending_Conditional is - begin - for J in 1 .. Conditional_TOS loop - case Conditional_Stack (J).Cond is - when Set => - Error (Source_File, "Missing '@end ifset' for '@ifset' at line" - & Integer'Image (Conditional_Stack (J).Starting_Line)); - when Clear => - Error (Source_File, - "Missing '@end ifclear' for '@ifclear' at line" - & Integer'Image (Conditional_Stack (J).Starting_Line)); - end case; - end loop; - end Check_No_Pending_Conditional; - - ------------------ - -- Main Program -- - ------------------ - - Valid_Command_Line : Boolean; - Output_File_Name : VString; - - begin - Initialize_Extensions; - - Valid_Command_Line := Argument_Count in 3 .. 4; - - -- First argument: Target. - - if Valid_Command_Line then - begin - Target := Target_Type'Value (Argument (1)); - exception - when Constraint_Error => - Valid_Command_Line := False; - end; - end if; - - -- Second argument: Source_File. - - if Valid_Command_Line then - begin - Source_File.Name := V (Argument (2)); - Open (Source_File.Data, In_File, Argument (2)); - exception - when Name_Error => - Valid_Command_Line := False; - end; - end if; - - -- Third argument: Dictionary_File. - - if Valid_Command_Line then - begin - Dictionary_File.Name := V (Argument (3)); - Open (Dictionary_File.Data, In_File, Argument (3)); - exception - when Name_Error => - Valid_Command_Line := False; - end; - end if; - - -- Fourth argument: Output_File. - - if Valid_Command_Line then - if Argument_Count = 4 then - Output_File_Name := V (Argument (4)); - else - case Target is - when VMS => - Output_File_Name := V ("gnat_ug_vms.texi"); - when WNT => - Output_File_Name := V ("gnat_ug_wnt.texi"); - when UNX => - Output_File_Name := V ("gnat_ug_unx.texi"); - when VXWORKS => - Output_File_Name := V ("gnat_ug_vxw.texi"); - end case; - end if; - - begin - Create (Output_File, Out_File, S (Output_File_Name)); - exception - when Name_Error | Use_Error => - Valid_Command_Line := False; - end; - end if; - - if not Valid_Command_Line then - Usage; - Set_Exit_Status (Failure); - else - Read_Dictionary_File; - Close (Dictionary_File.Data); - - -- Main processing starts here. - - Process_Source_File; - Close (Output_File); - Close (Source_File.Data); - if Have_Errors then - Set_Exit_Status (Failure); - else - Set_Exit_Status (Success); - end if; - end if; - end Xgnatug; --- 0 ---- diff -Nrc3pad gcc-3.4.0/gcc/ada/xgnatugn.adb gcc-3.4.1/gcc/ada/xgnatugn.adb *** gcc-3.4.0/gcc/ada/xgnatugn.adb 1970-01-01 00:00:00.000000000 +0000 --- gcc-3.4.1/gcc/ada/xgnatugn.adb 2004-06-09 09:20:45.000000000 +0000 *************** *** 0 **** --- 1,1380 ---- + ------------------------------------------------------------------------------ + -- -- + -- GNAT SYSTEM UTILITIES -- + -- -- + -- X G N A T U G N -- + -- -- + -- B o d y -- + -- -- + -- Copyright (C) 2003-2004 Free Software Foundation, Inc. -- + -- -- + -- GNAT is free software; you can redistribute it and/or modify it under -- + -- terms of the GNU General Public License as published by the Free Soft- -- + -- ware Foundation; either version 2, or (at your option) any later ver- -- + -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- + -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- + -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- + -- for more details. You should have received a copy of the GNU General -- + -- Public License distributed with GNAT; see file COPYING. If not, write -- + -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- + -- MA 02111-1307, USA. -- + -- -- + ------------------------------------------------------------------------------ + + -- This utility is used to process the source of gnat_ugn.texi to make a + -- version suitable for running through standard Texinfo processor. It is + -- invoked as follows: + + -- xgnatugn [ [ ] ] + + -- 1. is the target type of the manual, which is one of: + + -- unw Unix and Windows platforms + -- vms OpenVMS + + -- 2. is the file name of the Texinfo file to be + -- preprocessed. + + -- 3. is the name of the word list file. This file is used for + -- rewriting the VMS edition. Each line contains a word mapping: The source + -- word in the first column, the target word in the second column. The + -- columns are separated by a '^' character. When preprocessing for VMS, the + -- first word is replaced with the second. (Words consist of letters, + -- digits, and the four characters "?-_~". A sequence of multiple words can + -- be replaced if they are listed in the first column, separated by a single + -- space character. If multiple words are to be replaced, there must be a + -- replacement for each prefix.) + + -- 4. (optional) is the name of the output file. It defaults to + -- gnat_ugn_unw.texi or gnat_ugn_vms.texi, depending on the target. + + -- 5. (optional, and allowed only if is explicit) + -- can be any string. If present, it indicates that warning messages are + -- to be output to Standard_Error. If absent, no warning messages are + -- generated. + + -- The following steps are performed: + + -- In VMS mode + + -- Any occurrences of ^alpha^beta^ are replaced by beta. The sequence + -- must fit on a single line, and there can only be one occurrence on a + -- line. + + -- Any occurrences of a word in the Ug_Words list are replaced by the + -- appropriate vms equivalents. Note that replacements do not occur + -- within ^alpha^beta^ sequences. + + -- Any occurence of [filename].extension, where extension one of the + -- following: + + -- "o", "ads", "adb", "ali", "ada", "atb", "ats", "adc", "c" + + -- replaced by the appropriate VMS names (all upper case with .o + -- replaced .OBJ). Note that replacements do not occur within + -- ^alpha^beta^ sequences. + + -- In UNW mode + + -- Any occurrences of ^alpha^beta^ are replaced by alpha. The sequence + -- must fit on a single line. + + -- In both modes + + -- The sequence ^^^ is replaced by a single ^. This escape sequence + -- must be used if the literal character ^ is to appear in the + -- output. A line containing this escape sequence may not also contain + -- a ^alpha^beta^ sequence. + + -- Recognize @ifset and @ifclear (this is because we have menu problems + -- if we let makeinfo handle the ifset/ifclear pairs + + with Ada.Command_Line; use Ada.Command_Line; + with Ada.Strings; use Ada.Strings; + with Ada.Strings.Fixed; use Ada.Strings.Fixed; + with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; + with Ada.Strings.Maps; use Ada.Strings.Maps; + with Ada.Strings.Maps.Constants; use Ada.Strings.Maps.Constants; + with Ada.Text_IO; use Ada.Text_IO; + + with GNAT.Spitbol; use GNAT.Spitbol; + with GNAT.Spitbol.Table_VString; use GNAT.Spitbol.Table_VString; + + procedure Xgnatugn is + + procedure Usage; + -- Print usage information. Invoked if an invalid command line is + -- encountered. + + Output_File : File_Type; + -- The preprocessed output is written to this file + + type Input_File is record + Name : VString; + Data : File_Type; + Line : Natural := 0; + end record; + -- Records information on an input file. Name and Line are used + -- in error messages, Line is updated automatically by Get_Line. + + function Get_Line (Input : access Input_File) return String; + -- Returns a line from Input and performs the necessary + -- line-oriented checks (length, character set, trailing spaces). + + Number_Of_Warnings : Natural := 0; + Number_Of_Errors : Natural := 0; + Warnings_Enabled : Boolean; + + procedure Error + (Input : Input_File; + At_Character : Natural; + Message : String); + procedure Error + (Input : Input_File; + Message : String); + -- Prints a message reporting an error on line Input.Line. If + -- At_Character is not 0, indicate the exact character at which + -- the error occurs. + + procedure Warning + (Input : Input_File; + At_Character : Natural; + Message : String); + procedure Warning + (Input : Input_File; + Message : String); + -- Like Error, but just print a warning message. + + Dictionary_File : aliased Input_File; + procedure Read_Dictionary_File; + -- Dictionary_File is opened using the name given on the command + -- line. It contains the replacements for the Ug_Words list. + -- Read_Dictionary_File reads Dictionary_File and fills the + -- Ug_Words table. + + Source_File : aliased Input_File; + procedure Process_Source_File; + -- Source_File is opened using the name given on the command line. + -- It contains the Texinfo source code. Process_Source_File + -- performs the necessary replacements. + + type Target_Type is (UNW, VMS); + Target : Target_Type; + -- The target for which preprocessing is performed: + -- UNW (Unix and Windows) or VMS + -- The Target variable is initialized using the command line. + + Valid_Characters : constant Character_Set + := To_Set (Span => (' ', '~')); + -- This array controls which characters are permitted in the input + -- file (after line breaks have been removed). Valid characters + -- are all printable ASCII characters and the space character. + + Word_Characters : constant Character_Set := + (To_Set (Ranges => + (('0', '9'), ('a', 'z'), ('A', 'Z'))) + or To_Set ("?-_~")); + -- The characters which are permitted in words. Other (valid) + -- characters are assumed to be delimiters between words. Note that + -- this set has to include all characters of the source words of the + -- Ug_Words dictionary. + + Reject_Trailing_Spaces : constant Boolean := True; + -- Controls whether Xgnatug rejects superfluous space characters + -- at the end of lines. + + Maximum_Line_Length : constant Positive := 79; + Fatal_Line_Length_Limit : constant Positive := 5000; + Fatal_Line_Length : exception; + -- If Maximum_Line_Length is exceeded in an input file, an error + -- message is printed. If Fatal_Line_Length is exceeded, + -- execution terminates with a Fatal_Line_Length exception. + + VMS_Escape_Character : constant Character := '^'; + -- The character used to mark VMS alternatives (^alpha^beta^). + + Extensions : GNAT.Spitbol.Table_VString.Table (20); + procedure Initialize_Extensions; + -- This table records extensions and their replacement for + -- rewriting filenames in the VMS version of the manual. + + function Is_Extension (Extension : String) return Boolean; + function Get_Replacement_Extension (Extension : String) return String; + -- These functions query the replacement table. Is_Extension + -- checks if the given string is a known extension. + -- Get_Replacement returns the replacement extension. + + Ug_Words : GNAT.Spitbol.Table_VString.Table (200); + function Is_Known_Word (Word : String) return Boolean; + function Get_Replacement_Word (Word : String) return String; + -- The Ug_Words table lists replacement words for the VMS version + -- of the manual. Is_Known_Word and Get_Replacement_Word query + -- this table. The table is filled using Read_Dictionary_File. + + function Rewrite_Source_Line (Line : String) return String; + -- This subprogram takes a line and rewrites it according to Target. + -- It relies on information in Source_File to generate error messages. + + type Conditional is (Set, Clear); + procedure Push_Conditional (Cond : Conditional; Flag : Target_Type); + procedure Pop_Conditional (Cond : Conditional); + -- These subprograms deal with conditional processing (@ifset/@ifclear). + -- They rely on information in Source_File to generate error messages. + + function Currently_Excluding return Boolean; + -- Returns true if conditional processing directives imply that the + -- current line should not be included in the output. + + function VMS_Context_Determined return Boolean; + -- Returns true if, in the current conditional preprocessing context, we + -- always have a VMS or a non-VMS version, regardless of the value of + -- Target. + + function In_VMS_Section return Boolean; + -- Returns True if in an "@ifset vms" section. + + procedure Check_No_Pending_Conditional; + -- Checks that all preprocessing directives have been properly matched by + -- their @end counterpart. If this is not the case, print an error + -- message. + + -- The following definitions implement a stack to track the conditional + -- preprocessing context. + + type Conditional_Context is record + Starting_Line : Positive; + Cond : Conditional; + Flag : Target_Type; + Excluding : Boolean; + end record; + + Conditional_Stack_Depth : constant := 3; + + Conditional_Stack : + array (1 .. Conditional_Stack_Depth) of Conditional_Context; + + Conditional_TOS : Natural := 0; + -- Pointer to the Top Of Stack for Conditional_Stack. + + ----------- + -- Usage -- + ----------- + + procedure Usage is + begin + Put_Line (Standard_Error, + "usage: xgnatug TARGET SOURCE DICTIONARY [OUTFILE [WARNINGS]]"); + New_Line; + Put_Line (Standard_Error, "TARGET is one of:"); + + for T in Target_Type'Range loop + Put_Line (Standard_Error, " " & Target_Type'Image (T)); + end loop; + + New_Line; + Put_Line (Standard_Error, "SOURCE is the source file to process."); + New_Line; + Put_Line (Standard_Error, "DICTIONARY is the name of a file " + & "that contains word replacements"); + Put_Line (Standard_Error, "for the VMS version."); + New_Line; + Put_Line (Standard_Error, + "OUT-FILE, if present, is the output file to be created;"); + Put_Line (Standard_Error, + "If OUT-FILE is absent, the output file is either " & + "gnat_ugn_unw.texi, "); + Put_Line (Standard_Error, + "or gnat_ugn_vms.texi, depending on TARGET."); + New_Line; + Put_Line (Standard_Error, + "WARNINGS, if present, is any string;"); + Put_Line (Standard_Error, + "it will result in warning messages (e.g., line too long))"); + Put_Line (Standard_Error, + "being output to Standard_Error."); + end Usage; + + -------------- + -- Get_Line -- + -------------- + + function Get_Line (Input : access Input_File) return String is + Line_Buffer : String (1 .. Fatal_Line_Length_Limit); + Last : Natural; + + begin + Input.Line := Input.Line + 1; + Get_Line (Input.Data, Line_Buffer, Last); + + if Last = Line_Buffer'Last then + Error (Input.all, "line exceeds fatal line length limit"); + raise Fatal_Line_Length; + end if; + + declare + Line : String renames Line_Buffer (Line_Buffer'First .. Last); + + begin + for J in Line'Range loop + if not Is_In (Line (J), Valid_Characters) then + Error (Input.all, J, "invalid character"); + exit; + end if; + end loop; + + if Line'Length > Maximum_Line_Length then + Warning (Input.all, Maximum_Line_Length + 1, "line too long"); + end if; + + if Reject_Trailing_Spaces + and then Line'Length > 0 + and then Line (Line'Last) = ' ' + then + Error (Input.all, Line'Last, "trailing space character"); + end if; + + return Trim (Line, Right); + end; + end Get_Line; + + ----------- + -- Error -- + ----------- + + procedure Error + (Input : Input_File; + Message : String) + is + begin + Error (Input, 0, Message); + end Error; + + procedure Error + (Input : Input_File; + At_Character : Natural; + Message : String) + is + Line_Image : constant String := Integer'Image (Input.Line); + At_Character_Image : constant String := Integer'Image (At_Character); + -- These variables are required because we have to drop the leading + -- space character. + + begin + Number_Of_Errors := Number_Of_Errors + 1; + + if At_Character > 0 then + Put_Line (Standard_Error, + S (Input.Name) & ':' + & Line_Image (Line_Image'First + 1 .. Line_Image'Last) & ':' + & At_Character_Image (At_Character_Image'First + 1 + .. At_Character_Image'Last) + & ": " + & Message); + else + Put_Line (Standard_Error, + S (Input.Name) & ':' + & Line_Image (Line_Image'First + 1 .. Line_Image'Last) + & ": " + & Message); + end if; + end Error; + + ------------- + -- Warning -- + ------------- + + procedure Warning + (Input : Input_File; + Message : String) + is + begin + if Warnings_Enabled then + Warning (Input, 0, Message); + end if; + end Warning; + + procedure Warning + (Input : Input_File; + At_Character : Natural; + Message : String) + is + Line_Image : constant String := Integer'Image (Input.Line); + At_Character_Image : constant String := Integer'Image (At_Character); + -- These variables are required because we have to drop the leading + -- space character. + + begin + if not Warnings_Enabled then + return; + end if; + + Number_Of_Warnings := Number_Of_Warnings + 1; + + if At_Character > 0 then + Put_Line (Standard_Error, + S (Input.Name) & ':' + & Line_Image (Line_Image'First + 1 .. Line_Image'Last) & ':' + & At_Character_Image (At_Character_Image'First + 1 + .. At_Character_Image'Last) + & ": warning: " + & Message); + else + Put_Line (Standard_Error, + S (Input.Name) & ':' + & Line_Image (Line_Image'First + 1 .. Line_Image'Last) + & ": warning: " + & Message); + end if; + end Warning; + + -------------------------- + -- Read_Dictionary_File -- + -------------------------- + + procedure Read_Dictionary_File is + begin + while not End_Of_File (Dictionary_File.Data) loop + declare + Line : constant String := + Get_Line (Dictionary_File'Access); + Split : constant Natural := + Index (Line, (1 => VMS_Escape_Character)); + + begin + if Line'Length = 0 then + Error (Dictionary_File, "empty line in dictionary file"); + + elsif Line (Line'First) = ' ' then + Error (Dictionary_File, 1, "line starts with space character"); + + elsif Split = 0 then + Error (Dictionary_File, "line does not contain " + & VMS_Escape_Character & " character"); + else + declare + Source : constant String := + Trim (Line (1 .. Split - 1), Both); + Target : constant String := + Trim (Line (Split + 1 .. Line'Last), Both); + Two_Spaces : constant Natural := + Index (Source, " "); + Non_Word_Character : constant Natural := + Index (Source, + Word_Characters or + To_Set (" "), + Outside); + + begin + if Two_Spaces /= 0 then + Error (Dictionary_File, Two_Spaces, + "multiple space characters in source word"); + end if; + + if Non_Word_Character /= 0 then + Error (Dictionary_File, Non_Word_Character, + "illegal character in source word"); + end if; + + if Source'Length = 0 then + Error (Dictionary_File, "source is empty"); + + elsif Target'Length = 0 then + Error (Dictionary_File, "target is empty"); + + else + Set (Ug_Words, Source, V (Target)); + + -- Ensure that if Source is a sequence of words + -- "WORD1 WORD2 ...", we already have a mapping for + -- "WORD1". + + for J in Source'Range loop + if Source (J) = ' ' then + declare + Prefix : String renames + Source (Source'First .. J - 1); + + begin + if not Is_Known_Word (Prefix) then + Error (Dictionary_File, + "prefix '" & Prefix + & "' not known at this point"); + end if; + end; + end if; + end loop; + end if; + end; + end if; + end; + end loop; + end Read_Dictionary_File; + + ------------------------- + -- Rewrite_Source_Line -- + ------------------------- + + function Rewrite_Source_Line (Line : String) return String is + + -- We use a simple lexer to split the line into tokens: + + -- Word consisting entirely of Word_Characters + -- VMS_Alternative ^alpha^beta^ replacement (but not ^^^) + -- Space a space character + -- Other everything else (sequence of non-word characters) + -- VMS_Error incomplete VMS alternative + -- End_Of_Line no more characters on this line + + -- A sequence of three VMS_Escape_Characters is automatically + -- collapsed to an Other token. + + type Token_Span is record + First, Last : Positive; + end record; + -- The character range covered by a token in Line + + type Token_Kind is (End_Of_Line, Word, Other, + VMS_Alternative, VMS_Error); + type Token_Record (Kind : Token_Kind := End_Of_Line) is record + First : Positive; + case Kind is + when Word | Other => + Span : Token_Span; + when VMS_Alternative => + Non_VMS, VMS : Token_Span; + when VMS_Error | End_Of_Line => + null; + end case; + end record; + + Input_Position : Positive := Line'First; + Token : Token_Record; + -- The position of the next character to be processed by Next_Token + + procedure Next_Token; + -- Returns the next token in Line, starting at Input_Position + + Rewritten_Line : VString; + -- Collects the line as it is rewritten + + procedure Rewrite_Word; + -- The current token is assumed to be a Word. When processing the VMS + -- version of the manual, additional tokens are gathered to check if + -- we have a file name or a sequence of known words. + + procedure Maybe_Rewrite_Extension; + -- The current token is assumed to be Other. When processing the VMS + -- version of the manual and the token represents a single dot ".", + -- the following word is rewritten according to the rules for + -- extensions. + + VMS_Token_Seen : Boolean := False; + -- This is set to true if a VMS_Alternative has been encountered, or a + -- ^^^ token. + + ---------------- + -- Next_Token -- + ---------------- + + procedure Next_Token is + Remaining_Line : String renames Line (Input_Position .. Line'Last); + Last_Character : Natural; + + begin + if Remaining_Line'Length = 0 then + Token := (End_Of_Line, Remaining_Line'First); + return; + end if; + + -- ^alpha^beta^, the VMS_Alternative case. + + if Remaining_Line (Remaining_Line'First) = VMS_Escape_Character then + declare + VMS_Second_Character, VMS_Third_Character : Natural; + + begin + if VMS_Token_Seen then + Error (Source_File, Remaining_Line'First, + "multiple " & VMS_Escape_Character + & " characters on a single line"); + else + VMS_Token_Seen := True; + end if; + + -- Find the second and third escape character. If one of + -- them is not present, generate an error token. + + VMS_Second_Character := + Index (Remaining_Line (Remaining_Line'First + 1 + .. Remaining_Line'Last), + (1 => VMS_Escape_Character)); + + if VMS_Second_Character = 0 then + Input_Position := Remaining_Line'Last + 1; + Token := (VMS_Error, Remaining_Line'First); + return; + end if; + + VMS_Third_Character := + Index (Remaining_Line (VMS_Second_Character + 1 + .. Remaining_Line'Last), + (1 => VMS_Escape_Character)); + + if VMS_Third_Character = 0 then + Input_Position := Remaining_Line'Last + 1; + Token := (VMS_Error, Remaining_Line'First); + return; + end if; + + -- Consume all the characters we are about to include in + -- the token. + + Input_Position := VMS_Third_Character + 1; + + -- Check if we are in a ^^^ situation, and return an Other + -- token in this case. + + if Remaining_Line'First + 1 = VMS_Second_Character + and then Remaining_Line'First + 2 = VMS_Third_Character + then + Token := (Other, Remaining_Line'First, + (Remaining_Line'First, Remaining_Line'First)); + return; + end if; + + Token := (VMS_Alternative, Remaining_Line'First, + (Remaining_Line'First + 1, VMS_Second_Character - 1), + (VMS_Second_Character + 1, VMS_Third_Character - 1)); + return; + end; + end if; -- VMS_Alternative + + -- The Word case. Search for characters not in Word_Characters. + -- We have found a word if the first non-word character is not + -- the first character in Remaining_Line, i.e. if Remaining_Line + -- starts with a word character. + + Last_Character := Index (Remaining_Line, Word_Characters, Outside); + if Last_Character /= Remaining_Line'First then + + -- If we haven't found a character which is not in + -- Word_Characters, all remaining characters are part of the + -- current Word token. + + if Last_Character = 0 then + Last_Character := Remaining_Line'Last + 1; + end if; + + Input_Position := Last_Character; + Token := (Word, Remaining_Line'First, + (Remaining_Line'First, Last_Character - 1)); + return; + end if; + + -- Remaining characters are in the Other category. To speed + -- up processing, we collect them together if there are several + -- of them. + + Input_Position := Last_Character + 1; + Token := (Other, + Remaining_Line'First, + (Remaining_Line'First, Last_Character)); + end Next_Token; + + ------------------ + -- Rewrite_Word -- + ------------------ + + procedure Rewrite_Word is + First_Word : String + renames Line (Token.Span.First .. Token.Span.Last); + + begin + -- We do not perform any error checking below, so we can just skip + -- all processing for the non-VMS version. + + if Target /= VMS then + Append (Rewritten_Line, First_Word); + Next_Token; + return; + end if; + + if Is_Known_Word (First_Word) then + + -- If we have a word from the dictionary, we look for the + -- longest possible sequence we can rewrite. + + declare + Seq : Token_Span := Token.Span; + Lost_Space : Boolean := False; + + begin + Next_Token; + loop + if Token.Kind = Other + and then Line (Token.Span.First .. Token.Span.Last) = " " + then + Next_Token; + if Token.Kind /= Word + or else not Is_Known_Word (Line (Seq.First + .. Token.Span.Last)) + then + -- When we reach this point, the following + -- conditions are true: + -- + -- Seq is a known word. + -- The previous token was a space character. + -- Seq extended to the current token is not a + -- known word. + + Lost_Space := True; + exit; + + else + + -- Extend Seq to cover the current (known) word. + + Seq.Last := Token.Span.Last; + Next_Token; + end if; + + else + -- When we reach this point, the following conditions + -- are true: + -- + -- Seq is a known word. + -- The previous token was a word. + -- The current token is not a space character. + + exit; + end if; + end loop; + + -- Rewrite Seq, and add the lost space if necessary + + Append (Rewritten_Line, + Get_Replacement_Word (Line (Seq.First .. Seq.Last))); + if Lost_Space then + Append (Rewritten_Line, ' '); + end if; + + -- The unknown token will be processed during the + -- next iteration of the main loop. + return; + end; + end if; + + Next_Token; + + if Token.Kind = Other + and then Line (Token.Span.First .. Token.Span.Last) = "." + then + -- Deal with extensions + + Next_Token; + if Token.Kind = Word + and then Is_Extension (Line (Token.Span.First + .. Token.Span.Last)) + then + -- We have discovered a file extension. Convert the file + -- name to upper case. + + Append (Rewritten_Line, + Translate (First_Word, Upper_Case_Map) & '.'); + Append (Rewritten_Line, + Get_Replacement_Extension + (Line (Token.Span.First .. Token.Span.Last))); + Next_Token; + else + -- We already have: Word ".", followed by an unknown + -- token. + + Append (Rewritten_Line, First_Word & '.'); + + -- The unknown token will be processed during the next + -- iteration of the main loop. + end if; + + else + -- We have an unknown Word, followed by an unknown token. + -- The unknown token will be processed by the outer loop. + + Append (Rewritten_Line, First_Word); + end if; + end Rewrite_Word; + + ----------------------------- + -- Maybe_Rewrite_Extension -- + ----------------------------- + + procedure Maybe_Rewrite_Extension is + begin + -- Again, we need no special processing in the non-VMS case + + if Target = VMS + and then Line (Token.Span.First .. Token.Span.Last) = "." + then + -- This extension is not preceded by a word, otherwise + -- Rewrite_Word would have handled it. + + Next_Token; + if Token.Kind = Word + and then Is_Extension (Line (Token.Span.First + .. Token.Span.Last)) + then + Append (Rewritten_Line, '.' & Get_Replacement_Extension + (Line (Token.Span.First .. Token.Span.Last))); + Next_Token; + else + Append (Rewritten_Line, '.'); + end if; + else + Append (Rewritten_Line, Line (Token.Span.First + .. Token.Span.Last)); + Next_Token; + end if; + end Maybe_Rewrite_Extension; + + -- Start of processing for Process_Source_Line + + begin + -- The following parser recognizes the following special token + -- sequences: + + -- Word "." Word rewrite as file name if second word is extension + -- Word " " Word rewrite as a single word using Ug_Words table + + Next_Token; + loop + case Token.Kind is + when End_Of_Line => + exit; + + when Word => + Rewrite_Word; + + when Other => + Maybe_Rewrite_Extension; + + when VMS_Alternative => + if VMS_Context_Determined then + if (not In_VMS_Section) + or else + Line (Token.VMS.First .. Token.VMS.Last) /= + Line (Token.Non_VMS.First .. Token.Non_VMS.Last) + then + Warning (Source_File, Token.First, + "VMS alternative already determined " + & "by conditionals"); + end if; + end if; + if Target = VMS then + Append (Rewritten_Line, Line (Token.VMS.First + .. Token.VMS.Last)); + else + Append (Rewritten_Line, Line (Token.Non_VMS.First + .. Token.Non_VMS.Last)); + end if; + Next_Token; + + when VMS_Error => + Error (Source_File, Token.First, "invalid VMS alternative"); + Next_Token; + end case; + end loop; + + return S (Rewritten_Line); + end Rewrite_Source_Line; + + ------------------------- + -- Process_Source_File -- + ------------------------- + + procedure Process_Source_File is + Ifset : constant String := "@ifset "; + Ifclear : constant String := "@ifclear "; + Endsetclear : constant String := "@end "; + -- Strings to be recognized for conditional processing. + + begin + while not End_Of_File (Source_File.Data) loop + declare + Line : constant String := Get_Line (Source_File'Access); + Rewritten : constant String := Rewrite_Source_Line (Line); + -- We unconditionally rewrite the line so that we can check the + -- syntax of all lines, and not only those which are actually + -- included in the output. + + Have_Conditional : Boolean := False; + -- True if we have encountered a conditional preprocessing + -- directive. + + Cond : Conditional; + -- The kind of the directive. + + Flag : Target_Type; + -- Its flag. + + begin + -- If the line starts with @ifset or @ifclear, we try to convert + -- the following flag to one of our target types. If we fail, + -- Have_Conditional remains False. + + if Line'Length >= Ifset'Length + and then Line (1 .. Ifset'Length) = Ifset + then + Cond := Set; + + declare + Arg : constant String := + Trim (Line (Ifset'Length + 1 .. Line'Last), Both); + + begin + Flag := Target_Type'Value (Arg); + + if Translate (Target_Type'Image (Flag), Lower_Case_Map) + /= Arg + then + Error (Source_File, "flag has to be lowercase"); + end if; + + Have_Conditional := True; + + exception + when Constraint_Error => + Error (Source_File, "unknown flag for '@ifset'"); + end; + + elsif Line'Length >= Ifclear'Length + and then Line (1 .. Ifclear'Length) = Ifclear + then + Cond := Clear; + + declare + Arg : constant String := + Trim (Line (Ifclear'Length + 1 .. Line'Last), Both); + + begin + Flag := Target_Type'Value (Arg); + if Translate (Target_Type'Image (Flag), Lower_Case_Map) + /= Arg + then + Error (Source_File, "flag has to be lowercase"); + end if; + + Have_Conditional := True; + + exception + when Constraint_Error => + Error (Source_File, "unknown flag for '@ifclear'"); + end; + end if; + + if Have_Conditional then + + -- We create a new conditional context and suppress the + -- directive in the output. + + Push_Conditional (Cond, Flag); + + elsif Line'Length >= Endsetclear'Length + and then Line (1 .. Endsetclear'Length) = Endsetclear + then + -- The '@end ifset'/'@end ifclear' case is handled here. We + -- have to pop the conditional context. + + declare + First, Last : Natural; + + begin + Find_Token (Source => Line (Endsetclear'Length + 1 + .. Line'Length), + Set => Letter_Set, + Test => Inside, + First => First, + Last => Last); + + if Last = 0 then + Error (Source_File, "'@end' without argument"); + else + if Line (First .. Last) = "ifset" then + Have_Conditional := True; + Cond := Set; + elsif Line (First .. Last) = "ifclear" then + Have_Conditional := True; + Cond := Clear; + end if; + + if Have_Conditional then + Pop_Conditional (Cond); + end if; + + -- We fall through to the ordinary case for other @end + -- directives. + + end if; -- @end without argument + end; + end if; -- Have_Conditional + + if not Have_Conditional then + + -- The ordinary case. + + if not Currently_Excluding then + Put_Line (Output_File, Rewritten); + end if; + end if; + end; + end loop; + + Check_No_Pending_Conditional; + end Process_Source_File; + + --------------------------- + -- Initialize_Extensions -- + --------------------------- + + procedure Initialize_Extensions is + + procedure Add (Extension : String); + -- Adds an extension which is replaced with itself (in upper + -- case). + + procedure Add (Extension, Replacement : String); + -- Adds an extension with a custom replacement. + + --------- + -- Add -- + --------- + + procedure Add (Extension : String) is + begin + Add (Extension, Translate (Extension, Upper_Case_Map)); + end Add; + + procedure Add (Extension, Replacement : String) is + begin + Set (Extensions, Extension, V (Replacement)); + end Add; + + -- Start of processing for Initialize_Extensions + + begin + -- To avoid performance degradation, increase the constant in the + -- definition of Extensions above if you add more extensions here. + + Add ("o", "OBJ"); + Add ("ads"); + Add ("adb"); + Add ("ali"); + Add ("ada"); + Add ("atb"); + Add ("ats"); + Add ("adc"); + Add ("c"); + end Initialize_Extensions; + + ------------------ + -- Is_Extension -- + ------------------ + + function Is_Extension (Extension : String) return Boolean is + begin + return Present (Extensions, Extension); + end Is_Extension; + + ------------------------------- + -- Get_Replacement_Extension -- + ------------------------------- + + function Get_Replacement_Extension (Extension : String) return String is + begin + return S (Get (Extensions, Extension)); + end Get_Replacement_Extension; + + ------------------- + -- Is_Known_Word -- + ------------------- + + function Is_Known_Word (Word : String) return Boolean is + begin + return Present (Ug_Words, Word); + end Is_Known_Word; + + -------------------------- + -- Get_Replacement_Word -- + -------------------------- + + function Get_Replacement_Word (Word : String) return String is + begin + return S (Get (Ug_Words, Word)); + end Get_Replacement_Word; + + ---------------------- + -- Push_Conditional -- + ---------------------- + + procedure Push_Conditional (Cond : Conditional; Flag : Target_Type) is + Will_Exclude : Boolean; + + begin + -- If we are already in an excluding context, inherit this property, + -- otherwise calculate it from scratch. + + if Conditional_TOS > 0 + and then Conditional_Stack (Conditional_TOS).Excluding + then + Will_Exclude := True; + else + case Cond is + when Set => + Will_Exclude := Flag /= Target; + when Clear => + Will_Exclude := Flag = Target; + end case; + end if; + + -- Check if the current directive is pointless because of a previous, + -- enclosing directive. + + for J in 1 .. Conditional_TOS loop + if Conditional_Stack (J).Flag = Flag then + Warning (Source_File, "directive without effect because of line" + & Integer'Image (Conditional_Stack (J).Starting_Line)); + end if; + end loop; + + Conditional_TOS := Conditional_TOS + 1; + Conditional_Stack (Conditional_TOS) := + (Starting_Line => Source_File.Line, + Cond => Cond, + Flag => Flag, + Excluding => Will_Exclude); + end Push_Conditional; + + --------------------- + -- Pop_Conditional -- + --------------------- + + procedure Pop_Conditional (Cond : Conditional) is + begin + if Conditional_TOS > 0 then + case Cond is + when Set => + if Conditional_Stack (Conditional_TOS).Cond /= Set then + Error (Source_File, + "'@end ifset' does not match '@ifclear' at line" + & Integer'Image (Conditional_Stack + (Conditional_TOS).Starting_Line)); + end if; + + when Clear => + if Conditional_Stack (Conditional_TOS).Cond /= Clear then + Error (Source_File, + "'@end ifclear' does not match '@ifset' at line" + & Integer'Image (Conditional_Stack + (Conditional_TOS).Starting_Line)); + end if; + end case; + + Conditional_TOS := Conditional_TOS - 1; + + else + case Cond is + when Set => + Error (Source_File, + "'@end ifset' without corresponding '@ifset'"); + + when Clear => + Error (Source_File, + "'@end ifclear' without corresponding '@ifclear'"); + end case; + end if; + end Pop_Conditional; + + ------------------------- + -- Currently_Excluding -- + ------------------------- + + function Currently_Excluding return Boolean is + begin + return Conditional_TOS > 0 + and then Conditional_Stack (Conditional_TOS).Excluding; + end Currently_Excluding; + + ---------------------------- + -- VMS_Context_Determined -- + ---------------------------- + + function VMS_Context_Determined return Boolean is + begin + for J in 1 .. Conditional_TOS loop + if Conditional_Stack (J).Flag = VMS then + return True; + end if; + end loop; + + return False; + end VMS_Context_Determined; + + -------------------- + -- In_VMS_Section -- + -------------------- + + function In_VMS_Section return Boolean is + begin + for J in 1 .. Conditional_TOS loop + if Conditional_Stack (J).Flag = VMS then + return Conditional_Stack (J).Cond = Set; + end if; + end loop; + + return False; + end In_VMS_Section; + + ---------------------------------- + -- Check_No_Pending_Conditional -- + ---------------------------------- + + procedure Check_No_Pending_Conditional is + begin + for J in 1 .. Conditional_TOS loop + case Conditional_Stack (J).Cond is + when Set => + Error (Source_File, "Missing '@end ifset' for '@ifset' at line" + & Integer'Image (Conditional_Stack (J).Starting_Line)); + + when Clear => + Error (Source_File, + "Missing '@end ifclear' for '@ifclear' at line" + & Integer'Image (Conditional_Stack (J).Starting_Line)); + end case; + end loop; + end Check_No_Pending_Conditional; + + ------------------ + -- Main Program -- + ------------------ + + Valid_Command_Line : Boolean; + Output_File_Name : VString; + + begin + Initialize_Extensions; + + Valid_Command_Line := Argument_Count in 3 .. 5; + + -- First argument: Target. + + if Valid_Command_Line then + begin + Target := Target_Type'Value (Argument (1)); + + exception + when Constraint_Error => + Valid_Command_Line := False; + end; + end if; + + -- Second argument: Source_File. + + if Valid_Command_Line then + begin + Source_File.Name := V (Argument (2)); + Open (Source_File.Data, In_File, Argument (2)); + + exception + when Name_Error => + Valid_Command_Line := False; + end; + end if; + + -- Third argument: Dictionary_File. + + if Valid_Command_Line then + begin + Dictionary_File.Name := V (Argument (3)); + Open (Dictionary_File.Data, In_File, Argument (3)); + + exception + when Name_Error => + Valid_Command_Line := False; + end; + end if; + + -- Fourth argument: Output_File. + + if Valid_Command_Line then + if Argument_Count in 4 .. 5 then + Output_File_Name := V (Argument (4)); + else + case Target is + when UNW => + Output_File_Name := V ("gnat_ugn_unw.texi"); + when VMS => + Output_File_Name := V ("gnat_ugn_vms.texi"); + end case; + end if; + + Warnings_Enabled := Argument_Count = 5; + + begin + Create (Output_File, Out_File, S (Output_File_Name)); + + exception + when Name_Error | Use_Error => + Valid_Command_Line := False; + end; + end if; + + if not Valid_Command_Line then + Usage; + Set_Exit_Status (Failure); + + else + Read_Dictionary_File; + Close (Dictionary_File.Data); + + -- Main processing starts here. + + Process_Source_File; + Close (Output_File); + Close (Source_File.Data); + + New_Line (Standard_Error); + + if Number_Of_Warnings = 0 then + Put_Line (Standard_Error, " NO Warnings"); + + else + Put (Standard_Error, Integer'Image (Number_Of_Warnings)); + Put (Standard_Error, " Warning"); + + if Number_Of_Warnings > 1 then + Put (Standard_Error, "s"); + end if; + + New_Line (Standard_Error); + end if; + + if Number_Of_Errors = 0 then + Put_Line (Standard_Error, " NO Errors"); + + else + Put (Standard_Error, Integer'Image (Number_Of_Errors)); + Put (Standard_Error, " Error"); + + if Number_Of_Errors > 1 then + Put (Standard_Error, "s"); + end if; + + New_Line (Standard_Error); + end if; + + if Number_Of_Errors /= 0 then + Set_Exit_Status (Failure); + else + Set_Exit_Status (Success); + end if; + end if; + end Xgnatugn;