\input texinfo @c -*- texinfo -*-
@c %**start of header
@setfilename dld.info
@settitle DLD
@c %**end of header

@iftex
@finalout
@end iftex

@ifinfo
This file documents dld, a dynamic link/unlink editor.

This is edition 1.3 of the dld documentation.

Copyright (C) 1991 W. Wilson Ho.
Copyright (C) 1995 A. Jaffer.

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.

Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
@end ifinfo

@iftex
@titlepage
@title Dld
@subtitle A Dynamic Link/Unlink Editor
@subtitle Version 3.2.7.
@subtitle Copyright @copyright{} 1991 W. Wilson Ho.
@subtitle Copyright @copyright{} 1995 A. Jaffer.
@author by W. Wilson Ho
@end titlepage
@setchapternewpage off
@headings off
@everyheading @| @thispage @|
@end iftex

@node Top, dld_init, (dir), (dir)
@comment  node-name,  next,  previous,  up
@chapter What is dld?

@dfn{Dld} is a library package of C functions that performs @dfn{dynamic
link editing}.  Programs that use dld can add compiled object
code to or remove such code from a process anytime during its execution.
Loading modules, searching libraries, resolving external references, and
allocating storage for global and static data structures are all
performed at run time.

Dld is now available for VAX, Sun 3, SPARCstation, Sequent Symmetry,
Atari ST, and Linux.

This text describes how the dld functions can be called and some
technical details that should be aware of.  For the internals of dld and
sample applications, please refer to @cite{An Approach to Genuine
Dynamic Linking}, Software--Practice and Experirnce, Vol. 21(4), 375-390
(April 1991).  An early draft of that paper is included with the
original distribution (prep.ai.mit.edu:pub/gnu/dld-3.2.3.tar.gz).

@menu
* dld_init::                    Initializing Dld
* dld_link::                    Dynamically Linking in New Modules
* dld_unlink::                  Unlinking a Module
* dld_get_func::                Invoking Dynamically Linked Functions
* Executability::               Determining If a Function is Executable
* dld_list_undefined_sym::      Listing the Undefined Symbols
* dld_create_reference::        Explicitly Referencing a Symbol
* Explicit Definition::         Explicitly Defining a Symbol
* C++ support::                 
* dld_perror::                  Printing out the Error Messages
* Error Codes::                 Definition of Error Codes
@end menu

@node dld_init, dld_link, Top, Top
@comment  node-name,  next,  previous,  up
@section Initializing Dld

To use any of the dld functions, you must include the header file
@file{dld.h} for declaration of the functions and definition of the
error code constants.

The function @code{dld_init} must be called before any other dld
functions.

@deftypefun int dld_init (const char *@var{path})
where @var{path} is a string containing the path name of the executable
file of the executing process.

This function initializes internal data structures of dld and
loads into memory symbol definitions of the executing process.  By doing
so, other dynamically loaded functions can reference symbols already
defined or share functions already exist in the executing process.

@code{dld_init} returns 0 when successful; otherwise, it returns an
error code that is non-zero (@pxref{Error Codes, , Definition of Error
Codes}).  
@end deftypefun

@subsection Locating the Executable File

The path name of the executing process as required by @code{dld_init}
might not be easily obtained all the time.  Not all systems pass the
entire path name of the executable file as the first argument
(@code{argv[0]}) to @code{main}.  In order to obtain the full path of
the executable file, the @code{dld_find_executable} function can be
used.

@deftypefun char *dld_find_executable (const char *@var{command})
@code{dld_find_executable} returns the absolute path name of the file
that would be executed if @var{command} were given as a command.  It
looks up the environment variable @var{PATH}, searches in each of the
directory listed for @var{command}, and returns the absolute path name
for the first occurrence.  Thus, it is advisable to invoke
@code{dld_init} as:

@example
main (int argc, char **argv)
@{
    @dots{}
    if (dld_init (dld_find_executable (argv[0]))) @{
        @dots{}
    @}
    @dots{}
@}
@end example

@quotation
@strong{Note:} If the current process is executed using the
@code{execve} call without passing the correct path name as argument 0,
@code{dld_find_executable (argv[0]) } will also fail to locate the
executable file.
@end quotation

@code{dld_find_executable} returns zero if @code{command} is not found
in any of the directories listed in @code{PATH}.
@end deftypefun

@node dld_link, dld_unlink, dld_init, Top
@comment  node-name,  next,  previous,  up
@section Dynamically Linking in New Modules

The function @code{dld_link} dynamically links in the named relocatable
object or library file into memory.

@deftypefun int dld_link (const char *@var{filename})
where @var{filename} is the path name of the file to be linked.
Specifically, if the named file is a relocatable object file, it is
completely loaded into memory.  If it is a library file, only those
modules defining an unresolved external reference are loaded.  Since a
module in the library may itself reference other routines in the
library, loading it may generate more unresolved external references.
Therefore, a library file is searched repeatedly until a scan through
all library members is made without having to load any new modules.

