From e13fcff3454becbc35099fd43e934a8436e5a13c Mon Sep 17 00:00:00 2001 From: Jie Zhou <6649997+jzhou76@users.noreply.github.com> Date: Thu, 18 Jul 2019 15:19:45 -0700 Subject: [PATCH] Disallow explicit cast to nt_array_ptr in checked scopes (#391) (#626) 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. --- include/clang/Basic/DiagnosticSemaKinds.td | 4 ++++ lib/Sema/SemaCast.cpp | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td index f628fe0caf0e..8e5c41790a82 100644 --- a/include/clang/Basic/DiagnosticSemaKinds.td +++ b/include/clang/Basic/DiagnosticSemaKinds.td @@ -9867,6 +9867,10 @@ def err_bounds_type_annotation_lost_checking : Error< def err_checked_scope_no_assume_bounds_casting : Error< "_Assume_bounds_cast not allowed in a checked scope or function">; + def err_checked_scope_no_cast_to_nt_array_ptr : Error< + "%0 cannot be cast to %1 in a checked scope because " + "%0 might not point to a null-terminated array">; + def err_checked_on_non_function : Error< "%select{'_Unchecked'|'_Checked _Bounds_only|'_Checked'}0 " "can only appear on functions">; diff --git a/lib/Sema/SemaCast.cpp b/lib/Sema/SemaCast.cpp index 8abc2ef3ade1..a7fd1a75cfcc 100644 --- a/lib/Sema/SemaCast.cpp +++ b/lib/Sema/SemaCast.cpp @@ -2700,6 +2700,19 @@ void CastOperation::CheckCStyleCast(bool IsCheckedScope) { SrcExpr = ExprError(); return; } + + // Disallow cast from other Checked Pointer types to nt_arary_ptr because + // the SrcType might not point to a NULL-terminated array. + if (DestType->isPointerType() && DestType->isCheckedPointerNtArrayType()) { + if (SrcType->isPointerType() && !SrcType->isCheckedPointerNtArrayType()) { + Self.Diag(SrcExpr.get()->getExprLoc(), + diag::err_checked_scope_no_cast_to_nt_array_ptr) + << SrcType << DestType << SrcExpr.get()->getSourceRange(); + SrcExpr = ExprError(); + return; + } + } + } DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);