Showing posts with label cpp_abi. Show all posts
Showing posts with label cpp_abi. Show all posts

Jan 26, 2021

[C++] trivial_abi and borrow ownership

An interesting concept comes up from Rust's borrow ownership.

In C++, the unique_ptr can only be moved. While instead of using heavy-weighted shared_ptr
(i.e 2 words size, heap allocated control block, atomic ref-counting, weak_ptr etc.), the only way of borrow the ownership from unique_ptr is by passing raw pointer from unique_ptr.

Here's the tweet from Prof. John Regehr talking about this:
https://twitter.com/johnregehr/status/1351333748277592065
Follow up from s.o:
https://stackoverflow.com/a/30013891
i.e in C++, the borrow concept can't be made in compile time, but in runtime, which unlike Rust.

Another to mention about is trivial_abi.
AMD64 ABI for C++: https://www.uclibc.org/docs/psABI-x86_64.pdf

While call by value,

Quote from ABI:
If a C++ object has either a non-trivial copy constructor or a non-trivial destructor, it is passed by invisible reference (the object is replaced in the parameter list by a pointer […]).

And in Itanium C++ ABI document, quote:

non-trivial for the purposes of calls
A type is considered non-trivial for the purposes of calls if: it has a non-trivial copy constructor, move constructor, or destructor, or all of its copy and move constructors are deleted.
This definition, as applied to class types, is intended to be the complement of the definition in [class.temporary]p3 of types for which an extra temporary is allowed when passing or returning a type. A type which is trivial for the purposes of the ABI will be passed and returned according to the rules of the base C ABI, e.g. in registers; often this has the effect of performing a trivial copy of the type.

That is call by value with non-trivial type introduce double indirection during the call while the type could potentially not fit into the register for callee.  By double indirection meaning the argument is reference to the temporary r-value created on caller's stack.
i.e potential virtual pointer to v-table increases the size of type.


Reference: https://www.raywenderlich.com/615-assembly-register-calling-convention-tutorial

Assembly code can be found in godbolt:
https://godbolt.org/z/s1TPea6sx


#include <cstdio>

#define TRIVIAL_ABI __attribute__((trivial_abi))

template <class T> T incr(T obj) {
  obj.value += 1;
  puts("before exit incr func");
  return obj;
}

struct Up1 {
  int value;
  Up1() = default;
  Up1(const Up1& u) : value(u.value) { puts("Up1 copy constructor"); }
  ~Up1() { printf("detroyed Up1 value: %d\n", value); }
};

struct TRIVIAL_ABI Up2 {
  int value;
  Up2() = default;
  Up2(const Up1& u) : value(u.value) { puts("Up2 copy constructor"); }
  ~Up2() { printf("detroyed Up2 value: %d\n", value); }
};

template Up1 incr(Up1);
template Up2 incr(Up2);

auto main() -> int {
  auto u1 = Up1{};
  puts("before call incr func for u1");
  incr(u1);

  printf("\n\n");

  auto u2 = Up2{};
  puts("before call incr func for u2");
  incr(u2);
}

Output:
before call incr func for u1
Up1 copy constructor; temporary object creatd;
before exit incr func
Up1 copy constructor; temporary object creatd;
detroyed Up1 value: 1
detroyed Up1 value: 1


before call incr func for u2
// No temporary object created, all in register.
before exit incr func
detroyed Up2 value: 1
detroyed Up2 value: 1
detroyed Up2 value: 0
detroyed Up1 value: 0

Sep 30, 2019

[C++] ABI compatibility

Reference:
https://www.acodersjourney.com/20-abi-breaking-changes/
https://community.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B
https://community.kde.org/Policies/Binary_Compatibility_Examples


Each of these items needless to memorize, it's listed for convenience.
All based on memory layout reasoning. (plus linking logics)


