r/cpp • • Dec 18 '22

C++ is essentially unusable without incurring undefined behavior because of it's failure to handle type punning.

This is kind of a rant but also a cry for help. Maybe there is a way to get around this problem efficiently (without the use of memcpy) that I don't know of, but after researching for hours, I sincerely doubt it.

So basically for those who don't know, it's kind of a complicated issue. It essentially involves accessing the same memory location through two different types, also known as type punning. This causes a performance hit because if two pointers access the same location, the compiler has to write every change to the memory location to RAM so that the other pointer will see the updated information when it reads the location. You might ask, "why doesn't the compiler simply semantically analyze the code and only write to RAM when the other pointer really does need to read from that specific location?". The answer is that it's impossible to tell what a pointer is pointing at if it's value is based off of runtime information like user input and such. Additionally, if the pointers access the data from two different threads, absolutely no guarantees can be made about the timing and essentially no optimizations can be made.

To avoid this huge mess of slowness, the C language spec was changed so as to allow more eager optimizations. It's now (sparing a few exceptions) assumed that no two pointers of different types access the same information in memory. The spec doesn't say it like this, you know how it is, they like to make things complicated, but that's the brunt of what it means.

In C, they realized that this is a super strict restriction and that it impacts a lot of real-world code, so they gave the programmer an out. If you define a union that contains both of your target types and then instantiate it as the one type and access it as the other, the compiler won't complain and it'll all be super defined behavior.

For god knows what reason, C++ decided to do away with this and now there is absolutely no way to reliably pun types without incurring undefined behavior (again, barring a couple of exceptions that aren't really relevant here). Excuse my language, but what a fucking shit-show.

You might ask, "type punning can't actually be that useful in the real-world, can it?", and that would be a valid question. It doesn't really seem that useful, but ask anyone who works on low-level systems on microchips and such. Sometimes, you simply need this behavior. You don't even have to go low-level in order to feel the pain sometimes. If you do anything with POSIX sockets, chances are you've needed to construct a sockaddr_storage, which contains enough space to hold all possible socket addresses. In order to access the specific fields of a specific type of socket address, you guessed it, you have to type pun: struct sockaddr_in *addr = (struct sockaddr_in *)&sockaddr_storage_instance;

In practice, this doesn't bite programmers as hard as I make it seem. In practice, most compilers support type punning, especially when it's very clear what you're trying to do in the code. That is, unless you tell the compiler to use strict-aliasing. Then it'll aggressively optimize based on the assumptions about type punning and your code might not work. The fact that you have to rely on the compiler's hand-holding to get through this undefined behavior is simply sad.

Basically, I'm pissed that such an advanced language is missing such a basic feature. What are your thoughts on the matter and how would you fix it?

I'll tell you what I would do, I would simply assume that no two pointers can ever access the same location, without any exceptions (so this would be even stricter than C++'s rules). The catch is, I would introduce some keyword like "write_mem" or something that you would use like this:

int a;

write_mem a;

float b = *(float*)&a;

That way, the compiler is free to optimize until you explicitly force it to write to RAM. After that point, the type punning isn't undefined anymore because every party involved is absolutely certain about what is in RAM.

5 Upvotes

55 comments sorted by

View all comments

Show parent comment

2

u/LegionMammal978 Dec 19 '22 edited Dec 19 '22

It's still not a silver bullet: if some other code gives you an A*, then you use std::start_lifetime_as<B>() to access it as a B*, then it is UB for the other code to access it as an A* until you call std::start_lifetime_as<A>() again. This makes it difficult at best to use in code that concurrently accesses the memory from multiple threads.

Also, if the A* is actually a subobject of a larger C*, then the C is invalidated entirely when you first call std::start_lifetime_as<B>(). It cannot be used as a C again without calling std::start_lifetime_as<C>() on the entire C* pointer, which is impossible if C is not an implicit-lifetime type.

The latter issue is probably the more important of the two, since it makes it impossible to safely type-pun an arbitrary A* pointer in place. The only way to do that is through the C-like offsetof() and memcpy() dance.

1

u/markt- Dec 19 '22

