Skip to content

Commit fac9bd0

Browse files
jiezhoucsMandeep Singh Grang
authored and
Mandeep Singh Grang
committed
Disallow explicit cast to nt_array_ptr in checked scopes (#391) (#626)
Cherry-picked from commit e13fcff Disallow cast from other checked pointer types to nt_array_ptr in checked scopes because the source pointer might not point to a NULL_terminated array. Casting from an unchecked pointer to a nt_array_ptr pointer should also be prohibited; this has already been handled as no unchecked pointers are allowed in checked scopes. Also added a new error message in clang/include/clang/Basic/DiagnosticSemaKinds.td for casting to nt_array_ptr in checked scopes. The test file tests/typechecking/checked_scope_basic.c was updated with a new function test_cast_to_nt_array_ptr to test casting to nt_array_ptr.
1 parent 1e790c9 commit fac9bd0

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9867,6 +9867,10 @@ def err_bounds_type_annotation_lost_checking : Error<
98679867
def err_checked_scope_no_assume_bounds_casting : Error<
98689868
"_Assume_bounds_cast not allowed in a checked scope or function">;
98699869

9870+
def err_checked_scope_no_cast_to_nt_array_ptr : Error<
9871+
"%0 cannot be cast to %1 in a checked scope because "
9872+
"%0 might not point to a null-terminated array">;
9873+
98709874
def err_checked_on_non_function : Error<
98719875
"%select{'_Unchecked'|'_Checked _Bounds_only|'_Checked'}0 "
98729876
"can only appear on functions">;

clang/lib/Sema/SemaCast.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2700,6 +2700,19 @@ void CastOperation::CheckCStyleCast(bool IsCheckedScope) {
27002700
SrcExpr = ExprError();
27012701
return;
27022702
}
2703+
2704+
// Disallow cast from other Checked Pointer types to nt_arary_ptr because
2705+
// the SrcType might not point to a NULL-terminated array.
2706+
if (DestType->isPointerType() && DestType->isCheckedPointerNtArrayType()) {
2707+
if (SrcType->isPointerType() && !SrcType->isCheckedPointerNtArrayType()) {
2708+
Self.Diag(SrcExpr.get()->getExprLoc(),
2709+
diag::err_checked_scope_no_cast_to_nt_array_ptr)
2710+
<< SrcType << DestType << SrcExpr.get()->getSourceRange();
2711+
SrcExpr = ExprError();
2712+
return;
2713+
}
2714+
}
2715+
27032716
}
27042717

27052718
DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);

0 commit comments

Comments
 (0)