Source:NetHack 5.0.0/src/alloc.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to alloc.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/alloc.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	alloc.c	$NHDT-Date: 1737281026 2025/01/19 02:03:46 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.38 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2012. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #define ALLOC_C /* comment line for pre-compiled headers */
7. /* since this file is also used in auxiliary programs, don't include all the
8.    function declarations for all of nethack */
9. #define EXTERN_H /* comment line for pre-compiled headers */
10. 
11. #include "config.h"
12. #ifndef LUA_INTEGER
13. #include "nhlua.h"
14. #endif
15. 
16. 
17. /*#define FITSint(x) FITSint_(x, __func__, __LINE__)*/
18. extern int FITSint_(LUA_INTEGER, const char *, int) NONNULLARG2;
19. /*#define FITSuint(x) FITSuint_(x, __func__, __LINE__)*/
20. extern unsigned FITSuint_(unsigned long long, const char *, int) NONNULLARG2;
21. 
22. char *fmt_ptr(const genericptr) NONNULL;
23. 
24. #ifdef MONITOR_HEAP
25. #undef alloc
26. #undef re_alloc
27. #undef free
28. extern void free(genericptr_t);
29. staticfn void heapmon_init(void);
30. 
31. static FILE *heaplog = 0;
32. static boolean tried_heaplog = FALSE;
33. #endif
34. 
35. /*
36.  * For historical reasons, nethack's alloc() returns 'long *' rather
37.  * than 'void *' or 'char *'.
38.  *
39.  * Some static analysis complains if it can't deduce that the number
40.  * of bytes being allocated is a multiple of 'sizeof (long)'.  It
41.  * recognizes that the following manipulation overcomes that via
42.  * rounding the requested length up to the next long.  NetHack doesn't
43.  * make a lot of tiny allocations, so this shouldn't waste much memory
44.  * regardless of whether malloc() does something similar.  NetHack
45.  * isn't expected to call alloc(0), but if that happens treat it as
46.  * alloc(sizeof (long)) instead.
47.  */
48. #define ForceAlignedLength(LTH) \
49.     do {                                                        \
50.         if (!(LTH) || (LTH) % sizeof (long) != 0)               \
51.             (LTH) += sizeof (long) - (LTH) % sizeof (long);     \
52.     } while (0)
53. 
54. #ifndef MONITOR_HEAP
55. long *alloc(unsigned int) NONNULL;
56. long *re_alloc(long *, unsigned int) NONNULL;
57. #else
58.     /* for #if MONITOR_HEAP, alloc() might return Null but only nhalloc()
59.        should be calling it; nhalloc() never returns Null */
60. long *alloc(unsigned int);
61. long *re_alloc(long *, unsigned int);
62. long *nhalloc(unsigned int, const char *, int) NONNULL;
63. long *nhrealloc(long *, unsigned int, const char *, int) NONNULL;
64. #endif
65. ATTRNORETURN extern void panic(const char *, ...) PRINTF_F(1, 2) NORETURN;
66. 
67. long *
68. alloc(unsigned int lth)
69. {
70.     genericptr_t ptr;
71. 
72.     ForceAlignedLength(lth);
73.     ptr = malloc(lth);
74. #ifndef MONITOR_HEAP
75.     if (!ptr)
76.         panic("Memory allocation failure; cannot get %u bytes", lth);
77. #else
78.     /* for #if MONITOR_HEAP, failure is handled in nhalloc() */
79. #endif
80.     return (long *) ptr;
81. }
82. 
83. /* realloc() call that might get substituted by nhrealloc(p,n,file,line) */
84. long *
85. re_alloc(long *oldptr, unsigned int newlth)
86. {
87.     long *newptr;
88. 
89.     ForceAlignedLength(newlth);
90.     newptr = (long *) realloc((genericptr_t) oldptr, (size_t) newlth);
91. #ifndef MONITOR_HEAP
92.     /* "extend to":  assume it won't ever fail if asked to shrink */
93.     if (newlth && !newptr)
94.         panic("Memory allocation failure; cannot extend to %u bytes", newlth);
95. #else
96.     /* for #if MONITOR_HEAP, failure is handled in nhrealloc() */
97. #endif
98.     return newptr;
99. }
100. 
101. #ifdef HAS_PTR_FMT
102. #define PTR_FMT "%p"
103. #define PTR_TYP genericptr_t
104. #else
105. #define PTR_FMT "%06lx"
106. #define PTR_TYP unsigned long
107. #endif
108. 
109. /* A small pool of static formatting buffers.
110.  * PTRBUFSIZ:  We assume that pointers will be formatted as integers in
111.  * hexadecimal, requiring at least 16+1 characters for each buffer to handle
112.  * 64-bit systems, but the standard doesn't mandate that encoding and an
113.  * implementation could do something different for %p, so we make some
114.  * extra room.
115.  * PTRBUFCNT:  Number of formatted values which can be in use at the same
116.  * time.  To have more, callers need to make copies of them as they go.
117.  */
118. #define PTRBUFCNT 4
119. #define PTRBUFSIZ 32
120. static char ptrbuf[PTRBUFCNT][PTRBUFSIZ];
121. static int ptrbufidx = 0;
122. 
123. /* format a pointer for display purposes; returns a static buffer */
124. char *
125. fmt_ptr(const genericptr ptr)
126. {
127.     char *buf;
128. 
129.     buf = ptrbuf[ptrbufidx];
130.     if (++ptrbufidx >= PTRBUFCNT)
131.         ptrbufidx = 0;
132. 
133.     Sprintf(buf, PTR_FMT, (PTR_TYP) ptr);
134.     return buf;
135. }
136. 
137. #ifdef MONITOR_HEAP
138. 
139. /* If ${NH_HEAPLOG} is defined and we can create a file by that name,
140.    then we'll log the allocation and release information to that file. */
141. staticfn void
142. heapmon_init(void)
143. {
144.     char *logname = getenv("NH_HEAPLOG");
145. 
146.     if (logname && *logname)
147.         heaplog = fopen(logname, "w");
148.     tried_heaplog = TRUE;
149. }
150. 
151. long *
152. nhalloc(unsigned int lth, const char *file, int line)
153. {
154.     long *ptr = alloc(lth);
155. 
156.     if (!tried_heaplog)
157.         heapmon_init();
158.     if (heaplog)
159.         (void) fprintf(heaplog, "+%5u %s %4d %s\n", lth,
160.                        fmt_ptr((genericptr_t) ptr), line, file);
161.     /* potential panic in alloc() was deferred til here */
162.     if (!ptr)
163.         panic("Cannot get %u bytes, line %d of %s", lth, line, file);
164. 
165.     return ptr;
166. }
167. 
168. /* re_alloc() with heap logging; we lack access to the old alloc size  */
169. long *
170. nhrealloc(
171.     long *oldptr,
172.     unsigned int newlth,
173.     const char *file,
174.     int line)
175. {
176.     long *newptr = re_alloc(oldptr, newlth);
177. 
178.     if (!tried_heaplog)
179.         heapmon_init();
180.     if (heaplog) {
181.         char op = '*'; /* assume realloc() will change size of previous
182.                         * allocation rather than make a new one */
183. 
184.         if (newptr != oldptr) {
185.             /* if oldptr wasn't Null, realloc() freed it */
186.             if (oldptr)
187.                 (void) fprintf(heaplog, "%c%5s %s %4d %s\n", '<', "",
188.                                fmt_ptr((genericptr_t) oldptr), line, file);
189.             op = '>'; /* new allocation rather than size-change of old one */
190.         }
191.         (void) fprintf(heaplog, "%c%5u %s %4d %s\n", op, newlth,
192.                            fmt_ptr((genericptr_t) newptr), line, file);
193.     }
194.     /* potential panic in re_alloc() was deferred til here;
195.        "extend to":  assume it won't ever fail if asked to shrink;
196.        even if that assumption happens to be wrong, we lack access to
197.        the old size so can't use alternate phrasing for that case */
198.     if (newlth && !newptr)
199.         panic("Cannot extend to %u bytes, line %d of %s", newlth, line, file);
200. 
201.     return newptr;
202. }
203. 
204. void
205. nhfree(genericptr_t ptr, const char *file, int line)
206. {
207.     if (!tried_heaplog)
208.         heapmon_init();
209.     if (heaplog)
210.         (void) fprintf(heaplog, "-      %s %4d %s\n",
211.                        fmt_ptr((genericptr_t) ptr), line, file);
212. 
213.     free(ptr);
214. }
215. 
216. /* strdup() which uses our alloc() rather than libc's malloc(),
217.    with caller tracking */
218. char *
219. nhdupstr(const char *string, const char *file, int line)
220. {
221.     /* we've got some info about the caller, so use it instead of __func__ */
222.     unsigned len = FITSuint_(strlen(string), file, line);
223. 
224.     if (FITSuint_(len + 1, file, line) < len)
225.         panic("nhdupstr: string length overflow, line %d of %s",
226.               line, file);
227. 
228.     return strcpy((char *) nhalloc(len + 1, file, line), string);
229. }
230. #undef dupstr
231. 
232. #endif /* MONITOR_HEAP */
233. 
234. /* strdup() which uses our alloc() rather than libc's malloc();
235.    not used when MONITOR_HEAP is enabled, but included unconditionally
236.    in case utility programs get built using a different setting for that */
237. char *
238. dupstr(const char *string)
239. {
240.     size_t len = strlen(string);
241. 
242.     /* make sure len+1 doesn't overflow plain unsigned (for alloc()) */
243.     if (len > (unsigned) (~0U - 1U))
244.         panic("dupstr: string length overflow");
245. 
246.     return strcpy((char *) alloc(len + 1), string);
247. }
248. 
249. #if 0   /* suppress this; if included, it will need a MONITOR_HEAP edition */
250. 
251. /* similar for reasonable size strings, but return length of input as well */
252. char *
253. dupstr_n(const char *string, unsigned int *lenout)
254. {
255.     size_t len = strlen(string);
256. 
257.     if (len >= LARGEST_INT)
258.         panic("dupstr_n: string too long");
259.     *lenout = (unsigned int) len;
260.     return strcpy((char *) alloc(len + 1), string);
261. }
262. #endif
263. 
264. /* cast to int or panic on overflow; use via macro */
265. int
266. FITSint_(LUA_INTEGER i, const char *file, int line)
267. {
268.     int iret = (int) i;
269. 
270.     if (iret != i)
271.         panic("Overflow at %s:%d", file, line);
272.     return iret;
273. }
274. 
275. unsigned
276. FITSuint_(unsigned long long ull, const char *file, int line)
277. {
278.     unsigned uret = (unsigned) ull;
279. 
280.     if (uret != ull)
281.         panic("Overflow at %s:%d", file, line);
282.     return uret;
283. }
284. 
285. /*alloc.c*/