| 1 |
/* { dg-skip-if "requires hosted libstdc++ for stdlib malloc" { ! hostedlib } } */ |
| 2 |
|
| 3 |
/* A toy re-implementation of CPython's object model. */ |
| 4 |
|
| 5 |
#include <stddef.h> |
| 6 |
#include <string.h> |
| 7 |
#include <stdlib.h> |
| 8 |
#include "analyzer-decls.h" |
| 9 |
|
| 10 |
typedef struct base_obj |
| 11 |
{ |
| 12 |
struct type_obj *ob_type; |
| 13 |
int ob_refcnt; |
| 14 |
} base_obj; |
| 15 |
|
| 16 |
typedef struct type_obj |
| 17 |
{ |
| 18 |
base_obj tp_base; |
| 19 |
void (*tp_dealloc) (base_obj *); |
| 20 |
} type_obj; |
| 21 |
|
| 22 |
typedef struct boxed_int_obj |
| 23 |
{ |
| 24 |
base_obj int_base; |
| 25 |
int int_val; |
| 26 |
} boxed_int_obj; |
| 27 |
|
| 28 |
extern void int_del (base_obj *); |
| 29 |
|
| 30 |
type_obj type_type = { |
| 31 |
{ &type_type, 1} |
| 32 |
}; |
| 33 |
|
| 34 |
type_obj boxed_int_type = { |
| 35 |
{ &type_type, 1}, |
| 36 |
int_del |
| 37 |
}; |
| 38 |
|
| 39 |
base_obj *alloc_obj (type_obj *ob_type, size_t sz) |
| 40 |
{ |
| 41 |
base_obj *obj = (base_obj *)malloc (sz); |
| 42 |
if (!obj) |
| 43 |
return NULL; |
| 44 |
obj->ob_type = ob_type; |
| 45 |
obj->ob_refcnt = 1; |
| 46 |
return obj; |
| 47 |
} |
| 48 |
|
| 49 |
base_obj *new_int_obj (int val) |
| 50 |
{ |
| 51 |
boxed_int_obj *int_obj |
| 52 |
= (boxed_int_obj *)alloc_obj (&boxed_int_type, sizeof (boxed_int_obj)); |
| 53 |
if (!int_obj) |
| 54 |
return NULL; |
| 55 |
int_obj->int_val = val; |
| 56 |
return (base_obj *)int_obj; |
| 57 |
} |
| 58 |
|
| 59 |
void unref (base_obj *obj) |
| 60 |
{ |
| 61 |
if (--obj->ob_refcnt == 0) |
| 62 |
obj->ob_type->tp_dealloc (obj); |
| 63 |
} |
| 64 |
|
| 65 |
void test_1 (const char *str) |
| 66 |
{ |
| 67 |
base_obj *obj = new_int_obj (42); |
| 68 |
if (!obj) |
| 69 |
return; |
| 70 |
__analyzer_eval (((boxed_int_obj *)obj)->int_val == 42); /* { dg-warning "TRUE" } */ |
| 71 |
__analyzer_eval (obj->ob_refcnt == 1); /* { dg-warning "TRUE" } */ |
| 72 |
unref (obj); |
| 73 |
} /* { dg-bogus "leak" "" } */ |