Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions cpp/ql/src/semmle/code/cpp/Union.qll
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ class Union extends Struct {
override string explain() { result = "union " + this.getName() }

override predicate isDeeplyConstBelow() { any() } // No subparts

/** Holds if this type is anonymous. */
final predicate isAnonymous() {
getName() = "union <unnamed>" and
exists(Variable v | v.getType() = this and v.getName() = "(null)")
}
}

/**
Expand Down Expand Up @@ -64,3 +70,16 @@ class NestedUnion extends Union {
/** Holds if this member is public. */
predicate isPublic() { this.hasSpecifier("public") }
}

/**
* A C/C++ anonymous union. For example:
* ```
* union {
* int i;
* float f;
* };
* ```
*/
class AnonymousUnion extends Union {
AnonymousUnion() { this.isAnonymous() }
}
3 changes: 0 additions & 3 deletions cpp/ql/src/semmle/code/cpp/UserType.qll
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ class UserType extends Type, Declaration, NameQualifyingElement, AccessHolder, @

override predicate hasName(string name) { usertypes(underlyingElement(this), name, _) }

/** Holds if this type is anonymous. */
predicate isAnonymous() { getName().matches("(unnamed%") }

override predicate hasSpecifier(string s) { Type.super.hasSpecifier(s) }

override Specifier getASpecifier() { result = Type.super.getASpecifier() }
Expand Down
2 changes: 2 additions & 0 deletions cpp/ql/test/library-tests/unions/Unions1.expected
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@
| unions.cpp:27:9:27:20 | MyLocalUnion | LocalUnion, Struct, Union | | operator= |
| unions.cpp:33:7:33:13 | MyClass | | | operator= |
| unions.cpp:36:9:36:21 | MyNestedUnion | NestedUnion, Struct, Union | | operator= |
| unions.cpp:43:9:43:9 | union <unnamed> | AnonymousUnion, LocalUnion, Struct, Union | | operator= |
| unions.cpp:48:9:48:9 | union <unnamed> | LocalUnion, Struct, Union | | operator= |
3 changes: 3 additions & 0 deletions cpp/ql/test/library-tests/unions/Unions1.ql
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ string describe(Class c) {
or
c instanceof NestedUnion and
result = "NestedUnion"
or
c instanceof AnonymousUnion and
result = "AnonymousUnion"
}

from Class c
Expand Down
12 changes: 12 additions & 0 deletions cpp/ql/test/library-tests/unions/unions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,15 @@ class MyClass
float f;
};
};

void test_anonymous_union() {
union {
int u1;
char* u2;
};

union {
int u3;
char* u4;
} not_an_anonymous_union;
}