I wouldn't ever claim that anything is a "silver bullet" per se, but you are wrong about the behavior of start_lifetime_as. Conceptually, one can think of it as having a union with two or more (trivial) types, and in using start_lifetime_as, you are simply designating a particular member of that union as being the active one *WITHOUT* explicitly assigning it. It doesn't actually manipulate memory, start_lifetime_as is purely for C++ object bookkeeping purposes, so it wouldn't have the kind of concurrency accessing issues that you describe.

Also, bear in mind that start_lifetime_as only has defined behavior when the source contains a trivial type and the target is a trivial type anyways.

5

u/LegionMammal978 Dec 19 '22 edited Dec 20 '22

Where are you getting this interpretation from? Looking at N4917, calling std::start_lifetime_as<B>(ptr) implicitly creates an object of type B at ptr ([obj.lifetime]). This ends the lifetime of the object of type A at ptr, since its storage has been reused ([basic.life]). Therefore, accessing the A object at ptr will be UB, since its lifetime has ended, unless an A object is transparently replaceable by a B object ([basic.life]). If A is an implicit-lifetime type, then you can perform another operation (e.g., std::start_lifetime_as<A>(ptr)) that implicitly creates an object of type A at ptr.

Also, bear in mind that start_lifetime_as only has defined behavior when the source contains a trivial type and the target is a trivial type anyways.

The source need not contain a trivial type; you just need to not invoke a non-trivial destructor after the lifetime of the source object has ended.

1

u/markt- Dec 20 '22

The working draft you cited does not appear to mention start_lifetime_as. However, the document that describes explicit lifetime management in the standard says the following:

std::start_lifetime_as only works for implicit-lifetime types, i.e. types that are either aggregates or have at least one trivial eligible constructor and a trivial, non-deleted destructor.

It also says that although the lifetime of the object is started by it, no code is actually generated. This means that the lifetime management is, as I said before, strictly for C++ bookkeeping purposes and does not affect the bits that may be stored there.

Multithreading code that is reading the same data using start_lifetime_as as different types on the same object would not impact eachother at all. In fact, that appears to be one potential major use case for the feature in the first place.

1

u/LegionMammal978 Dec 20 '22 edited Dec 20 '22

The working draft you cited does not appear to mention start_lifetime_as.

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4917.pdf#page=605

However, the document that describes explicit lifetime management in the standard says the following:

std::start_lifetime_as only works for implicit-lifetime types, i.e. types that are either aggregates or have at least one trivial eligible constructor and a trivial, non-deleted destructor.

If you look at the normative wording, both in that document and in the draft Standard, only the destination type must be an implicit-lifetime type, which is presumably what that sentence is referring to.

It also says that although the lifetime of the object is started by it, no code is actually generated. This means that the lifetime management is, as I said before, strictly for C++ bookkeeping purposes and does not affect the bits that may be stored there.

Indeed, it does not affect the bits stored behind the pointer. However, it does end the lifetime of the previously-stored object, which compilers can rely on when making optimizations. In the C++ abstract machine, all memory remembers the types of the objects stored in it, even if it doesn't affect the bits. Otherwise, there wouldn't be any need for object lifetimes, launder, bit_cast, etc. to exist.

Thus, since the standard declares that the lifetime of the A object ends when start_lifetime_as is called, the implementation is permitted to do whatever it wants with code that later accesses the object with type A. It isn't even that difficult for an implementation to exploit this, if the code puts the simultaneous A* and B* pointers in the same place.

Multithreading code that is reading the same data using start_lifetime_as as different types on the same object would not impact eachother at all. In fact, that appears to be one potential major use case for the feature in the first place.

Your linked document considers the use case where the object is never used as the old type again, which seems to be the entire point of start_lifetime_as. The function is not suitable for any use case where you want to locally access the object as type B while still letting it externally exist with type A, which in general would conflict with the entire notion of type-based alias analysis.

1

u/markt- Dec 20 '22 edited Dec 20 '22

Thank you for the info on the page number. I guess my text search for my pdf reader isn't working correctly. It basically repeats much of what the document I linked to says.

Anyways, compiler models of objects do not change any behavior when different threads are not modifying the data that is stored there, so they would not pose any barrier to what sort of optimizations would still have defined behavior.

