# Alpha Checkers

Experimental checkers in addition to the Default Checkers. These are checkers with known issues or limitations that keep them from being on by default. They are likely to have false positives. Bug reports are welcome but will likely not be investigated for some time. Patches welcome!

- Clone Alpha Checkers
- Core Alpha Checkers
- C++ Alpha Checkers
- LLVM Checkers
- Variable Argument Alpha Checkers
- Dead Code Alpha Checkers
- OS X Alpha Checkers
- Security Alpha Checkers
- Unix Alpha Checkers
- Non-determinism Alpha Checkers

### Clone Alpha Checkers

Name, Description | Example
alpha.clone.CloneChecker (C, C++, ObjC) Reports similar pieces of code. |
    void log();

    int max(int a, int b) { // warn
      log();
      if (a > b)
        return a;
      return b;
    }

    int maxClone(int x, int y) { // similar code here
      log();
      if (x > y)
        return x;
      return y;
    }

### Core Alpha Checkers

Name, Description | Example
alpha.core.BoolAssignment (ObjC) Warn about assigning non-{0,1} values to boolean variables. |
    void test() {
      BOOL b = -1; // warn
    }
alpha.core.CallAndMessageUnInitRefArg (C, C++) Check for uninitialized arguments in function calls and Objective-C message expressions. |
    void test(void) {
      int t;
      int &p = t;
      int &s = p;
      int &q = s;
      foo(q); // warn
    }
    void test(void) {
      int x;
      foo(&x); // warn
    }
alpha.core.CastSize (C) Check when casting a malloc'ed type T, whether the size is a multiple of the size of T (Works only with unix.Malloc or alpha.unix.MallocWithAnnotations checks enabled). |
    void test() {
      int *x = (int *)malloc(11); // warn
    }
alpha.core.CastToStruct (C, C++) Check for cast from non-struct pointer to struct pointer. |
    // C
    struct s {};

    void test(int *p) {
      struct s *ps = (struct s *) p; // warn
    }
    // C++
    class c {};

    void test(int *p) {
      c *pc = (c *) p; // warn
    }
alpha.core.Conversion (C, C++, ObjC) Loss of sign or precision in implicit conversions |
    void test(unsigned U, signed S) {
      if (S > 10) {
        if (U < S) {
        }
      }
      if (S < -10) {
        if (U < S) { // warn (loss of sign)
        }
      }
    }
    void test() {
      long long A = 1LL << 60;
      short X = A; // warn (loss of precision)
    }
alpha.core.DynamicTypeChecker (ObjC) Check for cases where the dynamic and the static type of an object are unrelated. |
    id date = [NSDate date];

    // Warning: Object has a dynamic type 'NSDate *' which is
    // incompatible with static type 'NSNumber *'"
    NSNumber *number = date;
    [number doubleValue];
alpha.core.FixedAddr (C) Check for assignment of a fixed address to a pointer. |
    void test() {
      int *p;
      p = (int *) 0x10000; // warn
    }
alpha.core.IdenticalExpr (C, C++) Warn about suspicious uses of identical expressions. |
    // C
    void test() {
      int a = 5;
      int b = a | 4 | a; // warn: identical expr on both sides
    }
    // C++
    bool f(void);

    void test(bool b) {
      int i = 10;
      if (f()) { // warn: true and false branches are identical
        do {
          i--;
        } while (f());
      } else {
        do {
          i--;
        } while (f());
      }
    }
alpha.core.PointerArithm (C) Check for pointer arithmetic on locations other than array elements. |
    void test() {
      int x;
      int *p;
      p = &x + 1; // warn
    }
alpha.core.PointerSub (C) Check for pointer subtractions on two pointers pointing to different memory chunks. |
    void test() {
      int x, y;
      int d = &y - &x; // warn
    }
alpha.core.SizeofPtr (C) Warn about unintended use of `sizeof()` on pointer expressions. |
    struct s {};

    int test(struct s *p) {
      return sizeof(p);
        // warn: sizeof(ptr) can produce an unexpected result
    }
alpha.core.StackAddressAsyncEscape (C) Check that addresses to stack memory do not escape the function that involves `dispatch_after` or `dispatch_async`. This checker is a part of core.StackAddressEscape, but is temporarily disabled until some false positives are fixed. |
    dispatch_block_t test_block_inside_block_async_leak() {
      int x = 123;
      void (^inner)(void) = ^void(void) {
        int y = x;
        ++y;
      };
      void (^outer)(void) = ^void(void) {
        int z = x;
        ++z;
        inner();
      };
      return outer; // warn: address of stack-allocated block is captured by a
                    //       returned block
    }