Storage for the text and data of the dynamically linked modules is
allocated using @code{malloc}.  In other words, they are kept in the
@emph{heap} of the executing process.

After all modules are loaded, @code{dld_link} resolves as many external
references as possible.  Note that some symbols might still be undefined
at this stage, because the modules defining them have not yet been
loaded.

If the specified module is linked successfully, @code{dld_link} returns
0; otherwise, it returns a non-zero error code (@pxref{Error Codes, ,
Definition of Error Codes}).
@end deftypefun

@node dld_unlink, dld_get_func, dld_link, Top
@comment  node-name,  next,  previous,  up
@section Unlinking a Module

The major difference between dld and other dynamic linker is that
dld allows object modules to be removed from the process anytime
during execution.  Unlinking a module is simply the reverse of the link
operation (@pxref{dld_unlink, , Important Points in Using Unlink}).
The specified module is removed and the memory allocated to it is
reclaimed.  Additionally, resolution of external references must be
undone.

There are two unlink functions:

@deftypefun int dld_unlink_by_file (const char *@var{path}, int @var{hard})
@deftypefunx int dld_unlink_by_symbol (const char *@var{id}, int @var{hard})
The two unlink functions are basically the same except that
@code{dld_unlink_by_file} takes as argument the path name (@var{path})
of a file corresponding to a module previously linked in by
@code{dld_link}, but @code{dld_unlink_by_symbol} unlinks the module that
defines the specified symbol (@var{id}).

Both functions take a second argument @var{hard}.  When @var{hard}
is non-zero (@dfn{hard unlink}), the specified module is removed from
memory unconditionally.  On the other hand, if @var{hard} is zero
(@dfn{soft unlink}), this module is removed from memory only if it is
not referenced by any other modules.  Furthermore, if unlinking a module
results in leaving some other modules being unreferenced, these
unreferenced modules are also removed.

Hard unlink is usually used when you want to explicitly remove a module
and probably replace it by a different module with the same name.  For
example, you may want to replace the system's @code{printf} by your own
version.  When you link in your version of @code{printf}, dld
will automatically redirect all references to @code{printf} to the new
version.

Soft unlink should be used when you are not sure if the specified module
is still needed.  If you just want to clean up unnecessary functions, it
is always safe to use soft unlink.

Both unlink functions returns 0 if the specified object file or symbol
is previously loaded.  Otherwise, they return a non-zero error code
(@pxref{Error Codes, , Definition of Error Codes}).
@end deftypefun

@subsection Important Points in Using Unlink

When a module is being unlinked, dld tries to clean up as much as
it can to restore the executing process to a state as if this module has
never been linked.  This clean up includes removing and reclaiming the
memory for storing the text and data segment of the module, and
@dfn{un-defining} any global symbols defined by this module.

However, side effects---such as modification of global variables,
input/output operations, and allocations of new memory blocks---caused
by the execution of any function in this module are not reversed.  Thus,
it is the responsibility of the programmer to explicitly carry out all
necessary clean up operations before unlinking a module.

@node dld_get_func, Executability, dld_unlink, Top
@comment  node-name,  next,  previous,  up
@section Invoking Dynamically Linked Functions

Dynamically linked functions may still be invoked from modules (e.g.,
@code{main}) that do not contain references to such functions.

@deftypefun unsigned long dld_get_symbol (const char *@var{id})
Returns the entry point of the function named @var{id} if found, 0 if
not found.  Non-zero returned values can be used as pointers to the
functions.

@deftypefunx unsigned long dld_get_func (const char *@var{func})
Returns the address of the global variable named @var{func} if found, 0
if not found.

A typical use of @code{dld_get_func} would be:

@c group
@example
@{
    void (*func) ();
    int error_code;

    @dots{}

    /* First, link in the object file "my_object_file.o".  Proceed
       only if the link operation is successful, i.e. it returns 0.
       "my_new_func" is a function defined in "my_object_file.o".
       Set func to point at the entry point of this function and
       then invoke it indirectly through func. */

    if ((error_code = dld_link ("my_object_file.o")) == 0) @{
        if ((func = (void (*) ()) get_func ("my_new_func")) != 0)
            (*func) ();
        @dots{}
    @} else @{

    @dots{}
    @}
@}
@end example
@c end group
@end deftypefun

@node Executability, dld_list_undefined_sym, dld_get_func, Top
@comment  node-name,  next,  previous,  up
@section Determining If a Function is Executable