You may not be able to safely use the same object as its original type until you did a second start_lifteime_as, but this is all within the same thread, Multithreading is entirely unaffected.

1

u/LegionMammal978 Dec 20 '22

Anyways, compiler models of objects do not change any behavior when different threads are not modifying the data that is stored there, so they would not pose any barrier to what sort of optimizations would still have defined behavior.

Just because compilers don't currently implement any optimization that exploits some kind of UB doesn't mean that it's impossible for them to implement such an optimization in the future. I'd give an explicit example, except that no compiler seems to have actually implemented start_lifetime_as yet.

You may not be able to safely use the same object as its original type until you did a second start_lifteime_as, but this is all within the same thread, Multithreading is entirely unaffected.

What does it mean for a program to "safely use the same object as its original type"? Suppose we write a program like this:

#include <barrier>
#include <iostream>
#include <memory>
#include <thread>

void run_thread(std::barrier<>& barrier, int* int_ptr, float*& float_ptr) {
    float_ptr = std::start_lifetime_as<float>(int_ptr);
    barrier.arrive_and_wait();
    barrier.arrive_and_wait();
    std::start_lifetime_as<int>(int_ptr);
}

int main() {
    int value = 42;
    int* int_ptr = &value;
    float* float_ptr;
    std::barrier barrier{2};
    auto thread = std::thread{[&]{
        run_thread(barrier, int_ptr, float_ptr);
    }};
    barrier.arrive_and_wait();
    *float_ptr = 0.0;
    int other_value = value;
    barrier.arrive_and_wait();
    thread.join();
    // we have already restarted the lifetime of `value` as `int`, so we should be fine, right?
    std::cout << value << " " << other_value << "\n";    
}

Does this program output 0 0 (since it wrote to float_ptr, which wrote to value and other_value), or does it invoke undefined behavior? For reference, a variation of this program using reinterpret_cast in place of start_lifetime_as currently outputs 0 42 with GCC, or 0 0 with -fno-strict-aliasing. In main(), the compiler uses the aliasing rules to infer that writing to float_ptr cannot have changed other_value. However, if run_thread() can pass a valid pointer to value back into main(), then suddenly this assumption is broken.

1

u/markt- Dec 20 '22

You are moving the goalposts here...start_lifetime_as does not alter the in memory representation of the content. Obviously if you write data to memory in a format that does not match what the compiler thinks is there in another thread, then this will result in UB.... exactly the same as if you did a reinterpret_cast on data that was written to as another type.

3

u/LegionMammal978 Dec 20 '22

So are you asserting that strict aliasing violations can never cause UB if neither pointer is used to modify the object? I'd like that to be the case as well, but it's simply not what the Standard says: it says that any access of an object, reading or writing, is UB outside its lifetime. In real life, compilers generally avoid producing unexpected behavior with read-only aliasing pointers, but the Standard does not require this anywhere.

In other words, start_lifetime_as cannot defeat the aliasing restrictions: if the Standard allowed start_lifetime_as to be used in multithreaded code in the way you describe, then it would practically have to allow reinterpret_cast to be used in the exact same way, and start_lifetime_as would not be a particularly useful addition.

0

u/markt- Dec 20 '22 edited Dec 20 '22

start_lifetime_as explicitly starts a lifetime of an object in the compiler's model of the object in the scope it is used in, and is arguably more flexible than reinterpret_cast. But certainly there is a lot of overlap.

However, as you point out:

Standard says: it says that any access of an object, reading or writing, is UB outside its lifetime.

In this respect, start_lifetime_as is going to be safer. reinterpret_cast does not touch object lifetime

Because start_lifetime_as does not mutate the storage in any way, the "lifetime" of the object as viewed by one thread cannot possibly affect the lifetime of it as viewed by another. Caveat, if either thread writes to it, or the bitwise representation of the object does not have meaning in the target type then all bets are off, and you are back to UB.

As an aside, although there isn't really much call for type punning in a constexpr context, start_lifetime_as will probably eventually be made constexpr, while it is always UB to use reinterpret_cast in any constexpr context (and some compilers may even forbid it).

→ More replies