Break ABI changes:
  1. Un-export or remove a class from the shared library
  2. Un-export or remove a function or method from a class
  3. Change the signature of any method in the class. This includes
    Changing the return type
    Changing the order of parameters
    Change the access rights ( eg. public to protected)
    Removing or adding parameters
  4. Add, remove, or re-order member variables in a class
  5. Change the type of any member variable in a class
  6. Change the class hierarchy  of the class exposed in shared library:
    make the exposed class inherit from a different base class
    make the exposed class  inherit from additional base classes
    remove base class(es) from the exposed class
  7. Change the template arguments (add, remove, re-order) of a templated class
    In line with #3 above since changing the template arguments changes the underlying function signatures generated when the template is instantiated
  8. Inline a function in an exported class
    When a function is declared inlined, the compiler inlines it where the function is called and may not generate an out-of-line copy. The client binary, which was thus far depending on the exported out-of-line function signature cannot locate it and will fail in unexpected ways (crash most likely).
  9. Change the const or volatile qualifier of a member function
    Some compilers encode the const-ness of a function in the mangled name and hence changing the function from const to non-const changes the mangled name.
  10. Change the type of global data
  11. Changing the const or volatile qualifiers on global data
  12. Adding an explicit copy constructor or destructor to a class that would otherwise have implicit versions.
    Reference: https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html
  13. Changing a non-virtual method to be virtual, and vice versa.
  14. Adding a virtual method to a class with no existing virtual methods.
  15. Changing the order of virtual methods.
  16. Adding new virtual methods (some compilers may preserve binary compatibility if you only add new virtual methods after existing ones).
  17. Override a virtual that doesn't come from a primary base
  18. Remove a virtual function, even if it is a reimplementation of a virtual function from the base class
  19. Change the calling convention of an exported function ( from _stdcall to _cdecl and vice versa)
  20. If passing C++ types across shared library boundary, make sure that your client binary and shared library are compiled with the same version of the compiler.


ABI remains with these changes:
  1. Add new class to the shared library
  2. Add new free functions
  3. Add new non-virtual method to an existing class
  4. Add new static variables to a class
  5. Remove private static variable
    (if never referenced from an inline method)
  6. Remove non-virtual private method (if never called from an inline method)
  7. Change the implementation of an inline method
  8. Change an inline method to non-inline
  9. Adding new constructors to the class
  10. Add a new enum to a class
  11. Append new enum values to an existing enum class
  12. Change the default arguments of a method
  13. Add or remove friend declarations from a class
  14. Add new static data members
  15. Extend reserved bit fields, provided this doesn't cause the bit field to cross the boundary of its underlying type
    (8 bits for char & bool, 16 bits for short, 32 bits for int, etc.)

Jan 31, 2019

[C++][note] ABI compatibility and inline namespaces - Arvid Norberg

Quick note/refresh about ABI through Arvid Norberg's talk.




ABI is about linking.
Reference:
https://vsdmars.blogspot.com/2015/09/linking-notes.html


Calling convention

Reference:
https://en.wikipedia.org/wiki/X86_calling_conventions
The history of calling conventions series - Raymond Chen
https://blogs.msdn.microsoft.com/oldnewthing/20040102-00/?p=41213
https://blogs.msdn.microsoft.com/oldnewthing/20040107-00/?p=41183
https://blogs.msdn.microsoft.com/oldnewthing/20040108-00/?p=41163
https://blogs.msdn.microsoft.com/oldnewthing/20040114-00/?p=41053
https://www.codeproject.com/Articles/1388/Calling-Conventions-Demystified
https://www.agner.org/optimize/calling_conventions.pdf
x64 calling convention
https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=vs-2017
Stack frame layout on x86-64
https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/

- which registers to pass arguments in
- pass two 32bit arguments in 64bit registers
- split structs and pass fields in registers
- pass floats in special registers
- pass arguments in SIMD registers
- return value optimization
- how are exceptions thrown


Class layouts:

