Harald Welte | 2d90611 | 2019-03-18 17:17:43 +0100 | [diff] [blame] | 1 | #include <stdint.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <unistd.h> |
| 4 | #include <stdio.h> |
| 5 | |
| 6 | #include <sys/eventfd.h> |
| 7 | |
| 8 | #include <osmocom/core/logging.h> |
| 9 | #include <osmocom/core/application.h> |
| 10 | #include <osmocom/core/utils.h> |
| 11 | #include <osmocom/core/select.h> |
| 12 | #include <osmocom/core/talloc.h> |
| 13 | |
| 14 | static struct osmo_fd g_evfd; |
| 15 | |
| 16 | static void *alloc_res_select; |
| 17 | static void *alloc_res_global; |
| 18 | |
| 19 | static int destructor_called; |
| 20 | |
| 21 | static int talloc_destructor(void *ptr) |
| 22 | { |
| 23 | printf("destructor was called automatically\n"); |
| 24 | /* ensure the destructor is only called for the chunk allocated from the |
| 25 | * volatile select context */ |
| 26 | OSMO_ASSERT(ptr == alloc_res_select); |
| 27 | destructor_called += 1; |
| 28 | return 0; |
| 29 | } |
| 30 | |
| 31 | static int evfd_cb(struct osmo_fd *ofd, unsigned int what) |
| 32 | { |
| 33 | uint64_t rval; |
| 34 | int rc; |
| 35 | |
| 36 | rc = read(ofd->fd, &rval, sizeof(rval)); |
| 37 | OSMO_ASSERT(rc == sizeof(rval)); |
| 38 | |
| 39 | printf("allocating from select context\n"); |
| 40 | alloc_res_select = talloc_named_const(OTC_SELECT, 23, "alloc_select"); |
| 41 | OSMO_ASSERT(alloc_res_select); |
| 42 | talloc_set_destructor(alloc_res_select, talloc_destructor); |
| 43 | |
| 44 | printf("allocating from global context\n"); |
| 45 | alloc_res_global = talloc_named_const(OTC_GLOBAL, 42, "alloc_global"); |
| 46 | OSMO_ASSERT(alloc_res_global); |
| 47 | talloc_set_destructor(alloc_res_global, talloc_destructor); |
| 48 | return 0; |
| 49 | } |
| 50 | |
| 51 | const struct log_info_cat default_categories[] = { |
| 52 | }; |
| 53 | |
| 54 | static struct log_info info = { |
| 55 | .cat = default_categories, |
| 56 | .num_cat = ARRAY_SIZE(default_categories), |
| 57 | }; |
| 58 | |
| 59 | int main(int argc, char **argv) |
| 60 | { |
| 61 | int rc; |
| 62 | |
| 63 | osmo_init_logging2(OTC_GLOBAL, &info); |
| 64 | |
| 65 | rc = eventfd(0, 0); |
| 66 | OSMO_ASSERT(rc >= 0); |
| 67 | osmo_fd_setup(&g_evfd, rc, OSMO_FD_READ, evfd_cb, NULL, 0); |
| 68 | osmo_fd_register(&g_evfd); |
| 69 | |
| 70 | /* make sure the select loop will immediately call the callback */ |
| 71 | uint64_t val = 1; |
| 72 | rc = write(g_evfd.fd, &val, sizeof(val)); |
| 73 | OSMO_ASSERT(rc == sizeof(val)); |
| 74 | |
| 75 | /* enter osmo_select_main_ctx() once */ |
| 76 | printf("entering osmo_select_main\n"); |
| 77 | osmo_select_main_ctx(1); |
| 78 | |
| 79 | /* the allocation must have happened, and the destructor must have been called |
| 80 | * automatically exactly once */ |
| 81 | OSMO_ASSERT(destructor_called == 1); |
| 82 | |
| 83 | exit(0); |
| 84 | } |