alpha.core.TestAfterDivZero (C, C++, ObjC) Check for division by variable that is later compared against 0. Either the comparison is useless or there is division by zero. |
    void test(int x) {
      var = 77 / x;
      if (x == 0) { } // warn
    }

### C++ Alpha Checkers

Name, Description | Example
alpha.cplusplus.DeleteWithNonVirtualDtor (C++) Reports destructions of polymorphic objects with a non-virtual destructor in their base class |
    NonVirtual *create() {
      NonVirtual *x = new NVDerived(); // note: conversion from derived to base
                                       //       happened here
      return x;
    }

    void sink(NonVirtual *x) {
      delete x; // warn: destruction of a polymorphic object with no virtual
                //       destructor
    }
alpha.cplusplus.EnumCastOutOfRange (C++) Check for integer to enumeration casts that could result in undefined values. |
    enum TestEnum {
      A = 0
    };

    void foo() {
      TestEnum t = static_cast(-1);
          // warn: the value provided to the cast expression is not in
                   the valid range of values for the enum
    }
alpha.cplusplus.InvalidatedIterator (C++) Check for use of invalidated iterators. |
    void bad_copy_assign_operator_list1(std::list &L1,
                                        const std::list &L2) {
      auto i0 = L1.cbegin();
      L1 = L2;
      *i0; // warn: invalidated iterator accessed
    }
alpha.cplusplus.IteratorRange (C++) Check for iterators used outside their valid ranges. |
    void simple_bad_end(const std::vector &v) {
      auto i = v.end();
      *i; // warn: iterator accessed outside of its range
    }
alpha.cplusplus.MismatchedIterator (C++) Check for use of iterators of different containers where iterators of the same container are expected. |
    void bad_insert3(std::vector &v1, std::vector &v2) {
      v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed
                                                      //       using foreign
                                                      //       iterator argument
      v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of
                                                      //       different containers
                                                      //       used where the same
                                                      //       container is
                                                      //       expected
      v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of
                                                      //       different containers
                                                      //       used where the same
                                                      //       container is
                                                      //       expected
    }
alpha.cplusplus.Move (C++) Method calls on a moved-from object and copying a moved-from object will be reported. |
    struct A {
      void foo() {}
    };

    void f() {
      A a;
      A b = std::move(a); // note: 'a' became 'moved-from' here
      a.foo();            // warn: method call on a 'moved-from' object 'a'
    }

### Dead Code Alpha Checkers

Name, Description | Example
alpha.deadcode.UnreachableCode (C, C++, ObjC) Check unreachable code. |
    // C
    int test() {
      int x = 1;
      while(x);
      return x; // warn
    }
    // C++
    void test() {
      int a = 2;

      while (a > 1)
        a--;

      if (a > 1)
        a++; // warn
    }
    // Objective-C
    void test(id x) {
      return;
      [x retain]; // warn
    }

### LLVM Checkers

Name, Description | Example
alpha.llvm.Conventions (C) Check code for LLVM codebase conventions: A `StringRef` should not be bound to a temporary std::string whose lifetime is shorter than the `StringRef`'s. Clang AST nodes should not have fields that can allocate memory. |

### OS X Alpha Checkers

Name, Description | Example
alpha.osx.cocoa.DirectIvarAssignment (ObjC) Check that Objective C properties follow the following rule: the property should be set with the setter, not though a direct assignment. |
    @interface MyClass : NSObject {}
    @property (readonly) id A;
    - (void) foo;
    @end

    @implementation MyClass
    - (void) foo {
      _A = 0; // warn
    }
    @end
alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions (ObjC) Check for direct assignments to instance variables in the methods annotated with `objc_no_direct_instance_variable_assignment`. |
    @interface MyClass : NSObject {}
    @property (readonly) id A;
    - (void) fAnnotated __attribute__((
        annotate("objc_no_direct_instance_variable_assignment")));
    - (void) fNotAnnotated;
    @end

    @implementation MyClass
    - (void) fAnnotated {
      _A = 0; // warn
    }
    - (void) fNotAnnotated {
      _A = 0; // no warn
    }
    @end
alpha.osx.cocoa.InstanceVariableInvalidation (ObjC) Check that the invalidatable instance variables are invalidated in the methods annotated with `objc_instance_variable_invalidator`. |
    @protocol Invalidation <NSObject>
    - (void) invalidate
      __attribute__((annotate("objc_instance_variable_invalidator")));
    @end

    @interface InvalidationImpObj : NSObject <Invalidation>
    @end

    @interface SubclassInvalidationImpObj : InvalidationImpObj {
      InvalidationImpObj *var;
    }
    - (void)invalidate;
    @end

    @implementation SubclassInvalidationImpObj
    - (void) invalidate {}
    @end
    // warn: var needs to be invalidated or set to nil
