memalign.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* malloc.c - C standard library routine.
  2. Copyright (c) 1989, 1993 Michael J. Haertel
  3. You may redistribute this library under the terms of the
  4. GNU Library General Public License (version 2 or any later
  5. version) as published by the Free Software Foundation.
  6. THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED
  7. WARRANTY. IN PARTICULAR, THE AUTHOR MAKES NO REPRESENTATION OR
  8. WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY OF THIS
  9. SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. */
  10. #define _GNU_SOURCE
  11. #include <features.h>
  12. #include <limits.h>
  13. #include <stddef.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <unistd.h>
  17. #include "malloc.h"
  18. #ifdef __UCLIBC_HAS_THREADS__
  19. #include <pthread.h>
  20. extern pthread_mutex_t __malloclock;
  21. # define LOCK pthread_mutex_lock(&__malloclock)
  22. # define UNLOCK pthread_mutex_unlock(&__malloclock);
  23. #else
  24. # define LOCK
  25. # define UNLOCK
  26. #endif
  27. __ptr_t memalign (size_t alignment, size_t size)
  28. {
  29. __ptr_t result;
  30. unsigned long int adj;
  31. result = malloc (size + alignment - 1);
  32. if (result == NULL)
  33. return NULL;
  34. adj = (unsigned long int) ((unsigned long int) ((char *) result -
  35. (char *) NULL)) % alignment;
  36. if (adj != 0)
  37. {
  38. struct alignlist *l;
  39. LOCK;
  40. for (l = _aligned_blocks; l != NULL; l = l->next)
  41. if (l->aligned == NULL)
  42. /* This slot is free. Use it. */
  43. break;
  44. if (l == NULL)
  45. {
  46. l = (struct alignlist *) malloc (sizeof (struct alignlist));
  47. if (l == NULL) {
  48. __free_unlocked (result);
  49. UNLOCK;
  50. return NULL;
  51. }
  52. l->next = _aligned_blocks;
  53. _aligned_blocks = l;
  54. }
  55. l->exact = result;
  56. result = l->aligned = (char *) result + alignment - adj;
  57. UNLOCK;
  58. }
  59. return result;
  60. }