Skip to content

Commit

Permalink
test: Add a test for typedef array parameter size check.
Browse files Browse the repository at this point in the history
  • Loading branch information
iphydf committed Jan 10, 2024
1 parent a5cb6d5 commit c2a7132
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Tokstyle/C/Linter/SizeArg.hs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import Tokstyle.C.TraverseAst (AstActions (..), astActions,

checkArraySizes :: Ident -> [(ParamDecl, CExpr, Type)] -> Trav Env ()
checkArraySizes funId ((_, _, arrTy@(ArrayTypeSize arrSize)):(ParamName sizeParam, sizeArg, sizeTy):args)
| isIntegral sizeTy && any (`List.isInfixOf` sizeParam) ["size", "len"] =
| any (`List.isInfixOf` sizeParam) ["size", "len"] =
-- Ignore any name lookup errors here. VLAs have locally defined
-- array sizes, but we don't check VLAs.
catchTravError (do
Expand Down
20 changes: 20 additions & 0 deletions test/Tokstyle/C/Linter/SizeArgSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,26 @@ spec = do
]
]

it "works on typedef array parameters" $ do
ast <- mustParse
[ "enum { CRYPTO_PUBLIC_KEY_SIZE = 32 };"
, "enum { EXTENDED_PUBLIC_KEY_SIZE = 64 };"
, "typedef char Public_Key[CRYPTO_PUBLIC_KEY_SIZE];"
, "typedef void consume_cb(char *arr, int size);"
, "void caller(consume_cb *consume, Public_Key pk) {"
, " consume(pk, EXTENDED_PUBLIC_KEY_SIZE);"
, "}"
]
analyse allWarnings ast
`shouldBe`
[ Text.unlines
[ "test.c:6: (column 15) [ERROR] >>> Type mismatch"
, " size parameter `size` is passed constant value `EXTENDED_PUBLIC_KEY_SIZE` (= 64),"
, " which is greater than the array size of `char [CRYPTO_PUBLIC_KEY_SIZE]`,"
, " potentially causing buffer overrun in `consume`"
]
]

it "warns about string literal overrun" $ do
ast <- mustParse
[ "void consume(char *arr, int size);"
Expand Down
1 change: 1 addition & 0 deletions tokstyle.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ test-suite testsuite
Tokstyle.Linter.CompoundInitSpec
Tokstyle.Linter.ConstnessSpec
Tokstyle.Linter.EnumDefinesSpec
Tokstyle.Linter.MallocCallSpec
Tokstyle.Linter.ParensSpec
Tokstyle.Linter.SwitchIfSpec
Tokstyle.Linter.TypeCheckSpec
Expand Down

0 comments on commit c2a7132

Please sign in to comment.