alpha.osx.cocoa.MissingInvalidationMethod (ObjC) Check that the invalidation methods are present in classes that contain invalidatable instance variables. |
    @protocol Invalidation <NSObject>
    - (void)invalidate
      __attribute__((annotate("objc_instance_variable_invalidator")));
    @end

    @interface NeedInvalidation : NSObject <Invalidation>
    @end

    @interface MissingInvalidationMethodDecl : NSObject {
      NeedInvalidation *Var; // warn
    }
    @end

    @implementation MissingInvalidationMethodDecl
    @end
alpha.osx.cocoa.localizability.PluralMisuseChecker (ObjC) Warns against using one vs. many plural pattern in code when generating localized strings. |
    NSString *reminderText =
      NSLocalizedString(@"None", @"Indicates no reminders");
    if (reminderCount == 1) {
      // Warning: Plural cases are not supported across all languages.
      // Use a .stringsdict file instead
      reminderText =
        NSLocalizedString(@"1 Reminder", @"Indicates single reminder");
    } else if (reminderCount >= 2) {
      // Warning: Plural cases are not supported across all languages.
      // Use a .stringsdict file instead
      reminderText =
        [NSString stringWithFormat:
          NSLocalizedString(@"%@ Reminders", @"Indicates multiple reminders"),
            reminderCount];
    }

### Security Alpha Checkers

Name, Description | Example
alpha.security.ArrayBound (C) Warn about buffer overflows (older checker). |
    void test() {
      char *s = "";
      char c = s[1]; // warn
    }
    struct seven_words {
      int c[7];
    };

    void test() {
      struct seven_words a, *p;
      p = &a;
      p[0] = a;
      p[1] = a;
      p[2] = a; // warn
    }
    // note: requires unix.Malloc or
    // alpha.unix.MallocWithAnnotations checks enabled.
    void test() {
      int *p = malloc(12);
      p[3] = 4; // warn
    }
    void test() {
      char a[2];
      int *b = (int*)a;
      b[1] = 3; // warn
    }
alpha.security.ArrayBoundV2 (C) Warn about buffer overflows (newer checker). |
    void test() {
      char *s = "";
      char c = s[1]; // warn
    }
    void test() {
      int buf[100];
      int *p = buf;
      p = p + 99;
      p[1] = 1; // warn
    }
    // note: compiler has internal check for this.
    // Use -Wno-array-bounds to suppress compiler warning.
    void test() {
      int buf[100][100];
      buf[0][-1] = 1; // warn
    }
    // note: requires alpha.security.taint check turned on.
    void test() {
      char s[] = "abc";
      int x = getchar();
      char c = s[x]; // warn: index is tainted
    }
alpha.security.MallocOverflow (C) Check for overflows in the arguments to `malloc()`. |
    void test(int n) {
      void *p = malloc(n * sizeof(int)); // warn
    }
alpha.security.MmapWriteExec (C) Warn on `mmap()`calls that are both writable and executable.`` |
    void test(int n) {
      void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC,
                     MAP_PRIVATE | MAP_ANON, -1, 0);
      // warn: Both PROT_WRITE and PROT_EXEC flags are set. This can lead to
      //       exploitable memory regions, which could be overwritten with malicious
      //       code
    }
alpha.security.ReturnPtrRange (C) Check for an out-of-bound pointer being returned to callers. |
    static int A[10];

    int *test() {
      int *p = A + 10;
      return p; // warn
    }
    int test(void) {
      int x;
      return x; // warn: undefined or garbage returned
    }
alpha.security.taint.TaintPropagation (C) Generate taint information used by other checkers. |
    void test() {
      char x = getchar(); // 'x' marked as tainted
      system(&x); // warn: untrusted data is passed to a system call
    }
    // note: compiler internally checks if the second param to
    // sprintf is a string literal or not.
    // Use -Wno-format-security to suppress compiler warning.
    void test() {
      char s[10], buf[10];
      fscanf(stdin, "%s", s); // 's' marked as tainted

      sprintf(buf, s); // warn: untrusted data as a format string
    }
    void test() {
      size_t ts;
      scanf("%zd", &ts); // 'ts' marked as tainted
      int *p = (int *)malloc(ts * sizeof(int));
        // warn: untrusted data as buffer size
    }

### Unix Alpha Checkers

