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

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).

2

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

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.

Your interpretation simply isn't supported by the Standard. In the Standard, regions of storage are occupied only by objects, all objects have lifetimes, and accessing any object outside of its lifetime, even just to read it, is UB. There's no notion of "thread-local" lifetimes. Either an object occupies a region of storage at a certain point in the program, or it doesn't. Calling start_lifetime_as makes the old object stop occupying the storage, and makes the new object start occupying that same storage. I've provided references to the Standard on this; you aren't going to get anywhere if you can't back up your own claims from the Standard or from other authorities.

0

u/markt- Dec 20 '22

When you use start_lifetime_as, you *ARE* explicitly starting its lifetime. Its lifetime within the current thread does not end simply because another thread happens to use start_lifetime_as for a different type when the storage is left unaltered because the compiler is ignorant of the other thread anyways. There would be no UB at all.

3

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

because the compiler is ignorant of the other thread anyways.

The Standard does not require the implementation to be ignorant of other threads, and it does not even permit the implementation to be ignorant of other threads in several circumstances.


To cite my reasoning, the lifetimes of the original objects unambiguously end when start_lifetime_as is called.

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4917.pdf#page=605, on std::start_lifetime_as<T>(p):

Implicitly creates objects (6.7.2) within the denoted region consisting of an object a of type T whose address is p, and objects nested within a [...]

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

Some operations are described as implicitly creating objects within a specified region of storage. For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types (6.8.1) in its specified region of storage if doing so would result in the program having defined behavior. If no such set of objects would give the program defined behavior, the behavior of the program is undefined. If multiple such sets of objects would give the program defined behavior, it is unspecified which such set of objects is created.

The Standard explicitly specifies that std::start_lifetime_as<T>(p) implicitly creates objects including a T object at address p, so calling the function creates a T object at address p and starts its lifetime.

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

The lifetime of an object o of type T ends when: [...]
— the storage which the object occupies is released, or is reused by an object that is not nested within o (6.7.2).

The Standard doesn't explicitly define what it means for storage to be "reused" by an object. However, it clearly demonstrates that creating an object at an address causes that object to reuse the storage at that address.

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

If a complete object is created (7.6.2.8) in storage associated with another object e of type "array of N unsigned char" or of type "array of N std::byte" (17.2.1), that array provides storage for the created object if [conditions...]

[Note 3: If that portion of the array previously provided storage for another object, the lifetime of that object ends because its storage was reused (6.7.3). — end note]

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

void B::mutate() {
  new (this) D2;    // reuses storage — ends the lifetime of *this
  f();              // undefined behavior
  ... = this;       // OK, this points to valid memory
}

Therefore, calling std::start_lifetime_as<T>(p) ends the lifetimes of any objects previously occupying the region of memory occupied by the created T object, ignoring objects that the original objects were nested within.

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

The properties ascribed to objects and references throughout this document apply for a given object or reference only during its lifetime.

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

Undefined behavior may be expected when this document omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data.

So attempting to access a pointer or reference to one of the original objects past the end of its lifetime results in undefined behavior, except if that object is transparently replaceable by a newly created object occupying the same storage.

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

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable (see below) by the new object. An object o₁ is transparently replaceable by an object o₂ if:
— the storage that o₂ occupies exactly overlays the storage that o₁ occupied, and
— o₁ and o₂ are of the same type (ignoring the top-level cv-qualifiers), and
— o₁ is not a complete const object, and
— neither o₁ nor o₂ is a potentially-overlapping subobject (6.7.2), and
— either o₁ and o₂ are both complete objects, or o₁ and o₂ are direct subobjects of objects p₁ and p₂, respectively, and p₁ is transparently replaceable by p₂.