/* * newdel.cpp. * * example of functions for new, delete and global constructors * for gnu c++ for the net yaroze * * 12-7-97 */ #include #include #include // prototypes void * __builtin_new(size_t size); void * __builtin_vec_new(size_t size); void __builtin_vec_delete(void *ptr); void __builtin_delete(void *ptr); extern "C" { // start is located in libps.a void _start(void); void _xxstart(void); } // __CTOR_LIST__ symbol created by linker typedef void (*func_ptr) (void); extern func_ptr __CTOR_LIST__[]; // define a dummy class with a constructor that takes // a parameter to make sure that there is a __CTOR_LIST__ // generated, otherwise you get a linker error from // _xxstart class __always_have_a_non_default_constructor_global { public: __always_have_a_non_default_constructor_global(int g) {x=g;}; int x; }; // here is the global __always_have_a_non_default_constructor_global __always_have_this_global(5); void *__builtin_new(size_t size) { void *ptr; // Apparently malloc (0) can be a bit unpredictable if (size==0) { size = 1; } ptr = (void *)malloc(size); if (ptr==NULL) { printf("new failed - out of heap\n"); } return ptr; } void *__builtin_vec_new(size_t size) { return __builtin_new(size); } void __builtin_delete(void *ptr) { if (ptr!=NULL) { free(ptr); } } void __builtin_vec_delete(void *ptr) { __builtin_delete(ptr); } extern "C" { void _xxstart(void) { unsigned int h; unsigned int nptrs; // on some systems, __CTOR_LIST__[0] contains the number // of pointers to global initialisation functions nptrs=(unsigned int)__CTOR_LIST__[0]; if (nptrs==(unsigned int)-1) { // on others, it is -1 and you see how many // pointers there are because the array is // null terminated nptrs=0; while (__CTOR_LIST__[nptrs+1]!=NULL) { nptrs++; } } // Call the initialisation functions in reverse order (?) for (h=nptrs; h>=1; h--) { __CTOR_LIST__[h](); } // call libps start function - this will call main() _start(); } }