Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tunz committed Mar 10, 2018
0 parents commit 252d02a
Show file tree
Hide file tree
Showing 36 changed files with 2,952 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.cabal-sandbox
dist

*.swp
core
5 changes: 5 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Revision history for chow

## 0.1.0.0 -- 2018-03-10

* First version. Released on an unsuspecting world.
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) 2018 Choongwoo Han <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Chow

Static Analysis Checker with Micro-Grammar based on this academic paper [How to build static checking systems using orders of magnitude less code](https://web.stanford.edu/~mlfbrown/paper.pdf). Current version only supports Null Pointer Dereference Checker targeting C code as a default.

## Example

Run chow on `examples/c/nullptr/nullptr1.c`.
```c
...
void case1(MyStruct *ptr) {
printf("elem1: %d\n", ptr->elem1); // XXX: null-pointer-dereference

if (!ptr) {
// Use-then-check
printf("elem2: %d\n", ptr->elem2);
} else {
// Check-then-use
printf("eleme2 is null: %d\n", ptr->elem2);
}
}
...
```
```
$ cabal build
$ ./dist/build/chow-cli/chow-cli ./examples/c/nullptr/nullptr1.c
Language: C
Checker: Default
Running Time: 0.002030201s
[Detect]
ptr is dereferenced in "./examples/c/nullptr/nullptr1.c" (line 13, column 25)
ptr is believed to be 'IsBoth' in "./examples/c/nullptr/nullptr1.c" (line 15, column 10)
```
2 changes: 2 additions & 0 deletions Setup.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain
95 changes: 95 additions & 0 deletions chow-cli/Main.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
module Main where

import Control.Monad
import Data.Char
import Data.Maybe
import Data.Semigroup ((<>))
import Data.Time
import Options.Applicative
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import System.Posix.Files

import Chow.Checker
import Chow.Common

data Args = Args
{ checker :: Maybe String
, lang :: Maybe String
, isDir :: Bool
, path :: String }

main :: IO ()
main = execParser opts
>>= parseArgs
>>= checkTime <$> runChecker
>>= mapM_ (putStrLn.snd)
where
opts = info (args <**> helper)
( fullDesc
<> progDesc "Static Analysis Checker with Micro-Grammar")
args = Args
<$> optional ( strOption
( long "checker"
<> short 'c'
<> help "Checker" ))
<*> optional ( strOption
( long "lang"
<> short 'l'
<> help "Programming Language" ))
<*> switch
( long "isdir"
<> short 'd'
<> help "The given file path is directory")
<*> argument str
( metavar "path"
<> help "File or Directory Path" )

parseArgs (Args checker lang isDir path) =
if langType == LangUnknown
then failAndExit "Please specify a programming language"
else putStrLn ("Language: " ++ show langType)
>> putStrLn ("Checker: " ++ show ckType)
>> fmap (Options ckType langType) getPaths
where
ckType = detectChecker checker
detectChecker _ = TypeNone

langType = detectLang $ lowerString lang
detectLang "c" = LangC
detectLang "c++" = LangCpp
detectLang "cpp" = LangCpp
detectLang "cc" = LangCpp
detectLang _ = LangUnknown
lowerString (Just str) = [ toLower c | c <- str ]
lowerString Nothing = lowerString (Just fileExt)
fileExt = safeTail $ takeExtension path
safeTail "" = ""
safeTail (x:xs) = xs

getPaths | not isDir = return [path]
| isDir = traverseDir path findExtFiles
findExtFiles x = any (`endsWith` x) (extsFrom langType)
extsFrom LangC = [".c"]
extsFrom LangCpp = [".c", ".cpp", ".cc"]
endsWith endstr [] = False
endsWith endstr str = endstr == str || endsWith endstr (tail str)
traverseDir top include = do
ds <- listDirectory top
paths <- forM ds $ \d -> do
let path = top </> d
s <- getSymbolicLinkStatus path
if isDirectory s
then traverseDir path include
else (if include path then return [path] else return [])
return (concat paths)

checkTime fn = do
start <- getCurrentTime
result <- fn
stop <- getCurrentTime
putStr "Running Time: "
print $ diffUTCTime stop start
return result
77 changes: 77 additions & 0 deletions chow.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
-- Initial chow.cabal generated by cabal init. For further
-- documentation, see http://haskell.org/cabal/users-guide/

-- The name of the package.
name: chow

-- The package version. See the Haskell package versioning policy (PVP)
-- for standards guiding when and how versions should be incremented.
-- https://wiki.haskell.org/Package_versioning_policy
-- PVP summary: +-+------- breaking API changes
-- | | +----- non-breaking API additions
-- | | | +--- code changes with no API change
version: 0.1.0.0

-- A short (one-line) description of the package.
-- synopsis:

-- A longer description of the package.
-- description:

-- The license under which the package is released.
license: MIT

-- The file containing the license text.
license-file: LICENSE

-- The package author(s).
author: Choongwoo Han

-- An email address to which users can send suggestions, bug reports, and
-- patches.
maintainer: [email protected]

-- A copyright notice.
-- copyright:

-- category:

build-type: Simple

-- Extra files to be distributed with the package, such as examples or a
-- README.
extra-source-files: ChangeLog.md

-- Constraint on the version of Cabal needed to build this package.
cabal-version: >=1.10

library
hs-source-dirs: src
exposed-modules:
Chow.Checker,
Chow.Common
Chow.Token,
Chow.C.Ast,
Chow.C.Checker,
Chow.C.NullDerefChecker,
Chow.C.Parser,
Chow.Cpp.Ast,
Chow.Cpp.Parser
build-depends: base >= 4.6 && < 5, parsec, transformers,
containers
default-language: Haskell2010

executable chow-cli
hs-source-dirs: chow-cli
main-is: Main.hs
build-depends: base >= 4.6 && < 5, chow, optparse-applicative,
semigroups, filepath, time, directory >= 1.2.5.0, unix
default-language: Haskell2010

test-suite test
hs-source-dirs: tests
main-is: Test.hs
other-modules: C.NullDerefTest, C.ParserTest, Cpp.ParserTest
build-depends: base >= 4.6 && < 5, tasty >= 0.7, tasty-hunit, parsec, chow, containers
default-language: Haskell2010
type: exitcode-stdio-1.0
33 changes: 33 additions & 0 deletions examples/c/nullptr/nullptr1.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h>

struct some_struct {
int elem1;
int elem2;
int *ptrelem;
struct some_struct *next;
};
typedef struct some_struct MyStruct;

void case1(MyStruct *ptr) {
printf("elem1: %d\n", ptr->elem1); // XXX: null-pointer-dereference

if (!ptr) {
// Use-then-check
printf("elem2: %d\n", ptr->elem2);
} else {
// Check-then-use
printf("eleme2 is null: %d\n", ptr->elem2);
}
}

int main() {
int val = 10;
MyStruct* ptr = malloc(sizeof(MyStruct));
ptr->elem1 = 1;
ptr->elem2 = 1;
ptr->ptrelem = &val;

case1(ptr);
case1(NULL);
}
25 changes: 25 additions & 0 deletions examples/c/nullptr/nullptr10.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>

struct some_struct {
int elem1;
int elem2;
int *ptrelem;
struct some_struct *next;
};
typedef struct some_struct MyStruct;

void case10(MyStruct *ptr) {
printf("%d\n", ptr ? 1 : 2);
printf("%d\n", ptr->elem1); // XXX: null-pointer-dereference
}

int main() {
int val = 10;
MyStruct* ptr = malloc(sizeof(MyStruct));
ptr->elem1 = 1;
ptr->elem2 = 1;
ptr->ptrelem = &val;

case10(NULL);
}
76 changes: 76 additions & 0 deletions examples/c/nullptr/nullptr11.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include <stdio.h>
#include <stdlib.h>

struct some_struct {
int elem1;
int elem2;
int *ptrelem;
struct some_struct *next;
};
typedef struct some_struct MyStruct;

MyStruct * make_new_struct(MyStruct *ptr) {
if (ptr)
free(ptr);

return malloc(sizeof(MyStruct));
}

void case11(MyStruct *ptr1, MyStruct *ptr2, MyStruct *ptr3) {
int val;

if (ptr1 == NULL || ptr1->ptrelem == NULL)
goto out;

printf("%d\n", ptr1->elem1); // False positive case

switch (ptr1->elem1) {
case 1:
if (!ptr3)
break;
printf("%d\n", ptr3->elem1);
ptr3 = malloc(sizeof(MyStruct));
if (!ptr3) // False positive case
goto out;
break;
default:
if (!ptr2->elem1 && !ptr2->elem2)
break;
if (!ptr2->elem1)
printf("%d\n", ptr2->elem2);
}
if (ptr3)
printf("test ahah\n");

ptr1 = make_new_struct(ptr1);
if (ptr1 == NULL) {
ptr1 = make_new_struct(ptr1);
if (ptr1 == NULL)
return;
val = 2;
} else
val = 1;

printf("%d %d\n", val, ptr1->elem1); // False positive case

ptr1 = make_new_struct(ptr1);
if (ptr1)
ptr1->elem1 = 0;
if (!ptr1)
return;
ptr1->elem1 = 2; // Fales positive case
out:
if (ptr1)
printf("something");
return;
}

int main() {
int val = 10;
MyStruct* ptr = malloc(sizeof(MyStruct));
ptr->elem1 = 1;
ptr->elem2 = 1;
ptr->ptrelem = &val;

case11(NULL, NULL, NULL);
}
Loading

0 comments on commit 252d02a

Please sign in to comment.