Since dld allows modules to be added to or removed from an executing
process dynamically, some global symbols may not be defined.  As a
result, an invocation of a function might reference an undefined symbol.
We say that a function is @dfn{executable} if and only if all its
external references have been fully resolved and all functions that it
might call are executable.

@deftypefun int dld_function_executable_p (const char *@var{func})
The predicate function @code{dld_function_executable_p} helps solve this
problem by tracing the cross references between modules and returns
non-zero only if the named function is executable.

Note that the implementation of @code{dld_function_executable_p} is not
complete according to the (recursive) definition of executability.
External references through pointers are not traced.  That is,
@code{dld_function_executable_p} will still return non-zero if the named
function uses a pointer to indirectly call another function which has
already been unlinked.  Furthermore, if one external reference of a
object module is unresolved, all functions defined in this module are
considered unexecutable.  Therefore, @code{dld_function_executable_p} is
usually too conservative.

However, it is advisable to use @code{dld_function_executable_p} to
check if a function is executable before its invocation.  In such a
dynamic environment where object modules are being added and removed, a
function that is executable at one point in time might not be executable
at another.  Under most circumstances, @code{dld_function_executable_p}
is accurate.  Also, the implementation of this function has been
optimized and it is relatively cheap to use.
@end deftypefun

@node  dld_list_undefined_sym, dld_create_reference, Executability, Top
@comment  node-name,  next,  previous,  up
@section Listing the Undefined Symbols

@deftypefun char **dld_list_undefined_sym ()
The function @code{dld_list_undefined_sym} returns an array of undefined
global symbol names.

The list returned contains all the symbols that have been referenced
by some modules but have not been defined.  This function is designed
for debugging, especially in the case when a function is found to be not
executable but you do not know what the missing symbols are.

The length of the array is given by the global variable
@code{dld_undefined_sym_count}, which always holds the current total
number of undefined global symbols.  Note that all C symbols are listed
in their internal representation---i.e., they are prefixed by the
underscore character @samp{_}.

Storage for the array returned is allocated by @code{malloc}.  It is the
programmer's responsibility to release this storage by @code{free} when
it is not needed anymore.
@end deftypefun

@node dld_create_reference, Explicit Definition, dld_list_undefined_sym, Top
@comment  node-name,  next,  previous,  up
@section Explicitly Referencing a Symbol

Normally, a library module is loaded only when it defines one of more
symbols that has been referenced.  To force a library routine to be
loaded, one need to explicitly create a reference to a symbol defined by
that library routine.  The function @code{dld_create_reference} is
designed for this purpose:

@deftypefun int dld_create_reference (const char *@var{name})
Usually @var{name} is the name of the library routine that should be
loaded, but it can be any symbol defined by that routine.  After such a
reference has been created, linking the appropriate library by
@code{dld_link} would cause the required library routine to be loaded.

If the call is successful, @code{dld_create_reference} returns 0;
otherwise, it returns a non-zero error code (@pxref{Error Codes, ,
Definition of Error Codes}).

The library routine loaded by this method can be unlinked by
@code{dld_unlink_by_symbol (@var{name})}.  Once it has been unlinked,
the corresponding reference created by @code{dld_create_reference} is
also removed so that this routine will not be loaded in again by
subsequent linking of the library.
@end deftypefun

@node Explicit Definition, C++ support, dld_create_reference, Top
@comment  node-name,  next,  previous,  up
@section Explicitly Defining a Symbol

Dld allows a programmer to explicitly define global symbols.  That is, a
programmer can force a symbol to have storage assigned for it.  This is
especially useful in incremental program testing where the function
being tested needs to access some global variables which are defined by
another function not yet linked in (or even not yet written).  There are
two functions related to explicit definition:

@deftypefun int dld_define_sym (const char *@var{name}, unsigned int @var{size})
@code{dld_define_sym} forces dld to allocate @var{size} bytes for symbol
@var{name}.  It can be called before or after a reference to @var{name}
is made.  If references to @var{name} already exist when it is defined,
all such references are directed to point to the correct address
allocated for @var{name}.

@code{dld_define_sym} returns 0 if successful.  Otherwise, it returns a
non-zero error code (@pxref{Error Codes, , Definition of Error Codes}).
The typical error is a multiple definition of @var{name}.
@end deftypefun

@deftypefun void dld_remove_defined_symbol (const char *@var{name})
When the definition of @var{name} is no longer needed, it can be removed
by @code{dld_remove_define_symbol}.
@end deftypefun

@node C++ support, dld_perror, Explicit Definition, Top
@section C++ support

From: Thomas Hiller, Hiller@@tu-harburg.d400.de

The original DLD supports only C function linking. When using C++ there
is a problem with the global constructors and destructors. The new DLD
version contains code which mimics the original @dfn{collect2} supplied
by gcc (@pxref{Top, , ??, gcc, The GNU Compiler Manual}).  The way
GNU @code{ld} (@pxref{Top, , ??, binutils, Binary Utilities})
does this is better (more direct).  But I'm not familiar with the
internals of GNU @code{ld} and DLD.

