1  /* Passing tainted sizes to external functions with attribute ((access)) with
       2     a size-index.  */
       3  
       4  // TODO: remove need for the explicit taint option:
       5  /* { dg-additional-options "-fanalyzer-checker=taint -fanalyzer-show-duplicate-count" } */
       6  
       7  #include "analyzer-decls.h"
       8  #include <stdio.h>
       9  #include <stdlib.h>
      10  #include <string.h>
      11  
      12  struct foo
      13  {
      14    size_t sz;
      15  };
      16  
      17  char buf[100];
      18  
      19  extern void extern_fn_read_only (void *p, size_t sz) /* { dg-message "parameter 2 of 'extern_fn_read_only' marked as a size via attribute 'access \\(read_only, 1, 2\\)'" } */
      20    __attribute__ ((access (read_only, 1, 2)));
      21  
      22  void test_fn_read_only (FILE *f, void *p)
      23  {
      24    struct foo tmp;
      25    if (1 == fread(&tmp, sizeof(tmp), 1, f)) { /* { dg-message "\\(\[0-9\]+\\) 'tmp' gets an unchecked value here" "event: tmp gets unchecked value" { xfail *-*-* } } */
      26                                               /* { dg-message "\\(\[0-9\]+\\) following 'true' branch\\.\\.\\." "event: following true branch" { target *-*-* } .-1 } */
      27      __analyzer_dump_state ("taint", tmp.sz); /* { dg-warning "state: 'tainted'" } */
      28      /* { dg-message "\\(\[0-9\]+\\) \\.\\.\\.to here" "event: to here" { target *-*-* } .-1 } */
      29  
      30      extern_fn_read_only (p, tmp.sz); /* { dg-warning "use of attacker-controlled value 'tmp.sz' as size without upper-bounds checking" "warning" } */
      31      /* { dg-bogus "duplicate" "duplicate" { target *-*-* } .-1 } */
      32    }
      33  }
      34  
      35  /* We shouldn't complain if the value has been sanitized.  */
      36  
      37  void test_fn_sanitized (FILE *f, void *p)
      38  {
      39    struct foo tmp;
      40    if (1 == fread(&tmp, sizeof(tmp), 1, f)) {
      41      __analyzer_dump_state ("taint", tmp.sz); /* { dg-warning "state: 'tainted'" } */
      42  
      43      if (tmp.sz > 100)
      44        return;
      45  
      46      __analyzer_dump_state ("taint", tmp.sz); /* { dg-warning "state: 'has_ub'" } */
      47      
      48      extern_fn_read_only (p, tmp.sz); /* { dg-bogus "use of attacker-controlled value" } */
      49    }
      50  }
      51  
      52  /* We shouldn't complain if there was no size annotation.  */
      53  
      54  extern void extern_fn_no_size (void *p)
      55    __attribute__ ((access (read_only, 1)));
      56  
      57  void test_fn_no_size (FILE *f, void *p)
      58  {
      59    struct foo tmp;
      60    if (1 == fread(&tmp, sizeof(tmp), 1, f)) {
      61      __analyzer_dump_state ("taint", tmp.sz); /* { dg-warning "state: 'tainted'" } */
      62      extern_fn_no_size (p);
      63    }
      64  }