1 #include <stdlib.h>
2 #include <stdio.h>
3 
4 #include "libgccjit.h"
5 
6 #include "harness.h"
7 
8 void
9 create_code (gcc_jit_context *ctxt, void *user_data)
10 {
11   /* Let's try to inject the equivalent of:
12        char
13        test_array_bounds (void)
create_code(gcc_jit_context * ctxt,void * user_data)14        {
15 	  char buffer[10];
16 	  return buffer[10];
17        }
18      with -Warray-bounds and -ftree-vrp and verify that the
19      out-of-bounds access is detected and reported as a jit error.  */
20   gcc_jit_context_add_command_line_option (ctxt, "-Warray-bounds");
21   gcc_jit_context_add_command_line_option (ctxt, "-ftree-vrp");
22 
23   /* Ensure that the error message doesn't contain colorization codes
24      or escaped URLs, even if run at a TTY.  */
25   gcc_jit_context_add_command_line_option (ctxt, "-fdiagnostics-color=never");
26   gcc_jit_context_add_command_line_option (ctxt, "-fdiagnostics-urls=never");
27 
28   gcc_jit_type *char_type =
29     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CHAR);
30   gcc_jit_type *array_type =
31     gcc_jit_context_new_array_type (ctxt, NULL,
32 				    char_type, 10);
33   gcc_jit_type *int_type =
34     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
35 
36   /* Build the test_fn.  */
37   gcc_jit_function *test_fn =
38     gcc_jit_context_new_function (ctxt, NULL,
39 				  GCC_JIT_FUNCTION_EXPORTED,
40 				  char_type,
41 				  "test_array_bounds",
42 				  0, NULL,
43 				  0);
44   gcc_jit_lvalue *buffer =
45     gcc_jit_function_new_local (test_fn, NULL, array_type, "buffer");
46 
47   /* tree-vrp.c:check_all_array_refs only checks array lookups that
48      have source locations.  */
49   gcc_jit_location *dummy_loc =
50     gcc_jit_context_new_location (ctxt, "dummy.c", 10, 4);
51 
52   gcc_jit_block *block = gcc_jit_function_new_block (test_fn, NULL);
53   gcc_jit_rvalue *index =
54     gcc_jit_context_new_rvalue_from_int (ctxt, int_type, 10);
55   gcc_jit_lvalue *read_of_the_buffer =
56     gcc_jit_context_new_array_access (ctxt, dummy_loc,
57 				      gcc_jit_lvalue_as_rvalue (buffer),
58 				      index);
59   gcc_jit_block_end_with_return (
60     block, dummy_loc,
61     gcc_jit_lvalue_as_rvalue (read_of_the_buffer));
62 }
63 
64 void
65 verify_code (gcc_jit_context *ctxt, gcc_jit_result *result)
66 {
67   /* Verify that the diagnostic led to the context failing... */
68   CHECK_VALUE (result, NULL);
69 
70   /* ...and that the message was captured by the API.  */
71   CHECK_STRING_VALUE (gcc_jit_context_get_first_error (ctxt),
72 		      "array subscript 10 is above array bounds of"
73 		      " 'unsigned char[10]' [-Warray-bounds]");
74 }
75