Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Language Reference

table of contents

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

Application Binary Interface

Contents
  1. C ABI
  2. Endianness
  3. Basic Types
  4. Delegates
  5. Structs and Unions
  6. Classes
  7. Interfaces
  8. Arrays
  9. Associative Arrays
  10. Reference Types
  11. Name Mangling
    1. Back references
    2. Type Mangling
  12. Function Calling Conventions
    1. Register Conventions
    2. Return Value
    3. Parameters
  13. Exception Handling
    1. Windows 32 bit
    2. Linux, FreeBSD and OS X
    3. Windows 64 bit
  14. Garbage Collection
  15. ModuleInfo Instance
    1. Module Initialization and Termination
    2. Unit Testing
  16. Runtime Helper Functions
  17. Symbolic Debugging
    1. Codeview Debugger Extensions

A D implementation that conforms to the D ABI (Application Binary Interface) will be able to generate libraries, DLLs, etc., that can interoperate with D binaries built by other implementations.

C ABI

The C ABI referred to in this specification means the C Application Binary Interface of the target system. C and D code should be freely linkable together, in particular, D code shall have access to the entire C ABI runtime library.

Endianness

Theendianness (byte order) of the layout of the data will conform to the endianness of the target machine. The Intel x86 CPUs arelittle endian meaning that the value 0x0A0B0C0D is stored in memory as:0D 0C 0B 0A.

Basic Types

bool8 bit byte with the values 0 for false and 1 for true
byte8 bit signed value
ubyte8 bit unsigned value
short16 bit signed value
ushort16 bit unsigned value
int32 bit signed value
uint32 bit unsigned value
long64 bit signed value
ulong64 bit unsigned value
cent128 bit signed value
ucent128 bit unsigned value
float32 bit IEEE 754 floating point value
double64 bit IEEE 754 floating point value
realimplementation defined floating point value, for x86 it is 80 bit IEEE 754 extended real
char8 bit unsigned value
wchar16 bit unsigned value
dchar32 bit unsigned value

Delegates

Delegates arefat pointers with two parts:

Delegate Layout
offsetpropertycontents
0.ptrcontext pointer
ptrsize.funcptrpointer to function

Thecontext pointer can be a classthis reference, a structthis pointer, a pointer to a closure (nested functions) or a pointer to an enclosing function's stack frame (nested functions).

Structs and Unions

These conform to the target's C ABI struct layout, except:

Classes

An object consists of:

Class Object Layout
sizepropertycontents
ptrsize.__vptrpointer to vtable
ptrsize.__monitormonitor
ptrsize... vptrs for any interfaces implemented by this class in left to right, most to least derived, order
......super's non-static fields and super's interface vptrs, from least to most derived
...named fieldsnon-static fields

The vtable consists of:

Virtual Function Pointer Table Layout
sizecontents
ptrsizepointer to instance of TypeInfo
ptrsize...pointers to virtual member functions

Casting a class object to an interface consists of adding the offset of the interface's corresponding vptr to the address of the base of the object. Casting an interface ptr back to the class type it came from involves getting the correct offset to subtract from it from the object.Interface entry at vtbl[0]. Adjustor thunks are created and pointers to them stored in the method entries in the vtbl[] in order to set the this pointer to the start of the object instance corresponding to the implementing method.

An adjustor thunk looks like:

  ADD EAX,offset  JMP method

The leftmost side of the inheritance graph of the interfaces all share their vptrs, this is the single inheritance model. Every time the inheritance graph forks (for multiple inheritance) a new vptr is created and stored in the class' instance. Every time a virtual method is overridden, a new vtbl[] must be created with the updated method pointers in it.

The class definition:

class XXXX{    ....};

Generates the following:

Interfaces

An interface is a pointer to a pointer to a vtbl[]. The vtbl[0] entry is a pointer to the corresponding instance of the object.Interface class. The rest of thevtbl[1..$] entries are pointers to the virtual functions implemented by that interface, in the order that they were declared.

A COM interface differs from a regular interface in that there is no object.Interface entry invtbl[0]; the entriesvtbl[0..$] are all the virtual function pointers, in the order that they were declared. This matches the COM object layout used by Windows.

A C++ interface differs from a regular interface in that it matches the layout of a C++ class using single inheritance on the target machine.

Arrays

A dynamic array consists of:

Dynamic Array Layout
offsetpropertycontents
0.lengtharray dimension
size_t.ptrpointer to array data

