Issue 233519
Summary [analyzer] Detect misuse of placement new
Labels new issue
Assignees
Reporter mark-zilber
    `cplusplus.PlacementNew` checks the size and alignment of the placement buffer. I'd like to add checks for three other kinds of placement new misuse. They correspond to two entries of the [potential checkers list](https://clang-analyzer.llvm.org/potential_checkers.html): `ctordtor.PlacementSelfCopy` and `undefbehavior.ObjLocChanges`.

**1. The new object is initialized from the storage it is placed into** (`ctordtor.PlacementSelfCopy`)

```cpp
class A {};

void test(A *dst, A *src) {
  ::new (dst) A(*dst); // warn (should be 'src')
}
```

The constructor overwrites its own source. If the constructor is inlined, the checker reports the first read of a part of the storage that has already been written. Otherwise, it reports a copy or move constructor whose source is the target storage. `std::construct_at(p, *p)`, array placement new and initializer lists like `::new (p) Point{p->Y, p->X}` are covered as well.

**2. Deleting through the old type after placement new** (`undefbehavior.ObjLocChanges`, [expr.delete]/3)

```cpp
class A { public: ~A(); };
class B : public A {};

void test() {
  A *a = new A;
  new (a) B;
  delete a; // warn: deleting an object of type 'B' through a pointer to 'A'
}
```

**3. The destructor of the old object runs on the new one** (`undefbehavior.ObjLocChanges`, [basic.life]/11)

```cpp
class A {};
class B { public: ~B(); };

void test() {
  B b;
  new (&b) A;
} // warn: destructor of 'B' is called on storage that holds an object of type 'A'
```

Related: #164963 asked LifetimeSafety to detect use after destruction, double destruction and construction over a live object, and #194030 added placement new support there. The cases above are not part of that work.

I have implementations for all three with tests and I'm checking them on a few open-source projects. I'm working on this and plan to send one PR per checker: `alpha.cplusplus.PlacementSelfCopy` for (1) and `alpha.cplusplus.ObjLocChanges` for (2) and (3).

@steakhal @NagyDonat, are separate alpha checkers fine, or would you prefer these as sub-checkers of `cplusplus.PlacementNew`?

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to