The file @file{gxxload.cc} contains two C functions (@code{dyn_load} and
@code{dyn_unload}), which function as @code{dld_load} and
@code{dld_unload}, but they take account that the C++ objects or
libraries may contain global constructors and destructors.

@deftypefun void dyn_load (const char *@var{name})
Behaves like @code{dld_link(name)} but constructors are called before
control returns to the program.
@end deftypefun

@deftypefun void dyn_unload (const char *@var{name})
Behaves like @code{dld_unlink} but the destructors are called before the
unlink takes place.
@end deftypefun

@deftypevr {Global Array} char* dyn_libraries[];
The caller needs to define the null terminated array of strings
@code{dyn_libraries}.  The strings in the array @code{dyn_libraries},
give the pathnames of the files which should be used to resolve link
references after a call is made to @code{dyn_load}.  As in the example
below, @code{dyn_libraries} might contain:
@itemize
@item
"/usr/lib/libg++.a"
@item
"/usr/lib/libm.a"
@item
"/usr/lib/libc.a"
@end itemize
@end deftypevr

A small demonstration program is included in the @file{test}
sub-directory's files @file{gxxtest.cc} and @file{sub.cc}.  When
invoked, @code{gxxtest} should print @footnote{Running this example on
my machine does not print the @code{Hello} lines.  But I don't know
enough C++ to fix it.}  :

@example
DLD function:
dyn_load:
Hello, this is A
dyn_unload:
Hello, this was A
---
@end example

The constructor (which prints the first @samp{Hello} message) is called
by @code{dyn_load}.  @code{dyn_unload} calls the destructor (second
@samp{Hello} message).  The final @samp{---} message demonstrates that
the destructor is called by @code{dyn_unload} and not the @code{exit()}
function.

@subheading sub.cc
@example
#include <iostream.h>

class A @{
public:
        A() @{ cout<<"Hello, this is A"<<endl; @}
        ~A() @{ cout<<"Hello, this was A"<<endl; @}
@};


A a;
@end example

@subheading gxxtest.cc
@example
#include <iostream.h>

#include <dld.h>

char* dyn_libraries[] = @{
"/usr/lib/libg++.a",    /* link in libg++ */
"/usr/lib/libm.a",      /* link in libm */
"/usr/lib/libc.a",      /* link in libc */
LIBGCC,                 /* link in libgcc */
0
@};

main()
@{
        cout<<"DLD function: "<<endl;
        dld_link("sub.o");
        dld_unlink_by_file("sub.o",0);
        cout<<"dyn_load: "<<endl;
        dyn_load("sub.o");
        cout<<"dyn_unload: "<<endl;
        dyn_unload("sub.o");
        cout<<"---"<<endl;
@}
@end example

@node dld_perror, Error Codes, C++ support, Top
@comment  node-name,  next,  previous,  up
@section Printing out the Error Messages

@deftypefun void dld_perror (const char *@var{user_mesg})
where @var{user_mesg} is a user-supplied string prepended to the error
message.  The function @code{dld_perror} prints out a short message
explaining the error returns by the last dld functions.
@end deftypefun

@deftypefun char * dld_strerror (int @var{code})
The function @code{dld_strerror} returns the error message string
corresponding to the given error code (from @code{dld_errno}).
@end deftypefun

@node Error Codes,  , dld_perror, Top
@comment  node-name,  next,  previous,  up
@section Definition of Error Codes

The dld functions return a non-zero error code when they fail.  The
definitions of these error codes are:

@c group
@quotation
@iftex
@tableindent = 1.5in
@end iftex
@table @code
@item DLD_ENOFILE
cannot open file.

@item DLD_EBADMAGIC
bad magic number.

@item DLD_EBADHEADER
failure reading header.

@item DLD_ENOTEXT
premature eof in text section.

@item DLD_ENOSYMBOLS
premature eof in symbols.

@item DLD_ENOSTRINGS
bad string table.

@item DLD_ENOTXTRELOC
premature eof in text relocation.

@item DLD_ENODATA
premature eof in data section.

@item DLD_ENODATRELOC
premature eof in data relocation.

@item DLD_EMULTDEFS
multiple definitions of symbol.

@item DLD_EBADLIBRARY
malformed library archive.

@item DLD_EBADCOMMON
common block not supported.

@item DLD_EBADOBJECT
malformed input file (not object file or archive).

@item DLD_EBADRELOC
bad relocation info.

@item DLD_ENOMEMORY
virtual memory exhausted.

@item DLD_EUNDEFSYM
undefined symbol.
@end table
@end quotation
@c end group
@bye
