Repository navigation
[Clang] Diagnose UB and emit error when identifier has both internal and external linkage - #192116
Conversation
|
@llvm/pr-subscribers-clang Author: Aditya Medhane (flash1729) ChangesC11 6.2.2p7 says if the same identifier appears with both internal and external linkage in a translation unit, the behavior is undefined. This patch adds a check in Fixes #54215 4 Files Affected:
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fd58d7847717c..f1efd5f8c3b35 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -366,6 +366,10 @@ Improvements to Clang's diagnostics
code can automatically be made portable to other host platforms that don't
support backslashes.
+- Clang now diagnoses the undefined behavior described in C11 6.2.2p7 where
+ the same identifier appears with both internal and external linkage within a
+ translation unit. (#GH54215)
+
Improvements to Clang's time-trace
----------------------------------
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6d2fae551566f..8981d30475dde 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6528,6 +6528,9 @@ def err_inline_declaration_block_scope : Error<
"inline declaration of %0 not allowed in block scope">;
def err_static_non_static : Error<
"static declaration of %0 follows non-static declaration">;
+def err_internal_extern_mismatch : Error<
+ "variable %0 declared with both internal and external linkage "
+ "in the same translation unit; behavior is undefined">;
def err_different_language_linkage : Error<
"declaration of %0 has a different language linkage">;
def ext_retained_language_linkage : Extension<
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 9f8fc5a187b0a..19cc36446eedb 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4800,6 +4800,24 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
return New->setInvalidDecl();
}
}
+
+ // C11 6.2.2p7:
+ // If, within a translation unit, the same identifier appears with both
+ // internal and external linkage, the behavior is undefined.
+ //
+ // This can occur when an extern declaration in block scope finds a file-scope
+ // static declaration, but a no-linkage local variable shadowed the static,
+ // preventing linkage inheritance per C11 6.2.2p4.
+ if (New->isLocalVarDecl() && New->hasExternalStorage() &&
+ Old->isFileVarDecl() && Old->hasLinkage() &&
+ Previous.isShadowed() &&
+ Old->getFormalLinkage() == Linkage::Internal) {
+ Diag(New->getLocation(), diag::err_internal_extern_mismatch)
+ << New->getDeclName();
+ Diag(OldLocation, PrevDiag);
+ return New->setInvalidDecl();
+ }
+
// C99 6.2.2p4:
// For an identifier declared with the storage-class specifier
// extern in a scope in which a prior declaration of that
diff --git a/clang/test/Sema/linkage-internal-extern.c b/clang/test/Sema/linkage-internal-extern.c
new file mode 100644
index 0000000000000..42591c5b21f0b
--- /dev/null
+++ b/clang/test/Sema/linkage-internal-extern.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -verify -fsyntax-only %s
+
+// C11 6.2.2p7: same identifier with both internal and external linkage is UB.
+
+// Conflicting linkage (UB)
+
+static int x; // expected-note {{previous}}
+void test_basic_shadow(void) {
+ int x;
+ { extern int x; } // expected-error {{declared with both internal and external linkage}}
+}
+
+static int y; // expected-note {{previous}}
+void test_deep_nesting(void) {
+ int y;
+ { int y; { { extern int y; } } } // expected-error {{declared with both internal and external linkage}}
+}
+
+static int p; // expected-note {{previous}}
+void test_param_shadow(int p) {
+ { extern int p; } // expected-error {{declared with both internal and external linkage}}
+}
+
+// Valid cases
+
+static int a;
+void test_no_shadow(void) {
+ extern int a;
+}
+
+void test_no_file_scope(void) {
+ for (static int b = 0;;) {
+ extern int b;
+ break;
+ }
+}
|
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
995fc69 to
c06f721
Compare
🪟 Windows x64 Test Results
✅ The build succeeded and all tests passed. |
🐧 Linux x64 Test Results
✅ The build succeeded and all tests passed. |
|
Can you add a test for c++ too? This is https://cplusplus.github.io/CWG/issues/426.html |
AaronBallman
left a comment
There was a problem hiding this comment.
Thank you for working on this! This is actually a requirement for C2y now, because WG14 adopted https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3410.pdf
Note, CWG426 was adopted by WG21 in C++17 but the current wording now requires a particular behavior in C++: https://eel.is/c++draft/basic.link#4 (see the example in p6 as well). Amazingly, you can declare the variable as extern in C++ and it will have internal linkage (wow), and we definitely do not do that: https://godbolt.org/z/sYdxGaeer (look at the AST dump for the final declarations of i and f and see we give them external linkage while the standard now says they should have internal linkage). Changing this behavior in C++ will be an ABI break so I do not recommend trying to untangle the C++ bits in this PR -- that's better as a follow-up, IMO.
|
hey @AaronBallman, addressed all your review points. |
|
Oops, it looks like you've got a private email address: We require public emails in our developer policy: https://llvm.org/docs/DeveloperPolicy.html#email-addresses Can you set yours to public? |
|
actually i resolved one merge conflict using github's web ui and that's the commit which is causing problem, working on to fix that quickly |
d96412c to
ad332e7
Compare
|
@AaronBallman I fetched upstream and cherry-picked all related commits, PR's ready to merge |
…nkage C11 6.2.2p7 states that if the same identifier appears with both internal and external linkage within a translation unit, the behavior is undefined. This occurs when a block-scope extern declaration finds a file-scope static declaration, but a no-linkage local variable shadows the static, preventing linkage inheritance per C11 6.2.2p4. Fixes llvm#54215
ad332e7 to
3f215c1
Compare
|
cool finally I think I have made all the expected changes @AaronBallman |
Weirdly, it still shows you as having a non-public email address: |
|
I turned off the private email setting and set my public email to my personal one on my GitHub profile. |
That seems to have solved it, the changes landed with the right email address. Thank you! |
|
Great 👍, thanks a lot for your help and patience. I learnt multiple things. |
There was a problem hiding this comment.
TL;DR: CWG426 was superseded by P1787R6, @AaronBallman apparently got confused by an AST dump, extern declarations can have internal linkage since C89, and comments in linkage-internal-extern.cpp are entirely wrong.
(look at the AST dump for the final declarations of i and f and see we give them external linkage while the standard now says they should have internal linkage).
If you interpreted extern at the end as an indication of linkage, this is how AST dump looks like with getFormalLinkage():
|-FunctionDecl 0x55657e43d9d0 <test.cxx:1:1, col:15> col:13 f 'void ()' static internal-linkage
|-LinkageSpecDecl 0x55657e43dae0 <line:2:1, col:19> col:8 C
| `-FunctionDecl 0x55657e43db50 <col:12, col:19> col:17 h 'void ()' external-linkage
|-VarDecl 0x55657e43dc10 <line:3:1, col:16> col:12 i 'int' static cinit internal-linkage
| `-IntegerLiteral 0x55657e43dc78 <col:16> 'int' 0
`-FunctionDecl 0x55657e43dd00 <line:4:1, line:13:1> line:4:6 q 'void ()' external-linkage
`-CompoundStmt 0x55657e43e2c8 <col:10, line:13:1>
|-DeclStmt 0x55657e43de80 <line:5:3, col:18>
| `-FunctionDecl 0x55657e43ddc8 parent 0x55657e3eea58 prev 0x55657e43d9d0 <col:3, col:17> col:15 f 'void ()' extern internal-linkage
|-DeclStmt 0x55657e43df70 <line:6:3, col:18>
| `-FunctionDecl 0x55657e43deb8 parent 0x55657e3eea58 <col:3, col:17> col:15 g 'void ()' extern external-linkage
|-DeclStmt 0x55657e43e060 <line:7:3, col:18>
| `-FunctionDecl 0x55657e43dfa8 parent 0x55657e3eea58 prev 0x55657e43db50 <col:3, col:17> col:15 h 'void ()' extern external-linkage
|-DeclStmt 0x55657e43e0f8 <line:8:3, col:8>
| `-VarDecl 0x55657e43e090 <col:3, col:7> col:7 i 'int' no-linkage
`-CompoundStmt 0x55657e43e2a8 <line:9:3, line:12:3>
|-DeclStmt 0x55657e43e1e8 <line:10:5, col:20>
| `-FunctionDecl 0x55657e43e130 parent 0x55657e3eea58 prev 0x55657e43ddc8 <col:5, col:19> col:17 f 'void ()' extern internal-linkage
`-DeclStmt 0x55657e43e290 <line:11:5, col:17>
`-VarDecl 0x55657e43e218 parent 0x55657e3eea58 prev 0x55657e43dc10 <col:5, col:16> col:16 i 'int' extern internal-linkage
As you can see, the last two declarations (of i and f, respectively) have internal linkage. This was observed in our default GNU++17 mode.
When I checked a similar C example taken from N3410, the block scope extern had external linkage, as the C wording says.
This Core issue and its resolution were superseded by P1787R6 "Declarations and where to find them", adopted into C++23 (not as a DR, but we handle the example in [basic.link]/6 the same way in C++98 mode as in GNU++17 mode).
extern declarations with internal linkage in C
Amazingly, you can declare the variable as extern in C++ and it will have internal linkage (wow)
C89 3.1.2.2 Linkage of identifiers:
If the declaration of an identifier for an object or a function contains the storage-class specifier
extern, the identifier has the same linkage as any visible declaration of the identifier with file scope. If there is no visible declaration with file scope, the identifier has external linkage.
static int k = 0; // internal linkage
void f() {
extern int k; // inherits internal linkage from prior visible declaration per C89 wording
}|-VarDecl 0x55996df164b0 <test.c:1:1, col:16> col:12 k 'int' static cinit internal-linkage
| `-IntegerLiteral 0x55996df16560 <col:16> 'int' 0
`-FunctionDecl 0x55996df16620 <line:2:1, line:4:1> line:2:6 f 'void ()' external-linkage
`-CompoundStmt 0x55996df16770 <col:10, line:4:1>
`-DeclStmt 0x55996df16758 <line:3:3, col:15>
`-VarDecl 0x55996df166e0 parent 0x55996deae9d8 prev 0x55996df164b0 <col:3, col:14> col:14 k 'int' extern internal-linkage
Analysis of the C++ example ([basic.link]/6)
Per [dcl.meaning]/3.5:
If the declaration inhabits a block scope S and declares a function ([dcl.fct]) or uses the
externspecifier, the declaration shall not be attached to a named module ([module.unit]); its target scope is the innermost enclosing namespace scope, but the name is bound in S.
Which means declaration matching between innermost and outermost i succeeds ([basic.link]/8) irrespective of i at block scope that has no linkage. Then innermost i receives the linkage of the previous declaration. This is not captured in the wording of [basic.link], but is captured as CWG2938 "Inheriting linkage from a previous declaration". ("While the wording is in dire need of improvement here" refers to the first 4 paragraphs of [basic.link] and speaks volumes about the quality of the existing wording.)
| { | ||
| // FIXME: Per CWG 426, this should be ill-formed because the | ||
| // file-scope 'x' has internal linkage but this 'extern' gets | ||
| // external linkage due to the local shadow. |
There was a problem hiding this comment.
Nothing to fix here: this x already has internal linkage.
| // CWG 426 / [basic.link]p6: the same identifier with both internal and | ||
| // external linkage should be ill-formed in C++, but Clang does not yet | ||
| // diagnose this due to ABI break concerns. This test documents current | ||
| // behavior. |
There was a problem hiding this comment.
The quoted wording is long gone, and there's nothing to diagnose, because two declarations of x that have linkage both have internal linkage and declare the same entity at namespace scope.
Great catch, thank you for this! Let's revert the PR so that @flash1729 can fix things up and we can re-land in a better state.
Ugh, yeah, I got caught by that. It turns out that even a JSON dump is a bit confusing, it only lists the storage class but not the formal linkage. Tricky!
Ah, now that I see the formal linkage dumped, yup. The wording in C2y is different from C89 but is functionally equivalent. |
…nternal and external linkage" (#193462) Reverts #192116 See comments at #192116 (review)
… has both internal and external linkage" (#193462) Reverts llvm/llvm-project#192116 See comments at llvm/llvm-project#192116 (review)
… has both internal and external linkage" (#193462) Reverts llvm/llvm-project#192116 See comments at llvm/llvm-project#192116 (review)
|
I just now discovered that the spirit of the resolution of CWG426 lives on as [dcl.stc]/6:
This doesn't change any of the analysis above. It's just that "resolution of CWG426 is superseded by P1787R6" means something different from what I meant earlier today, but the wording in the resolution still did not survive to the present day. |
…and external linkage (llvm#192116) C11 6.2.2p7 says if the same identifier appears with both internal and external linkage in a translation unit, the behavior is undefined. This patch adds a check in `Sema::MergeVarDecl` that uses `LookupResult::isShadowed()` to detect when a block-scope `extern` found a file-scope `static` through a shadow, and emits an error. Fixes llvm#54215
…nternal and external linkage" (llvm#193462) Reverts llvm#192116 See comments at llvm#192116 (review)
… has both internal and external linkage" (#193462) Reverts llvm/llvm-project#192116 See comments at llvm/llvm-project#192116 (review)
…and external linkage (llvm#192116) C11 6.2.2p7 says if the same identifier appears with both internal and external linkage in a translation unit, the behavior is undefined. This patch adds a check in `Sema::MergeVarDecl` that uses `LookupResult::isShadowed()` to detect when a block-scope `extern` found a file-scope `static` through a shadow, and emits an error. Fixes llvm#54215
…nternal and external linkage" (llvm#193462) Reverts llvm#192116 See comments at llvm#192116 (review)
…and external linkage (llvm#192116) C11 6.2.2p7 says if the same identifier appears with both internal and external linkage in a translation unit, the behavior is undefined. This patch adds a check in `Sema::MergeVarDecl` that uses `LookupResult::isShadowed()` to detect when a block-scope `extern` found a file-scope `static` through a shadow, and emits an error. Fixes llvm#54215
…nternal and external linkage" (llvm#193462) Reverts llvm#192116 See comments at llvm#192116 (review)
This PR adds formal linkage (external, module, internal) to the textual AST dumps. The motivation is to inform users (including ourselves) what Clang thinks the linkage is, and to prevent situations where `extern` is mistaken for an indication of external linkage (see #192116 for an example). The wording around linkage is known to be defective, but that's the best we have: [[basic.link]](https://eel.is/c++draft/basic.link) paragraphs 3 through 7. There are enough changes in this PR, so I decided to defer adding formal linkage to JSON dumps to another PR. (Open questions and suggestions for reviewers are in #194600 (comment)) --------- Co-authored-by: Matheus Izvekov <[email protected]>
This PR adds formal linkage (external, module, internal) to the textual AST dumps. The motivation is to inform users (including ourselves) what Clang thinks the linkage is, and to prevent situations where `extern` is mistaken for an indication of external linkage (see llvm#192116 for an example). The wording around linkage is known to be defective, but that's the best we have: [[basic.link]](https://eel.is/c++draft/basic.link) paragraphs 3 through 7. There are enough changes in this PR, so I decided to defer adding formal linkage to JSON dumps to another PR. (Open questions and suggestions for reviewers are in llvm#194600 (comment)) --------- Co-authored-by: Matheus Izvekov <[email protected]>
C11 6.2.2p7 says if the same identifier appears with both internal and external linkage in a translation unit, the behavior is undefined.
This patch adds a check in
Sema::MergeVarDeclthat usesLookupResult::isShadowed()to detect when a block-scopeexternfound a file-scopestaticthrough a shadow, and emits an error.Fixes #54215