A dynamic array is declared as:

type[] array;
whereas a static array is declared as:
type[dimension] array;

Thus, a static array always has the dimension statically available as part of the type, and so it is implemented like in C. Static arrays and Dynamic arrays can be easily converted back and forth to each other.

Associative Arrays

Associative arrays consist of a pointer to an opaque, implementation defined type.

The current implementation is contained in and defined byrt/aaA.d.

Reference Types

D has reference types, but they are implicit. For example, classes are always referred to by reference; this means that class instances can never reside on the stack or be passed as function parameters.

Name Mangling

D accomplishes typesafe linking bymangling a D identifier to include scope and type information.

MangledName:_DQualifiedNameType_DQualifiedNameZ// Internal

TheType above is the type of a variable or the return type of a function. This is never aTypeFunction, as the latter can only be bound to a value via a pointer to a function or a delegate.

QualifiedName:SymbolFunctionNameSymbolFunctionNameQualifiedName
SymbolFunctionName:SymbolNameSymbolNameTypeFunctionNoReturnSymbolNameMTypeModifiersoptTypeFunctionNoReturn

TheM means that the symbol is a function that requires athis pointer. Class or struct fields are mangled withoutM. To disambiguateM from being aParameter with modifierscope, the following type needs to be checked for being aTypeFunction.

SymbolName:LNameTemplateInstanceNameIdentifierBackRef0// anonymous symbols

Template Instance Names have the types and values of its parameters encoded into it:

TemplateInstanceName:TemplateIDLNameTemplateArgsZ
TemplateID:__T__U// for symbols declared inside template constraint
TemplateArgs:TemplateArgTemplateArgTemplateArgs
TemplateArg:TemplateArgXHTemplateArgX

If a template argument matches a specialized template parameter, the argument is mangled with prefixH.

TemplateArgX:TTypeVTypeValueSQualifiedNameXNumberExternallyMangledName

ExternallyMangledName can be any series of characters allowed on the current platform, e.g. generated by functions with C++ linkage or annotated withpragma(mangle,...).

Values:ValueValueValues
Value:niNumberNNumbereHexFloatcHexFloatcHexFloatCharWidthNumber_HexDigitsANumberValuesSNumberValuesfMangledName
HexFloat:NANINFNINFNHexDigitsPExponentHexDigitsPExponent
Exponent:NNumberNumber
HexDigits:HexDigitHexDigitHexDigits
HexDigit:DigitABCDEF
CharWidth:awd
n
is fornull arguments.
iNumber
is for positive numeric literals (including character literals).
NNumber
is for negative numeric literals.
eHexFloat
is for real and imaginary floating point literals.
cHexFloatcHexFloat
is for complex floating point literals.
CharWidthNumber_HexDigits
CharWidth is whether the characters are 1 byte (a), 2 bytes (w) or 4 bytes (d) in size.Number is the number of characters in the string. TheHexDigits are the hex data for the string.
ANumberValues
An array or asssociative array literal.Number is the length of the array.Value is repeatedNumber times for a normal array, and 2 *Number times for an associative array.
SNumberValues
A struct literal.Value is repeatedNumber times.
Name:NamestartNamestartNamechars
Namestart:_Alpha
Namechar:NamestartDigit
Namechars:NamecharNamecharNamechars

AName is a standard Didentifier.

LName:NumberNameNumber__SNumber// function-local parent symbols
Number:DigitDigitNumber
Digit:0123456789

AnLName is a name preceded by aNumber giving the number of characters in theName.

Back references

AnyLName or non-basicType (i.e. any type that does not encode as a fixed one or two character sequence) that has been emitted to the mangled symbol before will not be emitted again, but is referenced by a special sequence encoding the relative position of the original occurrence in the mangled symbol name.

Numbers in back references are encoded with base 26 by upper case lettersA -Z for higher digits but lower case lettersa -z for the last digit.

TypeBackRef:QNumberBackRef
IdentifierBackRef:QNumberBackRef
NumberBackRef:lower-case-letterupper-case-letterNumberBackRef

To distinguish between the type of the back reference a look-up of the back referenced character is necessary: An identifier back reference always points to a digit0 to9, while a type back reference always points to a letter.

Type Mangling

Types are mangled using a simple linear scheme:

