malloc.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
  2. *
  3. * libhostile
  4. *
  5. * Copyright (C) 2011 Data Differential, http://datadifferential.com/
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /*
  22. Random malloc failing library for testing malloc failures.
  23. LD_PRELOAD="/usr/lib/libdl.so ./util/libhostile_malloc.so" ./binary
  24. */
  25. #define _GNU_SOURCE
  26. #include <dlfcn.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <time.h>
  30. #include <errno.h>
  31. #include <libhostile/initialize.h>
  32. static int not_until= 500;
  33. static struct function_st __function;
  34. static pthread_once_t function_lookup_once = PTHREAD_ONCE_INIT;
  35. static void set_malloc(void)
  36. {
  37. __function= set_function("malloc", "HOSTILE_MALLOC");
  38. }
  39. void *malloc(size_t size)
  40. {
  41. hostile_initialize();
  42. (void) pthread_once(&function_lookup_once, set_malloc);
  43. if (__function.frequency)
  44. {
  45. if (--not_until < 0 && random() % __function.frequency)
  46. {
  47. fprintf(stderr, "Mid=evil on malloc()\n");
  48. errno= ENOMEM;
  49. return NULL;
  50. }
  51. }
  52. return __function.function.malloc(size);
  53. }