Name, Description | Example
alpha.unix.BlockInCriticalSection (C) Check for calls to blocking functions inside a critical section. Applies to: lock unlock sleep getc fgets read revc pthread_mutex_lock pthread_mutex_unlock mtx_lock mtx_timedlock mtx_trylock mtx_unlock lock_guard unique_lock |
    void test() {
      std::mutex m;
      m.lock();
      sleep(3); // warn: a blocking function sleep is called inside a critical
                //       section
      m.unlock();
    }
alpha.unix.Chroot (C) Check improper use of `chroot`. |
    void f();

    void test() {
      chroot("/usr/local");
      f(); // warn: no call of chdir("/") immediately after chroot
    }
alpha.unix.PthreadLock (C) Simple lock -> unlock checker; applies to: pthread_mutex_lock pthread_rwlock_rdlock pthread_rwlock_wrlock lck_mtx_lock lck_rw_lock_exclusive lck_rw_lock_shared pthread_mutex_trylock pthread_rwlock_tryrdlock pthread_rwlock_tryrwlock lck_mtx_try_lock lck_rw_try_lock_exclusive lck_rw_try_lock_shared pthread_mutex_unlock pthread_rwlock_unlock lck_mtx_unlock lck_rw_done |
    pthread_mutex_t mtx;

    void test() {
      pthread_mutex_lock(&mtx);
      pthread_mutex_lock(&mtx);
        // warn: this lock has already been acquired
    }
    lck_mtx_t lck1, lck2;

    void test() {
      lck_mtx_lock(&lck1);
      lck_mtx_lock(&lck2);
      lck_mtx_unlock(&lck1);
        // warn: this was not the most recently acquired lock
    }
    lck_mtx_t lck1, lck2;

    void test() {
      if (lck_mtx_try_lock(&lck1) == 0)
        return;

      lck_mtx_lock(&lck2);
      lck_mtx_unlock(&lck1);
        // warn: this was not the most recently acquired lock
    }
alpha.unix.SimpleStream (C) Check for misuses of stream APIs: fopen fclose (demo checker, the subject of the demo (Slides ,Video) by Anna Zaks and Jordan Rose presented at the 2012 LLVM Developers' Meeting). |
    void test() {
      FILE *F = fopen("myfile.txt", "w");
    } // warn: opened file is never closed
    void test() {
      FILE *F = fopen("myfile.txt", "w");

      if (F)
        fclose(F);

      fclose(F); // warn: closing a previously closed file stream
    }
alpha.unix.Stream (C) Check stream handling functions: fopen tmpfile fclose fread fwrite fseek ftell rewind fgetpos fsetpos clearerr feof ferror fileno |
    void test() {
      FILE *p = fopen("foo", "r");
    } // warn: opened file is never closed
    void test() {
      FILE *p = fopen("foo", "r");
      fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL
      fclose(p);
    }
    void test() {
      FILE *p = fopen("foo", "r");

      if (p)
        fseek(p, 1, 3);
         // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR

      fclose(p);
    }
    void test() {
      FILE *p = fopen("foo", "r");
      fclose(p);
      fclose(p); // warn: already closed
    }
    void test() {
      FILE *p = tmpfile();
      ftell(p); // warn: stream pointer might be NULL
      fclose(p);
    }
alpha.unix.cstring.BufferOverlap (C) Checks for overlap in two buffer arguments; applies to: memcpy mempcpy |
    void test() {
      int a[4] = {0};
      memcpy(a + 2, a + 1, 8); // warn
    }
alpha.unix.cstring.NotNullTerminated (C) Check for arguments which are not null-terminated strings; applies to: strlen strnlen strcpy strncpy strcat strncat |
    void test() {
      int y = strlen((char *)&test); // warn
    }
alpha.unix.cstring.OutOfBounds (C) Check for out-of-bounds access in string functions; applies to: strncopy strncat |
    void test(char *y) {
      char x[4];
      if (strlen(y) == 4)
        strncpy(x, y, 5); // warn
    }

### Non-determinism Alpha Checkers

Name, Description | Example
alpha.nondeterminism.PointerIteration (C++) Check for non-determinism caused by iterating unordered containers of pointers. |
    // C++
    void test() {
     int a = 1, b = 2;
     std::unordered_set UnorderedPtrSet = {&a, &b};

     for (auto i : UnorderedPtrSet) // warn
       f(i);
    }
alpha.nondeterminism.PointerSorting (C++) Check for non-determinism caused by sorting of pointers. |
    // C++
    void test() {
     int a = 1, b = 2;
     std::vector V = {&a, &b};
     std::sort(V.begin(), V.end()); // warn
    }