Type:TypeModifiersoptTypeXTypeBackRef
TypeX:TypeArrayTypeStaticArrayTypeAssocArrayTypePointerTypeFunctionTypeIdentTypeClassTypeStructTypeEnumTypeTypedefTypeDelegateTypeVoidTypeByteTypeUbyteTypeShortTypeUshortTypeIntTypeUintTypeLongTypeUlongTypeCentTypeUcentTypeFloatTypeDoubleTypeRealTypeIfloatTypeIdoubleTypeIrealTypeCfloatTypeCdoubleTypeCrealTypeBoolTypeCharTypeWcharTypeDcharTypeNoreturnTypeNullTypeTupleTypeVector
TypeModifiers:ConstWildWildConstSharedSharedConstSharedWildSharedWildConstImmutable
Shared:O
Const:x
Immutable:y
Wild:Ng
TypeArray:AType
TypeStaticArray:GNumberType
TypeAssocArray:HTypeType
TypePointer:PType
TypeVector:NhType
TypeFunction:TypeFunctionNoReturnType
TypeFunctionNoReturn:CallConventionFuncAttrsoptParametersoptParamClose
CallConvention:F// DU// CW// WindowsR// C++Y// Objective-C
FuncAttrs:FuncAttrFuncAttrFuncAttrs
FuncAttr:FuncAttrPureFuncAttrNothrowFuncAttrRefFuncAttrPropertyFuncAttrNogcFuncAttrReturnFuncAttrScopeFuncAttrTrustedFuncAttrSafeFuncAttrLive

Function attributes are emitted in the order as listed above, with the exception ofreturn andscope.return comes beforescope whenthis is areturn scope parameter, and afterscope whenthis is ascope andreturn ref parameter.

FuncAttrPure:Na
FuncAttrNogc:Ni
FuncAttrNothrow:Nb
FuncAttrProperty:Nd
FuncAttrRef:Nc
FuncAttrReturn:Nj
FuncAttrScope:Nl
FuncAttrTrusted:Ne
FuncAttrSafe:Nf
FuncAttrLive:Nm
Parameters:ParameterParameterParameters
Parameter:Parameter2MParameter2// scopeNkParameter2// return
Parameter2:TypeIType// inJType// outKType// refLType// lazy
ParamClose:X// variadic T t...) styleY// variadic T t,...) styleZ// not variadic
TypeIdent:IQualifiedName
TypeClass:CQualifiedName
TypeStruct:SQualifiedName
TypeEnum:EQualifiedName
TypeTypedef:TQualifiedName
TypeDelegate:DTypeModifiersoptTypeFunction
TypeVoid:v
TypeByte:g
TypeUbyte:h
TypeShort:s
TypeUshort:t
TypeInt:i
TypeUint:k
TypeLong:l
TypeUlong:m
TypeCent:zi
TypeUcent:zk
TypeFloat:f
TypeDouble:d
TypeReal:e
TypeIfloat:o
TypeIdouble:p
TypeIreal:j
TypeCfloat:q
TypeCdouble:r
TypeCreal:c
TypeBool:b
TypeChar:a
TypeWchar:u
TypeDchar:w
TypeNoreturn:Nn
TypeNull:n
TypeTuple:BParametersZ

Function Calling Conventions

Theextern (C) andextern (D) calling convention matches the C calling convention used by the supported C compiler on the host system. Except that the extern (D) calling convention for Windows x86 is described here.

Register Conventions

Return Value

Parameters

The parameters to the non-variadic function:

foo(a1, a2, ..., an);
are passed as follows:
a1
a2
...
an
hidden
this

wherehidden is present if needed to return a struct value, andthis is present if needed as the this pointer for a member function or the context pointer for a nested function.

The last parameter is passed in EAX rather than being pushed on the stack if the following conditions are met:

Parameters are always pushed as multiples of 4 bytes, rounding upwards, so the stack is always aligned on 4 byte boundaries. They are pushed most significant first.out andref are passed as pointers. Static arrays are passed as pointers to their first element. On Windows, a real is pushed as a 10 byte quantity, a creal is pushed as a 20 byte quantity. On Linux, a real is pushed as a 12 byte quantity, a creal is pushed as two 12 byte quantities. The extra two bytes of pad occupy the ‘most significant’ position.

The callee cleans the stack.

The parameters to the variadic function:

void foo(int p1,int p2,int[] p3...)foo(a1, a2, ..., an);
are passed as follows:
p1
p2
a3
hidden
this

The variadic part is converted to a dynamic array and the rest is the same as for non-variadic functions.