- vtable layout
- where/how we pad fields
- empty base class optimization
- std::pair (compressed_pair)
- std::string (SSO)


Across library boundaries:

- C++ version
- may affect layout
- name mangling
- calling convention
- defines
- may affect layout (e.g _GLIBCXX_USE_CXX11_ABI)
- any compiler flag alters layout or calling conventions


'#define' harms, beware of using it which breaks
the compile ABI.

In Golang, it simply asks you to recompile everything again
with same version of compiler.

In C++, we often have .so (SONAME) libraries.
This is where the trouble begins(Or solved).



Name mangling:

- Trouble in shared libraries.
- release mode library and debug mode client.
- C++98 library and C++11 client.
- Library headers is newer than library binary.



Solution:

- Auh, like Golang, recompile everything.
- Use a build system which ensures what we build is
link-compatible.
i.e
build system should give us separate library builds,
release build, debug build, etc.

If we tried to build release against debug library, build
system should fail us..



Inline namespaces come to the rescue:

Reference:
[C++] inline namespace compile time replacement trick.
https://vsdmars.blogspot.com/2016/02/c-inline-namespace-compile-time.html
C++11-FAQ-BS
http://www.stroustrup.com/C++11FAQ.html#inline-namespace

- inline namespaces let us inject information into the mangled
name(ABI), without altering the API.
i.e
for the caller always refers to the symbol inside the namespace function
regardless the namespace's internal inline namespace is.

This trick can go further since specialized temaplte can be defined
in the namespace which embeds the inline namespace's main template.

- inline namespaces affect the linker names of symbols,
While preserving the API.
From caller's perspective, the callee's name remains the same,
regardless where the name coming from different inlined namespace.



Forward declarations:

- A symbol's actual namespace is an implementation detail.
- Clients may not forward declare 3rd party symbols.
(because that symbol might be an inline namespace symbol,
which during a real linking stage, compile fails~~~)


Summary:

- Always build from the source (if there's no versioning .so, SONAME available)
- Use inline namespace for backward compatible upgrades to the ABI
(use with #define)
- Use inline namespace for ABI-safe build configurations
- Library authors, provide forward declaration headers (versioned, of course)


Nov 20, 2013

[c++14][NOTE] pointer to function do have linkage in C++14

excerpt from Scott Meyers' New C++ Closures as Function Pointers: Capture‐less closures implicitly convert to function pointers:
 
int (*fp)(int) = [](int x) { return x * x; };
Such closures can be treated like functions.
 No need for std::function to refer to them.
 No captures ⇒ no stored pointers or references ⇒ no dangling.
 Often useful for callbacks with C‐like APIs:
 
int atexit(void (*f)()) noexcept; // from <cstdlib>
std::atexit([]{ logMsg("Shutting down..."); });
In C++11, function pointer linkage not specified ⇒ possible linkage problems.
 C++14 specifies C++ linkage.
noexcept akin to throw(), but enables more optimizations.
 Violated noexcept ⇒ terminate.
 Exception specifications now deprecated.

Sep 9, 2012

[C++]Something about Application Binary Interface(ABI)

Stability of the C++ ABI: Evolution of a Programing Language[SUN/ORACLE]
ABI: problems of C++ programs compatibility at the binary interface level
gcc manual , Binary Compatibility
libstdc++ : ABI Policy and Guidelines
Linux and C++ ABI
C++ ABI issues list[stackoverflow]
The big problem, in my experience, is the C++ standard library. Even if you had an 
ABI that dictates how a class should be laid out, different compilers provide different implementations of standard objects
like std::string and std::vector. I'm not saying that it would not be possible to standardize the internal layout of C++
library objects, only that it has not been done before.

C++ ABI Summary

C++ ABI [In Simplified Chinese/CN]
 Several errors and mostly copy from  "Stability of the C++ ABI: Evolution of a Programing Language".
But if we know C++ Object Model, could identify it easily.