The parameters to the variadic function:

void foo(int p1,int p2, ...)foo(a1, a2, a3, ..., an);
are passed as follows:
an
...
a3
a2
a1
_arguments
hidden
this

The caller is expected to clean the stack._argptr is not passed, it is computed by the callee.

Exception Handling

Windows 32 bit

Conforms to the Microsoft Windows Structured Exception Handling conventions.

Linux, FreeBSD and OS X

Conforms to the DWARF (debugging with attributed record formats) Exception Handling conventions.

Windows 64 bit

Uses static address range/handler tables. It is not compatible with the MSVC x64 exception handling tables. The stack is walked assuming it uses the EBP/RBP stack frame convention. The EBP/RBP convention must be used for every function that has an associated EH (Exception Handler) table.

For each function that has exception handlers, an EH table entry is generated.

EH Table Entry
fielddescription
void*pointer to start of function
DHandlerTable*pointer to corresponding EH data
uintsize in bytes of the function

The EH table entries are placed into the following special segments, which are concatenated by the linker.

EH Table Segment
Operating SystemSegment Name
Win32FI
Win64._deh$B
Linux.deh_eh
FreeBSD.deh_eh
OS X__deh_eh,__DATA

The rest of the EH data can be placed anywhere, it is immutable.

DHandlerTable
fielddescription
void*pointer to start of function
uintoffset of ESP/RSP from EBP/RBP
uintoffset from start of function to return code
uintnumber of entries inDHandlerInfo[]
DHandlerInfo[]array of handler information

DHandlerInfo
fielddescription
uintoffset from function address to start of guarded section
uintoffset of end of guarded section
intprevious table index
uintif != 0 offset to DCatchInfo data from start of table
void*if not null, pointer to finally code to execute

DCatchInfo
fielddescription
uintnumber of entries inDCatchBlock[]
DCatchBlock[]array of catch information

void*, catch handler code
DCatchBlock
fielddescription
ClassInfocatch type
uintoffset from EBP/RBP to catch variable

Garbage Collection

The interface to this is found in Druntime'score/gc/gcinterface.d.

ModuleInfo Instance

An instance ofModuleInfo is generated by the compiler and inserted into the object file for every module.ModuleInfo contains information about the module that is useful to the D runtime library:

ModuleInfo is defined in Druntime'sobject.d, which must match the compiler's output in both the values of flags and layout of fields.

Modules compiled with-betterC do not have aModuleInfo instance generated, because such modules must work without the D runtime library. Similarly,ImportC modules do not generate aModuleInfo.

Module Initialization and Termination

All the static constructors for a module are aggregated into a single function, and a pointer to that function is inserted into the ctor member of theModuleInfo instance for that module.

All the static destructors for a module are aggregated into a single function, and a pointer to that function is inserted into the dtor member of theModuleInfo instance for that module.

Unit Testing

All the unit tests for a module are aggregated into a single function, and a pointer to that function is inserted into the unitTest member of theModuleInfo instance for that module.

Runtime Helper Functions

These are found in Druntime'srt/.

Symbolic Debugging

D has types that are not represented in existing C or C++ debuggers. These are dynamic arrays, associative arrays, and delegates. Representing these types as structs causes problems because function calling conventions for structs are often different than that for these types, which causes C/C++ debuggers to misrepresent things. For these debuggers, they are represented as a C type which does match the calling conventions for the type.

Types for C Debuggers
D typeC representation
dynamic arrayunsigned long long
associative arrayvoid*
delegatelong long
dcharunsigned long

For debuggers that can be modified to accept new types, the following extensions help them fully support the types.

Codeview Debugger Extensions

The Ddchar type is represented by the special primitive type 0x78.

D makes use of the Codeview OEM generic type record indicated byLF_OEM (0x0015). The format is:

Codeview OEM Extensions for D
field size222222
D TypeLeaf IndexOEM IdentifierrecOEMnum indices type indextype index
dynamic arrayLF_OEMOEM12@index@element
associative arrayLF_OEMOEM22@key@element
delegateLF_OEMOEM32@this@function
where:
OEM0x42
indextype index of array index
keytype index of key
elementtype index of array element
thistype index of context pointer
functiontype index of function

These extensions can be pretty-printed byobj2asm. TheDdbg debugger supports them.

Memory Safety
Vector Extensions
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 18:05:52 2026

[8]ページ先頭

©2009-2026 Movatter.jp