home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume18 / malloc-trace < prev    next >
Encoding:
Internet Message Format  |  1989-03-26  |  67.5 KB

  1. Subject:  v18i066:  Malloc package with tracing
  2. Newsgroups: comp.sources.unix
  3. Sender: sources
  4. Approved: rsalz@uunet.UU.NET
  5.  
  6. Submitted-by: Mark Brader <msb@sq.sq.com>
  7. Posting-number: Volume 18, Issue 66
  8. Archive-name: malloctrace
  9.  
  10. This package has been put together from a number of different pieces and
  11. I don't have time to edit all the README files together nicely.  Most of
  12. them are just cover notes that came with the different parts.  I believe
  13. all code except my own to have previously been posted to the net and
  14. to be in the public domain.  My code is also in the public domain.
  15.  
  16. What this is is a malloc package with tracing, so you can find where in
  17. your program there is a call to malloc() without a matching free().
  18.  
  19. The malloc part is portable, the tracing will need work to run on
  20. anything other than Sun's.
  21.  
  22. : To unbundle, sh this file
  23. echo x - OVERALL_README 1>&2
  24. cat >OVERALL_README <<'@@@End of OVERALL_README'
  25. This package has been put together from a number of different pieces and
  26. I don't have time to edit all the README files together nicely.  Most of
  27. them are just cover notes that came with the different parts.  I believe
  28. all code except my own to have previously been posted to the net and
  29. to be in the public domain.  My code is also in the public domain.
  30.  
  31. What this is is a malloc package with tracing, so you can find where in
  32. your program there is a call to malloc() without a matching free().
  33.  
  34. This package is written in several separate source files so that a program
  35. won't have to load all of it if it doesn't need it.  However, there may be
  36. cases where a function in the C runtime library calls a malloc() family
  37. function that your program doesn't call, and it will then go to the system
  38. version of the malloc() package for that function.  This causes chaos.
  39.  
  40. You can force a particular function to be loaded from the malloctrace.a
  41. library by putting, e.g., "-u _calloc" on the compile line just before
  42. the library name.  Or you could avoid the problem permanently by editing
  43. the files malloc.h, malloc.c, free.c, calloc.c, init_trace.c, write_trace.c,
  44. and forget.c into one big file.
  45.  
  46. The original malloc package was written by Bill Sebok.  I then added the
  47. tracing, while Arthur David Olson, independently, added some bug fixes
  48. and enhancements.   I then took Olson's version and added my tracing to it.
  49.  
  50. For more details on the tracing see mallck.1 and TRACE_README in this
  51. directory.  README is Sebok's original README.  NEW_VERSION_README is
  52. Olson's cover note.  README.mtest2 and README.mtest3 are cover notes
  53. for two malloc-tester programs (originally called mtest and looptest).
  54. (mtest1, included here without its own README file, is part of Sebok's
  55. package and was originally called tstmalloc).
  56.  
  57. UNPORTABILITY CAVEATS -
  58.  
  59.   The tracing depends on being able to dump one's call stack.  This is
  60. done by code in the file write_trace.c.  It works on our Sun running SunOS
  61. 3.0 or 3.2, but is likely to need rewriting on your machine!
  62.   There are two other things that work on our Sun but aren't portable:
  63. the types "char *", "long", and "unsigned" seem to be inter-assigned
  64. carelessly (I don't have time to delint this, either); and the BSDish
  65. library function bcopy() is used.
  66.   Use at your own risk.
  67.  
  68. Mark Brader, SoftQuad Inc., Toronto, August 25, 1988
  69. { uunet!attcan | linus | decvax | watmath | pyramid } !utzoo!sq!msb
  70. msb@sq.com        decwrl!utcsri!sq!msb
  71. @@@End of OVERALL_README
  72. echo x - README 1>&2
  73. cat >README <<'@@@End of README'
  74. This is the malloc()/free()/realloc()/forget() package used at astrovax.
  75. [Except for the MALLOCTRACE feature -- see ./TRACE_README]
  76.  
  77. It does not have the property of the 4.2 BSD malloc of allocating huge amounts
  78. of excess memory.  Image processing is done here and large malloc requests
  79. are not rare.  It is quite undesirable when one asks for 4.1 megabytes of memory
  80. to have it try to return 8 megabytes and to fail because the process goes over
  81. quota or there is not enough swap space.
  82.  
  83. Also this malloc does not have the property of the 4.1 BSD malloc that a search
  84. for free memory traverses a linked list that covers all previous allocations,
  85. causing thrashing by touching them and thus paging them back into memory.
  86.  
  87. Hopefully this malloc covers the best of both worlds.  There is a fair attempt
  88. at storage compaction, merging freed areas with adjacent free areas and
  89. optionally returning freed areas adjacent to the break back to the system,
  90. thereby shrinking the size of the process.
  91.  
  92. It is also allowable and compatible with this package to obtain memory by the
  93. use of the sbrk() system call.  This memory can be reclaimed and returned to
  94. the malloc arena by the use of the provided forget() function.  This function
  95. is intended to provide the functionality of the Forth FORGET primitive in
  96. an environment that also includes malloc and free.
  97.  
  98. The main disadvantage of this package is a larger storage overhead of 24 bytes
  99. per memory area, due to the fact that each area is linked into two
  100. bi-directional chains.
  101.  
  102. Non-vax users should edit the commented system-dependent parts of Makefile and
  103. malloc.h for the requirements of one's own computer.
  104.  
  105. Bill Sebok            Princeton University, Astrophysics
  106. {allegra,akgua,cbosgd,decvax,ihnp4,noao,philabs,princeton,vax135}!astrovax!wls
  107. @@@End of README
  108. echo x - TRACE_README 1>&2
  109. cat >TRACE_README <<'@@@End of TRACE_README'
  110. The files malloc.c, free.c, realloc.c, and malloc.h have been edited,
  111. and the new files write_trace.c and init_trace.c have been created,
  112. to implement the tracing of calls to malloc, free, and realloc.
  113.  
  114. [WARNING: The implementation is system-dependent.  It works on our SunOS 3.2.]
  115.  
  116. The method is based on that described in the paper:
  117.  
  118.     "A Technique for Finding Storage Allocation Errors in
  119.      C-language Programs", David R. Barach, David H. Taenzer,
  120.      and Robert E. Wells; SIGPLAN Notices, V17#5 (May 1982).
  121.  
  122. All these changes and the associated new files are public domain,
  123. and are not guaranteed.
  124.  
  125. Basically, the functions free and malloc are modified by inserting
  126. calls to the new functions init_trace and write_trace.  Init_trace
  127. is called the first time malloc is called; it opens the output file
  128. named by the environment variable $MALLOCTRACE, or "malloc.out" by
  129. default.  Each call to write_trace then writes to that trace file
  130. a one-line description of the current event, e.g. "malloc of 256 at 5a10a".
  131. It follows this by a traceback of the calling stack with one line for
  132. each stack frame, e.g. "caller 0000210f", and an empty line.
  133.  
  134. The possible events are "malloc" and "realloc-to" to allocate memory,
  135. "free" and "realloc" to free memory.  A call to realloc generates
  136. both a "realloc" and a "realloc-to".
  137.  
  138. The variable _malstate provides interlocking so that when realloc
  139. calls malloc or free, which it sometimes does, an additional tracing
  140. line will not be generated, and so that no tracing will be generated
  141. before initialization is complete or if the trace file cannot be opened.
  142.  
  143. The associated shell script "prleak", containing three awk programs, 
  144. reads the $MALLOCTRACE or "malloc.out" (or other specified) file, and
  145. does an "nm" on the program supposed to have generated it ("a.out"
  146. by default).  It scans these outputs and produces a report of the
  147. high water level of allocated data (excluding that from stdio, as far
  148. as possible), the total amount of data remaining allocated at termin-
  149. ation, and the tracebacks of all calls that left data allocated at
  150. termination or that resulted in any error (including nonfatal ones
  151. such as frees of unallocated data).  The tracebacks give entries in
  152. forms such as "called from  5a9b [ _getframe + 42]", where 5a9b is in
  153. hexadecimal and 42 in decimal.
  154.  
  155.                         Mark Brader
  156.                         SoftQuad Inc.
  157.                         January 1987
  158. @@@End of TRACE_README
  159. echo x - NEW_VERSION_README 1>&2
  160. cat >NEW_VERSION_README <<'@@@End of NEW_VERSION_README'
  161. >From utai!uunet!ncifcrf.gov!elsie!ado Mon Aug  1 02:37:08 1988
  162. Received: by sq.sq.com id 21060; Mon, 1 Aug 88 02:36:59 EDT
  163. From:    ncifcrf.gov!elsie!ado
  164. Received: from fcs280s.ncifcrf.gov by a.cs.uiuc.edu with SMTP (UIUC-5.52/9.7)
  165.     id AA09603; Sun, 31 Jul 88 13:13:31 CDT
  166. Received: by fcs280s.ncifcrf.gov (4.0/NCIFCRF-1.0)
  167.     id AA05293; Sun, 31 Jul 88 14:15:06 EDT
  168. Received: by elsie.UUCP (5.51/4.7)
  169.     id AA15980; Sun, 31 Jul 88 14:11:42 EDT
  170. Date:    Sun, 31 Jul 88 12:51:42 EDT
  171. From:    ncifcrf.gov!elsie!ado (Arthur David Olson)
  172. Message-Id: <8807311811.AA15980@elsie.UUCP>
  173. To:    msb@sq.com
  174. Subject: Re:  Bug in Bill Sebok's malloc() package
  175. Status: RO
  176.  
  177. I get the right output from your sample code with the version of malloc we're
  178. using here at elsie; our version (Bill's with bug fixes) is attached.
  179.  
  180.                 --ado
  181.  
  182. @@@End of NEW_VERSION_README
  183. echo x - README.mtest2 1>&2
  184. cat >README.mtest2 <<'@@@End of README.mtest2'
  185. Article 1077 of net.sources:
  186. Path: sq!utfyzx!utgpu!water!watnot!watmath!clyde!rutgers!husc6!necntc!encore!vaxine!nw
  187. From: nw@vaxine.UUCP (Neil Webber)
  188. Newsgroups: net.sources
  189. Subject: malloc/free test program
  190. Message-ID: <417@vaxine.UUCP>
  191. Date: 16 Feb 87 20:49:49 GMT
  192. Organization: Automatix, Inc., Billerica, MA
  193. Lines: 460
  194.  
  195. A while back I asked the net if anyone had a malloc/free test program that
  196. would allocate and free randomly sized pieces of memory with random lifetimes
  197. (and fill them with patterns that would be checked for corruption).  I got
  198. a number of useful suggestions (best one: use the "diff" program as a
  199. malloc test ... it's brutal).  Eventually, I wound up writing my own
  200. test program, which actually helped me find a bug.
  201.  
  202. On the assumption that it might be useful to someone else, here it is.
  203. Please note:
  204.  
  205.         - No documentation (read the code to find out what it does).
  206.         - Could be extended in zillions of ways to make it more useful.
  207.         - No makefile, just compile "cc mtest.c"
  208.  
  209. A "shar" archive follows.
  210.  
  211. Neil Webber     Automatix Inc. (or current resident)    Billerica MA
  212.         {decvax,ihnp4,allegra}!encore!vaxine!nw
  213.  
  214. @@@End of README.mtest2
  215. echo x - README.mtest3 1>&2
  216. cat >README.mtest3 <<'@@@End of README.mtest3'
  217. Article 1086 of net.sources:
  218. Path: sq!utfyzx!utgpu!water!watnot!watmath!clyde!rutgers!lll-lcc!ptsfa!amdahl!rtech!daveb
  219. From: daveb@rtech.UUCP (Dave Brower)
  220. Newsgroups: net.sources
  221. Subject: Another allocator tester
  222. Message-ID: <665@rtech.UUCP>
  223. Date: 17 Feb 87 19:00:13 GMT
  224. References: <417@vaxine.UUCP>
  225. Organization: Relational Technology, Alameda CA
  226. Lines: 204
  227.  
  228. > A while back I asked the net if anyone had a malloc/free test program that 
  229. > would allocate and free randomly sized pieces of memory with random
  230. > lifetimes... [ and one follows ]
  231.  
  232. Here is a program I've been using recently.  It is a lot more intensive
  233. than Neil Webber's, and shows you what the process size is doing.  I am
  234. usually comfortable when I can run an allocator through 10 million or so
  235. loops with out a problem.
  236.  
  237. A useful addition would be computation of kilo-core-seconds.
  238.  
  239. As usual, no documentation and best wishes.
  240.  
  241. -dB
  242.  
  243. ---------------- cut here ----------------
  244. @@@End of README.mtest3
  245. echo x - mallck.1 1>&2
  246. cat >mallck.1 <<'@@@End of mallck.1'
  247. .TH MALLCK 1 "25 August 1988"
  248. .ds li /usr/lib/malloctrace.a
  249. .SH NAME
  250. mallck \- check memory allocation and deallocation calls
  251. .SH SYNOPSIS
  252. .B mallck
  253. [ program ] [ tracefile ]
  254. .SH DESCRIPTION
  255. .IX  mallck  ""  "\fLmallck\fP \(em check memory allocation and deallocation calls
  256. .I Mallck
  257. is used in conjunction with the library
  258. .IR \*(li .
  259. .PP
  260. If a program is linked with that library (as the last library searched),
  261. then when it is run, it will create a trace file of all the calls to
  262. .IR malloc ,
  263. .IR realloc ", and
  264. .IR free .
  265. The name of the trace file is taken from the environment variable
  266. \s-2MALLOCTRACE\s+2, or if that is undefined, defaults to
  267. .IR malloc.out .
  268. Output to the file is flushed after each entry unless the environment variable
  269. \s-2MALLOCTRACEBUF\s+2 is nonnull.
  270. .PP
  271. .I Mallck
  272. is used to scan this file and look for calls that do not pair up\(emeither
  273. .IR malloc s
  274. without
  275. .IR free s,
  276. or vice versa, or calls where the amount freed (taken from the
  277. internal information that
  278. .I free
  279. uses) does not correspond to the amount allocated.
  280. .I Mallck
  281. also reports the high-water mark of
  282. memory that it knows (see Bugs section) to have been allocated.
  283. .PP
  284. .I Mallck
  285. also examines the symbol table of the program, to format the tracebacks
  286. usefully.
  287. Its first argument
  288. .I program
  289. should be either the executable program, not stripped, or the output
  290. from running
  291. .I nm
  292. on the executable program.
  293. (Only the `T' entries are examined and their sequence does not matter, so
  294. .IR "nm -gp" "'s
  295. output would suffice.)
  296. If no arguments are given,
  297. .I a.out
  298. is used for
  299. .IR program .
  300. .PP
  301. The second argument
  302. .I malloctrace
  303. is the trace file described above.
  304. If omitted, the same defaults apply as above.
  305. .SH AUTHOR
  306. Mark Brader, SoftQuad Inc., 1987-88.
  307. .PP
  308. Based on the paper
  309. .I "A Technique for Finding Storage Allocation Errors in C-language Programs
  310. by David R. Barach, David H. Taenzer, and Robert E. Wells, in
  311. .IR "SIGPLAN Notices" ,
  312. .BR 17 ,
  313. 5 (May 1982).
  314. .PP
  315. The
  316. .I malloc
  317. family functions to which the tracing was added to create
  318. .I \*(li
  319. were the public-domain ones by Bill Sebok, then of Princeton University,
  320. with modifications by Arthur David Olson of the National Institutes of Health.
  321. .SH DIAGNOSTICS
  322. Self-explanatory, as they say.
  323. Since memory being allocated but never freed may be a harmless
  324. situation, it is reported in lower case, while other messages
  325. are more emphatic.
  326. .SH SEE ALSO
  327. nm(1), malloc(3)
  328. .SH FILES
  329. a.out
  330. .br
  331. malloc.out
  332. .br
  333. \*(li
  334. .SH BUGS
  335. There is no way to verify that the trace
  336. file did in fact come from the program
  337. .IR program ;
  338. nonsensical tracebacks are the only hint.
  339. Even if the program is the correct one, functions declared static are
  340. not seen by
  341. .I nm
  342. and thus tracebacks from calls in such functions will be misleading.
  343. .PP
  344. Due to interactions between
  345. .I stdio
  346. and the traced
  347. .I malloc
  348. family, programs may be unstable as to whether they report the
  349. calls to the
  350. .I malloc
  351. family that
  352. .I stdio
  353. functions may make.
  354. Thus
  355. .I stdio
  356. buffers may be counted in the high-water mark or not, depending only
  357. on what input the program received.
  358. The first
  359. .I stdio
  360. buffer is never reported.
  361. .PP
  362. Calls to
  363. .I realloc
  364. are treated internally as successive calls to two functions,
  365. .I realloc
  366. and 
  367. .I realloc-to
  368. (equivalent to
  369. .I free
  370. and
  371. .IR malloc ),
  372. and are so referred to in the output report.
  373. .PP
  374. The sizes reported in ``never freed'' messages
  375. exclude the overhead added by the
  376. .I malloc
  377. family functions, even though the allocation statistics do report it.
  378. (This is because the overhead may differ slightly on otherwise identical calls,
  379. and if this is ignored, their reports can be combined.)
  380. .PP
  381. The code in
  382. .I \*(li
  383. that produces the calling stack traceback was written
  384. without the aid of documentation on the Sun's stack format.
  385. Since it depends on the stack format, it is not portable.
  386. .PP
  387. The format of the trace file is somewhat verbose and it can rapidly
  388. consume large amounts of disk space.
  389. A pipe cannot be used because
  390. .I mallck
  391. reads the trace file twice.
  392. .SH NOTES
  393. .I Mallck
  394. is a shell script consisting principally of 3 invocations of
  395. .IR awk ,
  396. 3 of
  397. .IR sort ,
  398. and one each of
  399. .IR sed ,
  400. .IR grep ", and
  401. .IR nm .
  402. @@@End of mallck.1
  403. echo x - malloc.3 1>&2
  404. cat >malloc.3 <<'@@@End of malloc.3'
  405. .TH MALLOC 3  "30 June 1986"
  406. .SH NAME
  407. malloc, free, realloc \- memory allocator
  408. .SH SYNOPSIS
  409. .nf
  410. .B char *malloc(size)
  411. .B Size size;
  412. .PP
  413. .B void free(ptr)
  414. .B char *ptr;
  415. .PP
  416. .B char *realloc(ptr, size)
  417. .B char *ptr;
  418. .B Size size;
  419. .PP
  420. .B extern char endfree
  421. .PP
  422. .B extern void (*mlabort)()
  423. .fi
  424. .PP
  425. Where
  426. .I Size
  427. is an integer large enough to hold a char pointer.
  428. .SH DESCRIPTION
  429. .I Malloc
  430. and
  431. .I free
  432. provide a simple general-purpose memory allocation package.
  433. .I Malloc
  434. returns a pointer to a block of at least
  435. .I size
  436. bytes beginning on the boundary of the most stringent alignment required
  437. by the architecture.
  438. .PP
  439. The argument to
  440. .I free
  441. is a pointer to a block previously allocated by
  442. .IR malloc ;
  443. this space is made available for further allocation,
  444. but its contents are left undisturbed.
  445. .PP
  446. Needless to say, grave disorder will result if the space assigned by
  447. .I malloc
  448. is overrun or if some random number is handed to
  449. .IR free .
  450. .PP
  451. .I Malloc
  452. maintains multiple lists of free blocks according to size,
  453. allocating space from the appropriate list.
  454. It calls
  455. .I brk
  456. (see
  457. .IR brk (2))
  458. to get more memory from the system when there is no
  459. suitable space already free.
  460. .PP
  461. .I Free
  462. makes an attempt to merge newly freed memory with adjacent free areas.
  463. If the result of this merging is an area that touches the system break
  464. (the current location of the highest valid address of the data segment of the
  465. process) and if
  466. .I
  467. endfree
  468. has a non-zero value,  then break is moved back, contracting the process
  469. size and releasing the memory back to the system.
  470. .PP
  471. By default
  472. .I endfree
  473. has a value of 0, which disables the release of memory back to the system.
  474. .PP
  475. It is valid to also allocate memory by the use of
  476. .I sbrk(3)
  477. or by moving up the break with
  478. .I brk(3).
  479. This memory may be reclaimed and returned to
  480. the \fImalloc\fP/\fIfree\fP arena by the use of
  481. .I forget
  482. (see \fIforget\fP(3)).
  483. .PP
  484. .I Realloc
  485. changes the size of the block pointed to by
  486. .I ptr
  487. to
  488. .I size
  489. bytes and returns a pointer to the (possibly moved) block.
  490. The contents will be unchanged up to the lesser of the new and old sizes.
  491. .PP
  492. In order to be compatible with older versions,
  493. if
  494. .I endfree
  495. is 0, then
  496. .I realloc
  497. also works if
  498. .I ptr
  499. points to a block freed since the last call of
  500. .I malloc
  501. or
  502. .I realloc.
  503. Sequences of
  504. .I free, malloc
  505. and
  506. .I realloc
  507. were previously used to attempt storage compaction.
  508. This procedure is no longer recommended.
  509. In this implementation
  510. .I Realloc,
  511. .I malloc
  512. and
  513. .I free
  514. do a fair amount of their own storage compaction anyway.
  515. .SH DIAGNOSTICS
  516. .I Malloc, realloc
  517. return a null pointer (0) if there is no available memory or if the arena
  518. has been detectably corrupted by storing outside the bounds of a block.
  519. .I Realloc
  520. makes an attempt to detect and return a null pointer when the break has been
  521. moved so that the requested address is no longer valid.
  522. .I Malloc
  523. may be recompiled to check the arena very stringently on every transaction;
  524. those sites with a source code license may do this by recompiling the source
  525. with  -Ddebug .
  526. .PP
  527. On detection of corruption of the malloc arena the normal response is an
  528. abort with a core dump.  This response can be changed by placing a pointer to
  529. a function with the desired response into the extern pointer
  530. .I mlabort.
  531. .SH ALGORITHM
  532. .I Malloc
  533. returns a block of size equal to the size requested plus an overhead (24
  534. bytes for a 32 bit machine).
  535. Freed memory is linked into a chain selected by the size of the freed area
  536. (currently, memory size of items in a chain is between two adjacent powers of
  537. 2).
  538. The search for memory starts with the chain whose length index is at least
  539. equal to the size of the request and proceeds if unsuccessful to larger
  540. memory size chains.  If there is any surplus memory left after the filling
  541. of a request it is returned to the appropriate free list chain.
  542. .SH BUGS
  543. When
  544. .I realloc
  545. returns 0, the block pointed to by
  546. .I ptr
  547. may have been destroyed.
  548. @@@End of malloc.3
  549. echo x - forget.3 1>&2
  550. cat >forget.3 <<'@@@End of forget.3'
  551. .TH FORGET 3  "30 June 1986"
  552. .SH NAME
  553. forget \- reclaim sbrk'ed memory into malloc arena
  554. .SH SYNOPSIS
  555. .nf
  556. .B void forget(ptr)
  557. .B char *ptr;
  558. .PP
  559. .B extern char endfree
  560. .SH DESCRIPTION
  561. .I Forget
  562. provides a way of reclaiming memory obtained by
  563. .I sbrk(3)
  564. and returning it to the malloc arena.  All such memory above
  565. .I ptr
  566. (the "forget point") is marked free and merged if possible with adjacent
  567. free areas.  If
  568. .I endfree
  569. is non-zero any such memory adjacent to the "break" (the highest valid
  570. data address for the process) is released to the system by moving back
  571. the break.
  572. .PP
  573. This function was written to provide the functionality of the Forth
  574. FORGET primitive in an environment where
  575. a dictionary is grown by
  576. .I sbrk
  577. and
  578. .I malloc
  579. and
  580. .I free
  581. are also present.
  582. .SH BUGS
  583. When the specified forget point is below the initial end of the program,
  584. disaster can result.
  585. @@@End of forget.3
  586. echo x - mallck 1>&2
  587. cat >mallck <<'@@@End of mallck'
  588. #
  589. # mallck
  590. # Mark Brader, SoftQuad Inc., 1987
  591. #
  592. # NOT copyright by SoftQuad.  - msb, 1988
  593. #
  594. # sccsid @(#)mallck    1.4 88/08/24
  595. #
  596. # Checks a malloc trace file as produced by modified forms of malloc,
  597. # free, and realloc -- locally in /usr/lib/malloctrace.a -- for any
  598. # incorrectly paired allocations and frees, and any other problems.
  599. # Also computes a few statistics from the data.
  600. #
  601. # Usage:
  602. #    mallck [a.out] [${MALLOCTRACE-malloc.out}]
  603. # or
  604. #    mallck nm.out  [${MALLOCTRACE-malloc.out}]
  605. #
  606. # Both arguments optional, defaults as indicated.  nm.out is the result of
  607. # running nm on the program; only the T lines are significant.
  608. #
  609.  
  610. # The contents of the malloc trace file look like this:
  611. #
  612. #    malloc of 71 gets 104 at 143692
  613. #    caller 000020e8
  614. #    caller 0000204c
  615. #    
  616. #    free of 44 at 143500
  617. #    caller 000020f8
  618. #    caller 0000204c
  619. #    
  620.  
  621. # First, three awk programs.  Unfortunately, while it's most convenient
  622. # to put them in sh variables, it runs sh near its limits, so we use sed
  623. # to pack the programs a bit first...
  624.  
  625.  
  626. # Look up locations in symbol table.  This program reads the "caller"
  627. # entries in the malloc trace file, and the output of nm, and produces
  628. # output of this form:
  629. #
  630. #    0000204c     204c start 44
  631. #    000020b8     20b8 _main 24
  632. #    000020c8     20c8 _main 40
  633. #    000020d8     20d8 _main 56
  634.  
  635. SYMTAB=`sed -e "s/    //" -e "s/ *#.*//" <<'Eot'
  636. BEGIN {
  637.     digit["a"] = 10        # Hex into decimal without scanf
  638.     digit["b"] = 11
  639.     digit["c"] = 12
  640.     digit["d"] = 13
  641.     digit["e"] = 14
  642.     digit["f"] = 15
  643.     for (i = 0; i <= 9; ++i) digit[i] = i
  644.     func = "0"
  645.     funaddr = 0
  646. }
  647. /./ {
  648.     addr = 0
  649.     for (i = 1; i <= 8; ++i) addr = 16*addr + digit[substr($1,i,1)]
  650.     if (addr + 1 == addr) {
  651.         printf " --- **** WARNING: conversion of hex %s to decimal" \
  652.             " %d may be inaccurate!\n", $1, addr
  653.             # Single precision floating point!
  654.     }
  655.     if ($2 == "T") {
  656.         func = $3
  657.         funaddr = addr
  658.     } else \
  659.         printf "%8.8x %8x %s %d\n", addr, addr, func, addr - funaddr
  660. }
  661. Eot
  662. `
  663.  
  664. # Examine calls to malloc et al, and locate any problems.
  665. # This program reads the malloc trace file again, and produces output of
  666. # the following form, which is then sorted and filtered through uniq -c.
  667. # The part before the "---" is a complete call stack traceback.
  668. # There are also summary lines.
  669. #
  670. #     00002110 0000204c --- malloc - size 21 - never freed
  671. #     00002124 0000204c --- realloc-to - size 21 - never freed
  672. #
  673. # The sizes shown are the requested sizes, not the actual ones including
  674. # overhead.  This is so that duplicate entries can be reduced accurately
  675. # by uniq -c.  However, when errors are reported, actual sizes are shown too.
  676. #
  677.  
  678. FIND=`sed -e "s/    //" -e "s/ *#.*//" <<'Eot'
  679. BEGIN {
  680.         # So null input is harmless ...
  681.     alact[""] = totalloc = maxalloc = maxloc = 0
  682.  
  683.         # for waking up recipients of important errors
  684.     bang = " *****************"
  685. }
  686.  
  687. /of/ {
  688.     act = $1
  689.     reqsize = $3
  690.     caller = ""
  691.     if ($4 == "gets") {
  692.         gotsize = $5
  693.         loc = $7
  694.     } else {
  695.         gotsize = reqsize
  696.         loc = $5
  697.     }
  698. }
  699.  
  700. /caller/ {
  701.     caller = caller " " $2        # concatenate traceback together
  702. }
  703.  
  704. /^$/ {
  705.     if (act == "malloc" || act == "realloc-to") {
  706.  
  707.         if (loc == 0) {
  708.             printf "%s --- %s - size %s - ALLOCATION FAILED%s\n", \
  709.                 caller, act, reqsize, bang
  710.  
  711.         } else {
  712.                 # just take note for later reference
  713.             alcall[loc] = caller
  714.             alreq [loc] = reqsize
  715.             algot [loc] = gotsize
  716.             alact [loc] = act
  717.             totreq += reqsize
  718.             totgot += gotsize
  719.             if (maxreq < totreq) maxreq = totreq
  720.             if (maxgot < totgot) maxgot = totgot
  721.             if (maxloc < gotsize + loc) maxloc = gotsize + loc
  722.         }
  723.  
  724.     } else {
  725.                 # Must be free or realloc - check the data
  726.  
  727.         if (alact[loc]) {
  728.             if (algot[loc] != gotsize) {
  729.                 printf "%s --- %s - size %s - actual %s -" \
  730.                     " WRONG SIZE LATER FREED%s\n", \
  731.                     alcall[loc], alact[loc], alreq[loc], \
  732.                     algot[loc], bang
  733.                 printf "%s --- %s - size %s -" \
  734.                     " ACTUAL ALLOCATED SIZE WAS %s%s\n", \
  735.                     caller, act, gotsize, algot[loc], bang
  736.             }
  737.             alact[loc] = ""
  738.             totgot -= gotsize
  739.             totreq -= alreq[loc]
  740.  
  741.         } else {
  742.             printf "%s --- %s - size %s - UNALLOCATED%s\n", \
  743.                 caller, act, gotsize, bang
  744.         }
  745.     }
  746. }
  747.  
  748. END {
  749.                 # check for never-freed space
  750.     for (loc in alact)
  751.         if (alact[loc])
  752.             printf "%s --- %s - size %s -" \
  753.                 " never freed\n", \
  754.                 alcall[loc], alact[loc], alreq[loc]
  755.  
  756.         # The following statistics will print at the top of the
  757.         # final output, by a little trickery -- their beginnings
  758.         # are chosen to sort before the other records (and to
  759.         # leave them in the desired order after sorting)
  760.  
  761.     print " --- ****** ALLOCATION STATISTICS (excluding most stdio)"
  762.     printf " --- ****** Greatest allocated address: %d (hex %x)\n", \
  763.             maxloc - 1, maxloc - 1
  764.     print " --- ****** High-water allocation level: " \
  765.             maxreq " bytes (+ " maxgot-maxreq " overhead)"
  766.     print " --- ****** Total of memory never freed: " \
  767.             totreq " bytes (+ " totgot-totreq " overhead)"
  768. }
  769. Eot
  770. `
  771.  
  772. # Format the output of the 2nd awk program using the output
  773. # of the 1st to display symbolic locations
  774.  
  775. REPORT=`sed -e "s/    //" -e "s/ *#.*//" <<'Eot'
  776.  
  777. ! / --- / {
  778.     func[$1] = $3
  779.     offs[$1] = $4
  780.     nozeros[$1] = $2
  781.     if (maxlen < length($3)) maxlen = length($3)
  782.     if (maxdig < length($4)) maxdig = length($4)
  783. }
  784.  
  785. / --- / {
  786.     for (punct = 1; $punct != "---"; ++punct) {;} # Where in line is "---"?
  787.  
  788.     if (punct > 2) printf "\n\n"
  789.     if ($1 > 1) printf "occurring %d times - ", $1    # Bless uniq -c!
  790.  
  791.     for (i = punct + 1; i <= NF; ++i) printf "%s ", $i
  792.     printf "\n"
  793.  
  794.     if (punct > 2) {
  795.         for (i = 2; i < punct; ++i) {
  796.             if (i == 2) printf "\n\tcalled"; else printf "\t"
  797.             printf "\tfrom %8s [%" maxlen "s + %" maxdig "d]\n", \
  798.                 nozeros[$i], func[$i], offs[$i]
  799.         }
  800.     }
  801. }
  802.  
  803. Eot
  804. `
  805.  
  806. # Default arguments:
  807.  
  808. BIN=${1-a.out}
  809. TRACE=${2-${MALLOCTRACE-malloc.out}}
  810.  
  811. # And do it...
  812.  
  813. (
  814.     (
  815.         (sed -n '/caller /s///p' $TRACE || exit) \
  816.             | sort -u
  817.         (nm -gp $BIN 2>/dev/null || cat $BIN) \
  818.             | grep ' T '
  819.     ) \
  820.         | sort | awk "$SYMTAB"
  821.     awk "$FIND" $TRACE | sort | uniq -c
  822. ) \
  823. | awk "$REPORT"
  824. @@@End of mallck
  825. echo chmod +x mallck
  826. chmod +x mallck
  827. echo x - calloc.c 1>&2
  828. cat >calloc.c <<'@@@End of calloc.c'
  829. #include "malloc.h"
  830. #define NULL 0
  831.  
  832.  
  833. /* NOT copyright by SoftQuad. - msb, 1988 */
  834. #ifndef lint
  835. static char *SQ_SccsId = "@(#)calloc.c    1.2 88/08/24";
  836. #endif
  837. /*
  838. ** And added by ado. . .
  839. */
  840.  
  841. char *
  842. calloc(n, s)
  843. unsigned    n;
  844. unsigned    s;
  845. {
  846.     unsigned    cnt;
  847.     char *        cp;
  848.  
  849.     cnt = n * s;
  850.     cp = malloc(cnt);
  851.     if (cp != NULL)
  852.         bzero(cp, (int) cnt);
  853.     return cp;
  854. }
  855.  
  856. void
  857. cfree(mem)
  858. char *    mem;
  859. {
  860.     free(mem);
  861. }
  862.  
  863. @@@End of calloc.c
  864. echo x - forget.c 1>&2
  865. cat >forget.c <<'@@@End of forget.c'
  866. #include "malloc.h"
  867. #define NULL 0
  868.  
  869. /* NOT copyright by SoftQuad. - msb, 1988 */
  870. #ifndef lint
  871. static char *SQ_SccsId = "@(#)forget.c    1.4 88/08/24";
  872. #endif
  873. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  874.  *  forget                William L. Sebok
  875.  * A "smarter" malloc v1.0        Sept. 24, 1984 rev. June 30,1986
  876.  *            Then modified by Arthur David Olsen
  877.  *
  878.  *    forget returns to the malloc arena all memory allocated by sbrk()
  879.  *     above "bpnt".
  880.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  881.  
  882. void
  883. forget(bpnt)
  884. char *bpnt;
  885. {
  886.     register struct overhead *p, *q, *r, *b;
  887.     register Size l;
  888.     struct overhead *crbrk;
  889.     char pinvalid, oendfree;
  890.  
  891.     /*
  892.      * b = forget point
  893.      * p = beginning of entry
  894.      * q = end of entry, beginning of gap
  895.      * r = end of gap, beginning of next entry (or the break)
  896.      * pinvalid = true when groveling at forget point
  897.      */
  898.  
  899.     pinvalid = 0;
  900.     oendfree = endfree;    endfree = 0;
  901.     b = (struct overhead *)bpnt;
  902.     p = FROMADJ(adjhead.q_back);
  903.     r = crbrk = (struct overhead *)CURBRK;
  904.  
  905.     for (;pinvalid == 0 && b < r; p = FROMADJ(TOADJ(r = p)->q_back)) {
  906.         if ( p == FROMADJ(&adjhead)
  907.          || (q = (struct overhead *)((char *)p + p->ov_length)) < b
  908.         ) {
  909.             pinvalid = 1;
  910.             q = b;
  911.         }
  912.  
  913.         if (q == r)
  914.             continue;
  915.  
  916.         ASSERT(q < r,
  917. "\nforget: addresses in adjacency chain are out of order!\n");
  918.  
  919.         /* end of gap is at break */
  920.         if (oendfree && r == crbrk) {
  921.             (void)BRK((char *)q);    /* free it yourself */
  922.             crbrk = r = q;
  923.             continue;
  924.         }
  925.  
  926.         if (pinvalid)
  927.             q = (struct overhead *) /* align q pointer */
  928.                 (((long)q + (NALIGN-1)) & (~(NALIGN-1)));
  929.  
  930.         l = (char *)r - (char *)q;
  931.         /*
  932.          * note: unless something is screwy: (l%NALIGN) == 0
  933.          * as r should be aligned by this point
  934.          */
  935.  
  936.         if (l >= (int) sizeof(struct overhead)) {
  937.             /* construct busy entry and free it */
  938.             q->ov_magic = MAGIC_BUSY;
  939.             q->ov_length = l;
  940.             insque(TOADJ(q),TOADJ(p));
  941.             free((char *)q + sizeof(struct overhead));
  942.         } else if (pinvalid == 0) {
  943.             /* append it to previous entry */
  944.             p->ov_length += l;
  945.             if (p->ov_magic == MAGIC_FREE) {
  946.                 remque(TOBUK(p));
  947.                 {
  948.                     register struct qelem *    bp;
  949.  
  950.                     bp = &buckets[mlindx(p->ov_length)];
  951.                     if (bp > hifreebp)
  952.                         hifreebp = bp;
  953.                     insque(TOBUK(p),bp);
  954.                 }
  955.             }
  956.         }
  957.     }
  958.     endfree = oendfree;
  959.     if (endfree)
  960.         mlfree_end();
  961.     return;
  962. }
  963. @@@End of forget.c
  964. echo x - free.c 1>&2
  965. cat >free.c <<'@@@End of free.c'
  966. #include "malloc.h"
  967. #define NULL 0
  968.  
  969. /* NOT copyright by SoftQuad. - msb, 1988 */
  970. #ifndef lint
  971. static char *SQ_SccsId = "@(#)free.c    1.6 88/08/24";
  972. #endif
  973. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  974.  *  free                    William L. Sebok
  975.  * A "smarter" malloc v1.0        Sept. 24, 1984 rev. June 30,1986
  976.  *            Then modified by Arthur David Olsen
  977.  *            MALLOCTRACE added by Mark Brader
  978.  *
  979.  *     free takes a previously malloc-allocated area at mem and frees it.
  980.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  981.  
  982. free(mem)
  983. register char *mem;
  984. {
  985.     register struct overhead *p, *q;
  986.     void mlfree_end();
  987.  
  988. #ifdef    MALLOCTRACE    /* See ./TRACE_README */
  989.     extern enum _malstate _malstate;
  990.  
  991.     if (_malstate == S_INITIAL) _mal_init_trace();
  992. #endif
  993.  
  994.     if (mem == NULL)
  995.         return;
  996.  
  997.     p = (struct overhead *)(mem - sizeof(struct overhead));
  998.  
  999. #ifdef    MALLOCTRACE
  1000.     if (_malstate == S_TRACING)
  1001.         _mal_write_trace ("free", p->ov_length, p->ov_length, mem);
  1002. #endif
  1003.  
  1004.     /* not advised but allowed */
  1005.     if (p->ov_magic == MAGIC_FREE)
  1006.         return;
  1007.  
  1008.     if (p->ov_magic != MAGIC_BUSY) {
  1009.         mllcerr("attempt to free memory not allocated with malloc!\n");
  1010. #ifdef    MALLOCTRACE
  1011.         return;        /* mllcerr() normally doesn't return */
  1012. #endif
  1013.     }
  1014.  
  1015.     /* try to merge with previous free area */
  1016.     q = FROMADJ((TOADJ(p))->q_back);
  1017.  
  1018.     if (q != FROMADJ(&adjhead)) {
  1019.         ASSERT(q < p,
  1020. "\nfree: While trying to merge a free area with a lower adjacent free area,\n\
  1021.  addresses were found out of order!\n");
  1022.         /* If lower segment can be merged */
  1023.         if (   q->ov_magic == MAGIC_FREE
  1024.            && (char *)q + q->ov_length == (char *)p
  1025.         ) {
  1026.             /* remove lower address area from bucket chain */
  1027.             remque(TOBUK(q));
  1028.  
  1029.             /* remove upper address area from adjacency chain */
  1030.             remque(TOADJ(p));
  1031.  
  1032.             q->ov_length += p->ov_length;
  1033.             p->ov_magic = NULL;    /* decommission */
  1034.             p = q;
  1035.         }
  1036.     }
  1037.  
  1038.     /* try to merge with next higher free area */
  1039.     q = FROMADJ((TOADJ(p))->q_forw);
  1040.  
  1041.     if (q != FROMADJ(&adjhead)) {
  1042.         /* upper segment can be merged */
  1043.         ASSERT(q > p,
  1044. "\nfree: While trying to merge a free area with a higher adjacent free area,\n\
  1045.  addresses were found out of order!\n");
  1046.         if (     q->ov_magic == MAGIC_FREE
  1047.            &&    (char *)p + p->ov_length == (char *)q
  1048.         ) {
  1049.             /* remove upper from bucket chain */
  1050.             remque(TOBUK(q));
  1051.  
  1052.             /* remove upper from adjacency chain */
  1053.             remque(TOADJ(q));
  1054.  
  1055.             p->ov_length += q->ov_length;
  1056.             q->ov_magic = NULL;    /* decommission */
  1057.         }
  1058.     }
  1059.  
  1060.     p->ov_magic = MAGIC_FREE;
  1061.  
  1062.     /* place in bucket chain */
  1063.     {
  1064.         register struct qelem *    bp;
  1065.  
  1066.         bp = &buckets[mlindx(p->ov_length)];
  1067.         if (bp > hifreebp)
  1068.             hifreebp = bp;
  1069.         insque(TOBUK(p),bp);
  1070.     }
  1071.  
  1072.     if (endfree)
  1073.         mlfree_end();
  1074.  
  1075.     return;
  1076. }
  1077.  
  1078. void
  1079. mlfree_end()
  1080. {
  1081.     register struct overhead *p;
  1082.  
  1083.     p = FROMADJ(adjhead.q_back);
  1084.     if (    /* area is free and at end of memory */
  1085.             p->ov_magic == MAGIC_FREE
  1086.         &&    (char*)p + p->ov_length == (char *)CURBRK
  1087.     ) {
  1088.         p->ov_magic = NULL;    /* decommission (just in case) */
  1089.  
  1090.         /* remove from end of adjacency chain */
  1091.         remque(TOADJ(p));
  1092.  
  1093.         /* remove from bucket chain */
  1094.         remque(TOBUK(p));
  1095.  
  1096.         /* release memory to system */
  1097.         (void)BRK((char *)p);
  1098.     }
  1099.     return;
  1100. }
  1101. @@@End of free.c
  1102. echo x - init_trace.c 1>&2
  1103. cat >init_trace.c <<'@@@End of init_trace.c'
  1104. #ifdef    MALLOCTRACE
  1105.  
  1106. #include <stdio.h>
  1107. #include "malloc.h"
  1108.  
  1109.  
  1110. /* NOT copyright by SoftQuad. - msb, 1988 */
  1111. #ifndef lint
  1112. static char *SQ_SccsId = "@(#)init_trace.c    1.3 88/08/24";
  1113. #endif
  1114. /*
  1115.  * Open the trace output file.  The _malstate serves to prevent
  1116.  * any infinite recursion if stdio itself calls malloc.
  1117.  */
  1118.  
  1119. void
  1120. _mal_init_trace()
  1121. {
  1122.     char *filename, *bufflag;
  1123.     char *getenv();
  1124.     extern enum _malstate _malstate;
  1125.     extern int _malbuff;
  1126.     extern FILE *_malfp;
  1127.  
  1128.     if (_malstate != S_INITIAL)    /* Can't happen, but what the heck */
  1129.         return;
  1130.  
  1131.     _malstate = S_IN_STDIO;
  1132.  
  1133.     filename = getenv (TRACEENVVAR);
  1134.     if (filename == NULL)
  1135.         filename = TRACEFILE;
  1136.  
  1137.     _malfp = fopen (filename, "w");
  1138.     if (_malfp == NULL) {
  1139.  
  1140.         perror (filename);
  1141.         fprintf(stderr, "(will run without malloc tracing)\n");
  1142.  
  1143.     } else {
  1144.         /*
  1145.          * Nonportable kludge that should trigger a malloc
  1146.          * in stdio while doing no harm, and also reduce the
  1147.          * likelihood of a future malloc in stdio.
  1148.          */
  1149.  
  1150.         putc (0, _malfp);
  1151.         fflush (_malfp);
  1152.         fseek (_malfp, 0L, 0);
  1153.  
  1154.         /* Were we requested not to flush after each entry? */
  1155.  
  1156.         bufflag = getenv (TRACEBUFVAR);
  1157.         _malbuff = (bufflag != NULL && *bufflag != '\0');
  1158.  
  1159.         /* Initialization successful */
  1160.  
  1161.         _malstate = S_TRACING;
  1162.     }
  1163. }
  1164. #endif
  1165. @@@End of init_trace.c
  1166. echo x - malloc.c 1>&2
  1167. cat >malloc.c <<'@@@End of malloc.c'
  1168. #include "malloc.h"
  1169. #define NULL 0
  1170.  
  1171. /* NOT copyright by SoftQuad. - msb, 1988 */
  1172. #ifndef lint
  1173. static char *SQ_SccsId = "@(#)malloc.c    1.8 88/08/24";
  1174. #endif
  1175. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1176.  * A  "smarter" malloc v1.0            William L. Sebok
  1177.  *                    Sept. 24, 1984 rev. June 30,1986
  1178.  *            Then modified by Arthur David Olsen
  1179.  *            MALLOCTRACE added by Mark Brader
  1180.  *
  1181.  *    malloc allocates and returns a pointer to a piece of memory nbytes
  1182.  *    in size.
  1183.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1184.  
  1185. #ifdef    MALLOCTRACE    /* See ./TRACE_README */
  1186.  
  1187. #include <stdio.h>
  1188. FILE *_malfp;
  1189. int _malbuff;
  1190.  
  1191. enum _malstate _malstate = S_INITIAL;
  1192.  
  1193. #endif
  1194.  
  1195. /* sizes of buckets currently proportional to log 2() */
  1196. static Size mlsizes[] = {0, 64, 128, 256, 512, 1024, 2048,
  1197.     4096, 8192, 16384, 32768, 65536, 131072,
  1198.     262144, 524288, 1048576, 2097152, 4194304};
  1199.  
  1200. /* head of adjacency chain */
  1201. struct qelem adjhead = { &adjhead, &adjhead };
  1202.  
  1203. /* head of bucket chains */
  1204. struct qelem buckets[NBUCKETS] = {
  1205.     &buckets[0],  &buckets[0],    &buckets[1],  &buckets[1],
  1206.     &buckets[2],  &buckets[2],    &buckets[3],  &buckets[3],
  1207.     &buckets[4],  &buckets[4],    &buckets[5],  &buckets[5],
  1208.     &buckets[6],  &buckets[6],    &buckets[7],  &buckets[7],
  1209.     &buckets[8],  &buckets[8],    &buckets[9],  &buckets[9],
  1210.     &buckets[10], &buckets[10],    &buckets[11], &buckets[11],
  1211.     &buckets[12], &buckets[12],    &buckets[13], &buckets[13],
  1212.     &buckets[14], &buckets[14],    &buckets[15], &buckets[15],
  1213.     &buckets[16], &buckets[16],    &buckets[17], &buckets[17]
  1214. };
  1215.  
  1216. struct qelem *    hifreebp = &buckets[0];
  1217.  
  1218. char endfree = 0;
  1219. void (*mlabort)() = {0};
  1220. void    mlfree_end();
  1221.  
  1222. char *
  1223. malloc(nbytes)
  1224.     unsigned nbytes;    /* for 4.3 compat. */
  1225. {
  1226.     register struct overhead *p, *q;
  1227.     register struct qelem *bucket;
  1228.     register Size surplus;
  1229.     Size mlindx();
  1230.  
  1231. #ifdef    MALLOCTRACE
  1232.     unsigned old_nbytes;
  1233.  
  1234.     old_nbytes = nbytes;
  1235.     if (_malstate == S_INITIAL) _mal_init_trace();
  1236. #endif
  1237.  
  1238.     nbytes = ((nbytes + (NALIGN-1)) & ~(NALIGN-1))
  1239.         + sizeof(struct overhead);
  1240.  
  1241.     for (
  1242.         bucket = &buckets[mlindx((Size) nbytes)];
  1243.         bucket <= hifreebp;
  1244.         bucket++
  1245.     ) { 
  1246.         register struct qelem *b;
  1247.         for(b = bucket->q_forw; b != bucket; b = b->q_forw) {
  1248.             p = FROMBUK(b);
  1249.             ASSERT(p->ov_magic == MAGIC_FREE,
  1250. "\nmalloc: Entry not marked FREE found on Free List!\n");
  1251.             if (p->ov_length >= nbytes) {
  1252.                 remque(b);
  1253.                 surplus = p->ov_length - nbytes;
  1254.                 goto foundit;
  1255.             }
  1256.         }
  1257.     }
  1258.  
  1259.     /* obtain additional memory from system */
  1260.     {
  1261.         register Size i;
  1262.         p = (struct overhead *)CURBRK;
  1263.  
  1264.         i = ((Size)p)&(NALIGN-1);
  1265.         if (i != 0)
  1266.             p = (struct overhead *)((char *)p + NALIGN - i);
  1267.  
  1268.         if (BRK((char *)p + nbytes)) {
  1269. #ifdef    MALLOCTRACE
  1270.             if (_malstate == S_TRACING)
  1271.                 _mal_write_trace ("malloc", (Size) old_nbytes,
  1272.                             (Size) 0, (char*) 0);
  1273. #endif
  1274.             return(NULL);
  1275.         }
  1276.  
  1277.         p->ov_length = nbytes;
  1278.         surplus = 0;
  1279.  
  1280.         /* add to end of adjacency chain */
  1281.         ASSERT((FROMADJ(adjhead.q_back)) < p,
  1282. "\nmalloc: Entry in adjacency chain found with address lower than Chain head!\n"
  1283.             );
  1284.         insque(TOADJ(p),adjhead.q_back);
  1285.     }
  1286.  
  1287. foundit:
  1288.     /* mark surplus memory free */
  1289.     if (surplus > (int) sizeof(struct overhead)) {
  1290.         /* if big enough, split it up */
  1291.         q = (struct overhead *)((char *)p + nbytes);
  1292.  
  1293.         q->ov_length = surplus;
  1294.         p->ov_length = nbytes;
  1295.         q->ov_magic = MAGIC_FREE;
  1296.  
  1297.         /* add surplus into adjacency chain */
  1298.         insque(TOADJ(q),TOADJ(p));
  1299.  
  1300.         /* add surplus into bucket chain */
  1301.         {
  1302.             register struct qelem *    bp;
  1303.  
  1304.             bp = &buckets[mlindx(surplus)];
  1305.             if (bp > hifreebp)
  1306.                 hifreebp = bp;
  1307.             insque(TOBUK(q),bp);
  1308.         }
  1309.     }
  1310. #ifdef    MALLOCTRACE
  1311.     else
  1312.         nbytes += surplus;
  1313.  
  1314.     if (_malstate == S_TRACING)
  1315.         _mal_write_trace ("malloc", (Size) old_nbytes, (Size) nbytes,
  1316.                     (char *) p + sizeof (struct overhead));
  1317. #endif
  1318.  
  1319.     p->ov_magic = MAGIC_BUSY;
  1320.     return((char*)p + sizeof(struct overhead));
  1321. }
  1322.  
  1323. /*
  1324.  * select the proper size bucket
  1325.  */
  1326. Size
  1327. mlindx(n)
  1328. register Size n;
  1329. {
  1330.     register Size *p;
  1331.  
  1332.     p = mlsizes;
  1333.     p[NBUCKETS - 1] = n;
  1334.     /* Linear search. */
  1335.     while (n > *p++)
  1336.         ;
  1337.     return (p - 1) - mlsizes;
  1338. }
  1339.  
  1340. void
  1341. mllcerr(p)
  1342. char *p;
  1343. {
  1344.     register char *q;
  1345.     q = p;
  1346.     while (*q++);    /* find end of string */
  1347.     (void)write(2,p,q-p-1);
  1348. #ifndef    MALLOCTRACE
  1349.     if (mlabort)
  1350.         (*mlabort)();
  1351. #ifdef debug
  1352.     else
  1353.         abort();
  1354. #endif debug
  1355. #endif    MALLOCTRACE
  1356. }
  1357.  
  1358. #ifndef vax
  1359. /*
  1360.  * The vax has wondrous instructions for inserting and removing items into
  1361.  * doubly linked queues.  On the vax the assembler output of the C compiler is
  1362.  * massaged by an sed script to turn these function calls into invocations of
  1363.  * the insque and remque machine instructions.
  1364.  */
  1365.  
  1366. void
  1367. insque(item,queu)
  1368. register struct qelem *item, *queu;
  1369. /* insert "item" after "queu" */
  1370. {
  1371.     register struct qelem *pueu;
  1372.     pueu = queu->q_forw;
  1373.     item->q_forw = pueu;
  1374.     item->q_back = queu;
  1375.     queu->q_forw = item;
  1376.     pueu->q_back = item;
  1377. }
  1378.  
  1379. void
  1380. remque(item)
  1381. register struct qelem *item;
  1382. /* remove "item" */
  1383. {
  1384.     register struct qelem *queu, *pueu;
  1385.     pueu = item->q_forw;
  1386.     queu = item->q_back;
  1387.     queu->q_forw = pueu;
  1388.     pueu->q_back = queu;
  1389. }
  1390. #endif
  1391. @@@End of malloc.c
  1392. echo x - malloc.h 1>&2
  1393. cat >malloc.h <<'@@@End of malloc.h'
  1394. /* NOT copyright by SoftQuad. - msb, 1988 */
  1395.  
  1396. /* SQ SccsId "@(#)malloc.h    1.6 88/08/24" */
  1397.  
  1398. /*LINTLIBRARY*/
  1399.  
  1400. #ifndef lint
  1401. #ifndef NOID
  1402. #endif /* !NOID */
  1403. #endif /* !lint */
  1404.  
  1405. #ifdef vax
  1406.  
  1407. struct qelem *    _p;
  1408. struct qelem *    _q;
  1409.  
  1410. #define remque(p)    { _p = (p); asm("remque    *__p,r0"); }
  1411. #define insque(p, q)    { _p = (p); _q = (q) ; asm("insque    *__p,*__q"); }
  1412.  
  1413. #endif /* vax */
  1414.  
  1415. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1416.  * A  "smarter" malloc                William L. Sebok
  1417.  *            Then modified by Arthur David Olsen
  1418.  *            MALLOCTRACE added by Mark Brader
  1419.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1420.  *    Algorithm:
  1421.  *     Assign to each area an index "n". This is currently proportional to
  1422.  *    the log 2 of size of the area rounded down to the nearest integer.
  1423.  *    Then all free areas of storage whose length have the same index n are
  1424.  *    organized into a chain with other free areas of index n (the "bucket"
  1425.  *    chain). A request for allocation of storage first searches the list of
  1426.  *    free memory.  The search starts at the bucket chain of index equal to
  1427.  *    that of the storage request, continuing to higher index bucket chains
  1428.  *    if the first attempt fails.
  1429.  *    If the search fails then new memory is allocated.  Only the amount of
  1430.  *    new memory needed is allocated.  Any old free memory left after an
  1431.  *    allocation is returned to the free list.
  1432.  *
  1433.  *      All memory areas (free or busy) handled by malloc are also chained
  1434.  *    sequentially by increasing address (the adjacency chain).  When memory
  1435.  *    is freed it is merged with adjacent free areas, if any.  If a free area
  1436.  *    of memory ends at the end of memory (i.e. at the break), and if the
  1437.  *    variable "endfree" is non-zero, then the break is contracted, freeing
  1438.  *    the memory back to the system.
  1439.  *
  1440.  *    Notes:
  1441.  *        ov_length field includes sizeof(struct overhead)
  1442.  *        adjacency chain includes all memory, allocated plus free.
  1443.  */
  1444.  
  1445. /* the following items may need to be configured for a particular machine */
  1446.  
  1447. /* alignment requirement for machine (in bytes) */
  1448. #define NALIGN    4
  1449.  
  1450. /* size of an integer large enough to hold a character pointer */
  1451. typedef    long    Size;
  1452.  
  1453. /*
  1454.  * CURBRK returns the value of the current system break, i.e., the system's
  1455.  * idea of the highest legal address in the data area.  It is defined as
  1456.  * a macro for the benefit of systems that have provided an easier way to
  1457.  * obtain this number (such as in an external variable)
  1458.  */
  1459.  
  1460. #ifndef CURBRK
  1461. #define CURBRK    sbrk(0)
  1462. extern char *sbrk();
  1463. #else /* CURBRK */
  1464. #    if    CURBRK == curbrk
  1465. extern Size curbrk;
  1466. #    endif
  1467. #endif /* CURBRK */
  1468.  
  1469. /*
  1470.  * note that it is assumed that CURBRK remembers the last requested break to
  1471.  * the nearest byte (or at least the nearest word) rather than the nearest page
  1472.  * boundary.  If this is not true then the following BRK macro should be
  1473.  * replaced with one that remembers the break to within word-size accuracy.
  1474.  */
  1475.  
  1476. #ifndef BRK
  1477. #define BRK(x)    brk(x)
  1478. extern char *brk();
  1479. #endif /* !BRK */
  1480.  
  1481. /* END of machine dependent portion */
  1482.  
  1483. #ifdef    MALLOCTRACE
  1484. /* Tracing of all calls to malloc, free, realloc... see ./TRACE_README */
  1485.  
  1486. enum _malstate {S_INITIAL, S_IN_STDIO, S_IN_REALLOC, S_TRACING};
  1487.  
  1488. #define    TRACEFILE    "malloc.out"    /* default output filename */
  1489.  
  1490. #undef    MALLOCTRACE        /* so the next line means what it says! */
  1491. #define    TRACEENVVAR    "MALLOCTRACE"    /* where to read nondefault name */
  1492. #define    MALLOCTRACE        /* cancel #undef! */
  1493.  
  1494. #define    TRACEBUFVAR    "MALLOCTRACEBUF"    /* No-flush request */
  1495. #endif
  1496.  
  1497. #define    MAGIC_FREE    0x548a934c
  1498. #define    MAGIC_BUSY    0xc139569a
  1499.  
  1500. #define NBUCKETS    18
  1501.  
  1502. struct qelem {
  1503.     struct qelem *q_forw;
  1504.     struct qelem *q_back;
  1505. };
  1506.  
  1507. struct overhead {
  1508.     struct qelem    ov_adj;        /* adjacency chain pointers */ 
  1509.     struct qelem    ov_buk;        /* bucket chain pointers */
  1510.     long        ov_magic;
  1511.     Size        ov_length;
  1512. };
  1513.  
  1514. /*
  1515.  * The following macros depend on the order of the elements in struct overhead
  1516.  */
  1517. #define TOADJ(p)    ((struct qelem *)(p))
  1518. #define FROMADJ(p)    ((struct overhead *)(p))
  1519. #define FROMBUK(p)    ((struct overhead *)( (char *)p - sizeof(struct qelem)))
  1520. #define TOBUK(p)    ((struct qelem *)( (char *)p + sizeof(struct qelem)))
  1521.  
  1522. /*
  1523.  * return to the system memory freed adjacent to the break 
  1524.  * default is Off
  1525.  */
  1526. extern char endfree;
  1527.  
  1528. /* head of adjacency chain */
  1529. extern struct qelem adjhead;
  1530.  
  1531. /* head of bucket chains */
  1532. extern struct qelem buckets[NBUCKETS];
  1533. extern struct qelem *    hifreebp;
  1534.  
  1535. extern void (*mlabort)();
  1536.  
  1537. #ifndef vax
  1538. extern void insque(), remque();
  1539. #endif
  1540. extern void mllcerr();
  1541. extern char *malloc(), *realloc();
  1542.  
  1543. #ifdef debug
  1544. # define ASSERT(p,q)    if (!(p)) mllcerr(q)
  1545. #else
  1546. # define ASSERT(p,q)    ((p),(q))
  1547. #endif
  1548. @@@End of malloc.h
  1549. echo x - mtest1.c 1>&2
  1550. cat >mtest1.c <<'@@@End of mtest1.c'
  1551.  
  1552. /* NOT copyright by SoftQuad. - msb, 1988 */
  1553. #ifndef lint
  1554. static char *SQ_SccsId = "@(#)mtest1.c    1.2 88/08/24";
  1555. #endif
  1556. /*
  1557.  * tstmalloc    this routine tests and exercizes the malloc/free package
  1558.  */
  1559. #include <stdio.h>
  1560. #include <setjmp.h>
  1561. #include "malloc.h"
  1562.  
  1563. jmp_buf env;
  1564.  
  1565. main(argc,argv)
  1566. int argc; char *argv[];
  1567. {
  1568.     char lin[100], arg1[20], arg2[20], arg3[20];
  1569.     char *res, *malloc(), *realloc();
  1570.     register struct overhead *p, *q;
  1571.     register struct qelem *qp;
  1572.     int arg, nargs, argn;
  1573.     int l;
  1574.     void malerror();
  1575.  
  1576.     mlabort = &malerror;
  1577.     setjmp(env);
  1578.  
  1579.     for (;;) {
  1580.         printf("*  ");
  1581.         if (fgets(lin,sizeof lin, stdin)== NULL)
  1582.             exit(0);
  1583.         nargs = sscanf(lin,"%s%s%s",arg1,arg2,arg3);
  1584.         switch (arg1[0]) {
  1585.  
  1586.         case 'b':
  1587.             if (nargs == 2) {
  1588.                 arg = atoi(arg2);
  1589.                 if (arg<0 ||  arg>=NBUCKETS)
  1590.                     goto bad;
  1591.  
  1592.                 qp = &buckets[arg];
  1593.                 printf("Bucket %2d\t\t\t  buk=%08lx %08lx\n",
  1594.                     arg, qp->q_forw,qp->q_back);
  1595.                 qp = qp->q_forw;
  1596.                 for (; qp != &buckets[arg]; qp = qp->q_forw) {
  1597.                     p = FROMBUK(qp);
  1598.                     if (dump(p))
  1599.                         break;
  1600.                 }
  1601.             } else {
  1602.                 printf("Buckets:");
  1603.                 for (qp=buckets; qp<&buckets[NBUCKETS];qp++){
  1604.                     if (qp->q_forw != qp)
  1605.                         printf(" %d", qp-buckets);
  1606.                 }
  1607.                 printf("\n");
  1608.             }
  1609.             break;
  1610.         case 'e':
  1611.             endfree = 1;
  1612.             break;
  1613.         case 'E':
  1614.             endfree = 0;
  1615.             break;
  1616.         case 'f':
  1617.             if (nargs != 2) goto bad;
  1618.             sscanf(arg2,"%lx",&arg);
  1619.             printf("free(%x)\n",arg);
  1620.             free(arg);
  1621.             break;
  1622.         case 'F':
  1623.             if (nargs != 2) goto bad;
  1624.             sscanf(arg2,"%lx",&arg);
  1625.             printf("forget(%x)\n",arg);
  1626.             forget(arg);
  1627.             break;
  1628.         case 'h':
  1629.             printf("\
  1630. b    print bucket chains that aren't empty\n\
  1631. b [n]    trace through bucket chains\n\
  1632. e    turn on freeing of end of memory\n\
  1633. E    turn off freeing of end of memory\n\
  1634. f addr        free addr\n\
  1635. F addr        forget below addr\n\
  1636. h    print this help file\n\
  1637. m bytes        malloc bytes\n\
  1638. q    quit\n\
  1639. r addr bytes    realloc\n\
  1640. s    print break addr\n\
  1641. S    sbrk count\n\
  1642. t    trace through adjacency chain\n\
  1643. ");
  1644.             break;
  1645.         case 'm':
  1646.             if (nargs != 2) goto bad;
  1647.             arg = atoi(arg2);
  1648.             res = malloc(arg);
  1649.             printf("malloc(%d) = %lx\n",arg, res);
  1650.             break;
  1651.         case 'r':
  1652.             if (nargs != 3) goto bad;
  1653.             sscanf(arg2,"%lx",&arg);
  1654.             argn = atoi(arg3);
  1655.             res = realloc(arg,argn);
  1656.             printf("realloc(%lx,%d) = %lx\n",arg,argn,res);
  1657.             break;
  1658.         case 'q':
  1659.             exit(0);
  1660.             break;
  1661.         case 's':
  1662.             printf("brk = %08x\n",sbrk(0));
  1663.             break;
  1664.         case 'S':
  1665.             if (nargs != 2) goto bad;
  1666.             sscanf(arg2,"%ld",&arg);
  1667.             printf("sbrk(%d)\n",arg);
  1668.             sbrk(arg);
  1669.             break;
  1670.         case 't':
  1671.             printf("\t\t\t\t\t\thead    adj=%08lx %08lx\n",
  1672.                 adjhead.q_forw,adjhead.q_back);
  1673.             for (qp = adjhead.q_forw; qp!=&adjhead; qp=qp->q_forw) { 
  1674.                 p = FROMADJ(qp);
  1675.                 if (dump(p))
  1676.                     break;
  1677.                 q = FROMADJ(qp->q_forw);
  1678.                 if (q==FROMADJ(&adjhead))
  1679.                     q = (struct overhead *)sbrk(0);
  1680.                 l = (char *)q - (char *)p - p->ov_length;
  1681.                 if (l>0)
  1682.                     printf("%08x free space  len=%8d\n",
  1683.                         (char *)p + p->ov_length, l);
  1684.             }
  1685.             break;
  1686.         default:
  1687.     bad:        printf("Bad command\n");
  1688.         }
  1689.     }
  1690. }
  1691.  
  1692. dump(p)
  1693. register struct overhead *p;
  1694. {
  1695.     register char *s;
  1696.     int stat = 0;
  1697.  
  1698.     if (p->ov_magic == MAGIC_FREE)
  1699.         s = "MAGIC_FREE ";
  1700.     else if (p->ov_magic == MAGIC_BUSY) 
  1701.         s = "MAGIC_BUSY ";
  1702.     else {
  1703.         s = "BAD MAGIC  ";
  1704.         stat = 1;
  1705.     }
  1706.         
  1707.     printf( "%08x %s len=%8d buk=%08x %08x adj=%08x %08x\n",
  1708.         (&p[1]),s,p->ov_length,p->ov_buk.q_forw,p->ov_buk.q_back,
  1709.         p->ov_adj.q_forw,p->ov_adj.q_back
  1710.     );
  1711.     return(stat);
  1712. }
  1713.  
  1714. void
  1715. malerror()
  1716. {
  1717.     write(2,"malloc error\n",13);
  1718.     longjmp(env,1);
  1719. }
  1720. @@@End of mtest1.c
  1721. echo x - mtest2.c 1>&2
  1722. cat >mtest2.c <<'@@@End of mtest2.c'
  1723. /* NOT copyright by SoftQuad Inc. -- msb, 1988 */
  1724. #ifndef lint
  1725. static char *SQ_SccsId = "@(#)mtest2.c    1.2 88/08/25";
  1726. #endif
  1727. #include <stdio.h>
  1728.  
  1729. extern int      atoi ();
  1730. extern long     random ();
  1731. extern char    *sbrk ();
  1732.  
  1733. extern char    *malloc ();
  1734. extern char    *realloc ();
  1735. extern int      free ();
  1736.  
  1737. struct memevent {
  1738.         int                     m_time;         /* time to go */
  1739.         char                   *m_memory;       /* malloc'ed mem */
  1740.         unsigned                m_size;         /* size of mem */
  1741.         int                     m_id;           /* id, for trace/debug */
  1742.         int                     m_realloc;      /* counter, for debugging */
  1743.         char                    m_pattern;      /* pattern in memory */
  1744.         struct memevent        *m_next;         /* linked list pointer */
  1745. };
  1746.  
  1747. #ifndef MAX_EVENTS
  1748. #define MAX_EVENTS      10000
  1749. #endif
  1750.  
  1751. struct memevent eventpool[ MAX_EVENTS ];
  1752.  
  1753. struct memevent *events;
  1754. struct memevent *free_events;
  1755.  
  1756. char stdout_buf[ BUFSIZ ];
  1757. char stderr_buf[ BUFSIZ ];
  1758.  
  1759. int time_to_go;
  1760. int new_probability;
  1761. int realloc_probability = 25;           /* XXX: should set from argv */
  1762. int stat_frequency;
  1763.  
  1764. main (argc, argv)
  1765. int argc;
  1766. char *argv[];
  1767. {
  1768.         init (argc, argv);
  1769.         run_test ();
  1770. }
  1771.  
  1772. /*
  1773.  * run_test ()
  1774.  *
  1775.  * Run the actual memory test.
  1776.  */
  1777.  
  1778. run_test ()
  1779. {
  1780.         while (time_to_go > 0) {
  1781.                 arrival ();
  1782.                 service ();
  1783.                 -- time_to_go;
  1784.                 if ((time_to_go % stat_frequency) == 0)
  1785.                         do_stats ();
  1786.         }
  1787. }
  1788.  
  1789. /*
  1790.  * arrival ()
  1791.  *
  1792.  * With probability new_probability/100, allocate a new piece
  1793.  * of memory with some randomly determined size and lifetime,
  1794.  * and add it to the memory event list.
  1795.  */
  1796.  
  1797. arrival ()
  1798. {
  1799.         if (free_events && odds (new_probability, 100)) {
  1800.                 register struct memevent *m;
  1801.                 register char *p;
  1802.  
  1803.                 m = free_events;
  1804.                 free_events = m->m_next;
  1805.                 m->m_next = NULL;
  1806.  
  1807.                                         /* XXX: let these be set from argv */
  1808.                 m->m_size = (unsigned) random_range (1, 100);
  1809.                 if (time_to_go < 100)
  1810.                         m->m_time = random_range (1, time_to_go);
  1811.                 else
  1812.                         m->m_time = random_range (1, 100);
  1813.  
  1814.                 m->m_pattern = (char) random_range (0, 127);
  1815.                 m->m_realloc = 0;
  1816.                 m->m_memory = malloc (m->m_size);
  1817.                 if (! m->m_memory)
  1818.                         out_of_memory ();
  1819.  
  1820.  
  1821.                 for (p = m->m_memory; p < & m->m_memory[ m->m_size ]; p++)
  1822.                         *p = m->m_pattern;
  1823.  
  1824.                 add_to_events (m);
  1825.         }
  1826. } /* arrival */
  1827.  
  1828. /*
  1829.  * do_stats ()
  1830.  */
  1831.  
  1832. do_stats ()
  1833. {
  1834.         register struct memevent *m;
  1835.         int i;
  1836.         long total;
  1837.  
  1838.         printf ("---------------------\nTIME Remaining: %d\n", time_to_go);
  1839.  
  1840.         /* print other interesting but implementation-dependent stuff here
  1841.            (like count of blocks in heap, size of heap, etc) */
  1842.  
  1843.         total = 0;
  1844.         for (i = 1, m = events; m != NULL; m = m->m_next, i++) {
  1845.                 printf ("EVENT %5d (id %5d): ", i, m->m_id);
  1846.                 printf ("SIZE %4d, ", m->m_size);
  1847.                 printf ("PATTERN 0x%02x, ", m->m_pattern & 0xFF);
  1848.                 printf ("TIME %4d ", m->m_time);
  1849.                 if (m->m_realloc > 0)
  1850.                         printf ("REALLOC %d", m->m_realloc);
  1851.                 printf ("\n");
  1852.                 total += m->m_size;
  1853.         }
  1854.         printf ("TOTAL events %d, allocated memory %d\n", i-1, total);
  1855.         (void) fflush (stdout);
  1856. } /* do_stats */
  1857.  
  1858. /*
  1859.  * service ()
  1860.  *
  1861.  * Decrement the time remaining on the head event.  If
  1862.  * it's time is up (zero), service it.
  1863.  *
  1864.  * Servicing an event generally means free'ing it (after checking
  1865.  * for corruption).  It is also possible (realloc_probability) to
  1866.  * realloc the event instead.
  1867.  */
  1868.  
  1869. service ()
  1870. {
  1871.         register struct memevent *m;
  1872.  
  1873.         if ((m = events) != NULL)
  1874.                 -- m->m_time;
  1875.  
  1876.         while (m != NULL && m->m_time == 0) {
  1877.                 register char *p;
  1878.  
  1879.                 for (p = m->m_memory; p < & m->m_memory[ m->m_size ]; p++) {
  1880.                         if (*p != m->m_pattern)
  1881.                                 corrupted ();
  1882.                 }
  1883.  
  1884.                 events = m->m_next;     /* delete this event */
  1885.  
  1886.                 if (time_to_go > 1 && odds (realloc_probability, 100))
  1887.                         realloc_event (m);
  1888.                 else
  1889.                         free_event (m);
  1890.  
  1891.                 m = events;
  1892.  
  1893.         }
  1894. } /* service */
  1895.  
  1896. /*
  1897.  * free_event (m)
  1898.  *
  1899.  * Called to free up the given event, including its memory.
  1900.  */
  1901.  
  1902. free_event (m)
  1903. register struct memevent *m;
  1904. {
  1905.         free (m->m_memory);
  1906.         m->m_next = free_events;
  1907.         free_events = m;
  1908. }
  1909.  
  1910. /*
  1911.  * realloc_event (m)
  1912.  *
  1913.  * Called from service(), to reallocate an event's memory,
  1914.  * rather than freeing it.
  1915.  */
  1916.  
  1917. realloc_event (m)
  1918. register struct memevent *m;
  1919. {
  1920.         register char *p;
  1921.         unsigned new_size;
  1922.         unsigned min_size;
  1923.  
  1924.                                         /* XXX: let these be set from argv */
  1925.         new_size = (unsigned) random_range (1, 100);
  1926.  
  1927.         ++ m->m_realloc;                /* for stats */
  1928.         m->m_memory = realloc (m->m_memory, new_size);
  1929.         if (! m->m_memory)
  1930.                 out_of_memory ();
  1931.  
  1932.         m->m_next = NULL;
  1933.  
  1934.         if (time_to_go < 100)
  1935.                 m->m_time = random_range (1, time_to_go - 1);
  1936.         else
  1937.                 m->m_time = random_range (1, 100);   /* XXX: should set from argv */
  1938.  
  1939.         min_size = new_size > m->m_size ? m->m_size : new_size;
  1940.  
  1941.         for (p = m->m_memory; p < & m->m_memory[ min_size ]; p++) {
  1942.                 if (*p != m->m_pattern)
  1943.                         corrupted ();
  1944.         }
  1945.  
  1946.         m->m_size = new_size;
  1947.         for (p = m->m_memory; p < & m->m_memory[ m->m_size ]; p++)
  1948.                 *p = m->m_pattern;
  1949.  
  1950.  
  1951.         add_to_events (m);
  1952. } /* realloc_event */
  1953.  
  1954. /*
  1955.  * add_to_events (m)
  1956.  *
  1957.  * Add the given event structure onto the time-ordered event list.
  1958.  */
  1959.  
  1960. add_to_events (m)
  1961. register struct memevent *m;
  1962. {
  1963.         register struct memevent *l;
  1964.         register struct memevent *ol;
  1965.  
  1966.         for (ol = NULL, l = events; l != NULL; ol = l, l = l->m_next) {
  1967.                 if (l->m_time > m->m_time) {
  1968.                         if (ol == NULL) {
  1969.                                 m->m_next = events;
  1970.                                 events = m;
  1971.                         }
  1972.                         else {
  1973.                                 m->m_next = l;
  1974.                                 ol->m_next = m;
  1975.                         }
  1976.  
  1977.                         l->m_time -= m->m_time;
  1978.                         return;
  1979.                 }
  1980.  
  1981.                 m->m_time -= l->m_time;
  1982.         }
  1983.  
  1984.         if (events == NULL)
  1985.                 events = m;
  1986.         else
  1987.                 ol->m_next = m;
  1988. } /* add_to_events */
  1989.  
  1990. /*
  1991.  * init_events ()
  1992.  *
  1993.  * Set up the memevent pools.
  1994.  */
  1995.  
  1996. init_events ()
  1997. {
  1998.         register struct memevent *m;
  1999.         int i;
  2000.  
  2001.         for (i = 0, m = eventpool; m < & eventpool[ MAX_EVENTS ]; m++, i++) {
  2002.                 m->m_id = i;
  2003.                 m->m_next = m + 1;
  2004.         }
  2005.  
  2006.         eventpool[ MAX_EVENTS-1 ].m_next = NULL;
  2007.  
  2008.         free_events = eventpool;
  2009. }
  2010.  
  2011. /*
  2012.  * init (argc, argv)
  2013.  *
  2014.  * Initialize the memory tests.
  2015.  */
  2016.  
  2017. init (argc, argv)
  2018. int argc;
  2019. char *argv[];
  2020. {
  2021.     if (argc != 4) {
  2022.         fprintf (stderr, "usage: %s new_prob time_to_go stat_freq\n", argv[ 0 ]);
  2023.         exit (1);
  2024.     }
  2025.         new_probability = atoi (argv[ 1 ]);
  2026.         time_to_go = atoi (argv[ 2 ]);
  2027.         stat_frequency = atoi (argv[ 3 ]);
  2028.  
  2029.         srandom (1);
  2030.  
  2031.         init_events ();
  2032.  
  2033.         /*
  2034.          * Use statically allocated buffers, otherwise
  2035.          * stdio() will call malloc to allocate buffers, and
  2036.          * this gets confusing when debugging stuff.
  2037.          */
  2038.  
  2039.         setbuf (stdout, (char *) NULL);
  2040.         setbuf (stderr, (char *) NULL);
  2041. }
  2042.  
  2043. /*
  2044.  * XXX: Should really send SIGQUIT ...
  2045.  */
  2046.  
  2047. cause_core_dump ()
  2048. {
  2049.         * (long *) 1 = 5;
  2050. }
  2051.  
  2052. corrupted ()
  2053. {
  2054.         printf ("Corrupted\n");
  2055.         cause_core_dump ();
  2056. }
  2057.  
  2058. out_of_memory ()
  2059. {
  2060.         printf ("Out of memory!\n");
  2061.         cause_core_dump ();
  2062. }
  2063.  
  2064. /*
  2065.  * odds (m, n)
  2066.  *
  2067.  * Return TRUE (non-zero) with probability m out of n.
  2068.  */
  2069.  
  2070. odds (m, n)
  2071. int m;
  2072. int n;
  2073. {
  2074.         return ((random () % n) < m);
  2075. }
  2076.  
  2077. /*
  2078.  * random_range (lo, hi)
  2079.  *
  2080.  * Pick a random integer from lo to hi (inclusive).
  2081.  */
  2082.  
  2083. random_range (lo, hi)
  2084. int lo;
  2085. int hi;
  2086. {
  2087.         return ((random () % (hi - lo + 1)) + lo);
  2088. }
  2089.  
  2090. #if DBG
  2091. /*
  2092.  * de_cmpf (m1,m2)
  2093.  *
  2094.  * compare function for qsort() in dump_events.
  2095.  * Sort by memory address of the memory allocated to
  2096.  * the event.
  2097.  */
  2098.  
  2099. int
  2100. de_cmpf (m1, m2)
  2101. struct memevent **m1;
  2102. struct memevent **m2;
  2103. {
  2104.         unsigned long maddr1 = (unsigned long) (*m1)->m_memory;
  2105.         unsigned long maddr2 = (unsigned long) (*m2)->m_memory;
  2106.  
  2107.                                         /* sloppy */
  2108.         return (maddr1 - maddr2);
  2109. }
  2110. #endif DBG
  2111.  
  2112. /*
  2113.  * dump_events ()
  2114.  *
  2115.  * Useful for debugging.
  2116.  */
  2117.  
  2118. #if DBG
  2119. dump_events ()
  2120. {
  2121.         static struct memevent *sorted[ MAX_EVENTS ];
  2122.         register struct memevent *m;
  2123.         register int i;
  2124.  
  2125.         fprintf (stderr, "DUMP EVENTS (time remaining = %d)\n", time_to_go);
  2126.  
  2127.         for (m = events, i = 0; m != NULL; m = m->m_next, i++)
  2128.                 sorted[ i ] = m;
  2129.  
  2130.         if (i == 0) {
  2131.                 fprintf (stderr, "No events.\n");
  2132.                 return;
  2133.         }
  2134.  
  2135.         qsort ((char *) sorted, i, sizeof (struct memevent *), de_cmpf);
  2136.  
  2137.         sorted[ i ] = 0;
  2138.         for (i = 0, m = sorted[ 0 ]; m != NULL; m = sorted[ ++i ]) {
  2139.                 fprintf (stderr, "E# %3d: ", m->m_id);
  2140.                 fprintf (stderr, "SIZ%4d, ", m->m_size);
  2141.                 fprintf (stderr, "RANGE: 0x%08x -- 0x%08x ",
  2142.                                 m->m_memory, m->m_memory + m->m_size - 1);
  2143.                 (void) fflush (stderr);
  2144.  
  2145.                                         /* Peek at the surrounding longs,
  2146.                                            for debugging a particular malloc
  2147.                                            implementation.  Your choices may
  2148.                                            vary. */
  2149.  
  2150.                 fprintf (stderr, "BOUNDARY TAGS: %4d ", * (long *) (m->m_memory - 4));
  2151.                 (void) fflush (stderr);
  2152.                 fprintf (stderr, "%4d\n", * (long *) ((m->m_memory - 8) - (* (long *) (m->m_memory - 4))));
  2153.                 (void) fflush (stderr);
  2154.         }
  2155.         fprintf (stderr, "END DUMP_EVENTS\n");
  2156.         (void) fflush (stderr);
  2157. } /* dump_events */
  2158. #endif DBG
  2159. @@@End of mtest2.c
  2160. echo x - mtest3.c 1>&2
  2161. cat >mtest3.c <<'@@@End of mtest3.c'
  2162. /* NOT copyright by SoftQuad Inc. -- msb, 1988 */
  2163. #ifndef lint
  2164. static char *SQ_SccsId = "@(#)mtest3.c    1.2 88/08/25";
  2165. #endif
  2166. #include <stdio.h>
  2167. /*
  2168. ** looptest.c -- intensive allocator tester 
  2169. **
  2170. ** Usage:  looptest
  2171. **
  2172. ** History:
  2173. **    4-Feb-1987 rtech!daveb 
  2174. */
  2175.  
  2176.  
  2177. # ifdef SYS5
  2178. # define random    rand
  2179. # else
  2180. # include <sys/vadvise.h>
  2181. # endif
  2182.  
  2183. # include <stdio.h>
  2184. # include <signal.h>
  2185. # include <setjmp.h>
  2186.  
  2187. # define MAXITER    1000000        /* main loop iterations */
  2188. # define MAXOBJS    1000        /* objects in pool */
  2189. # define BIGOBJ        90000        /* max size of a big object */
  2190. # define TINYOBJ    80        /* max size of a small object */
  2191. # define BIGMOD        100        /* 1 in BIGMOD is a BIGOBJ */
  2192. # define STATMOD    10000        /* interation interval for status */
  2193.  
  2194. main( argc, argv )
  2195. int argc;
  2196. char **argv;
  2197. {
  2198.     register int **objs;        /* array of objects */
  2199.     register int *sizes;        /* array of object sizes */
  2200.     register int n;            /* iteration counter */
  2201.     register int i;            /* object index */
  2202.     register int size;        /* object size */
  2203.     register int r;            /* random number */
  2204.  
  2205.     int objmax;            /* max size this iteration */
  2206.     int cnt;            /* number of allocated objects */
  2207.     int nm = 0;            /* number of mallocs */
  2208.     int nre = 0;            /* number of reallocs */
  2209.     int nal;            /* number of allocated objects */
  2210.     int nfre;            /* number of free list objects */
  2211.     long alm;            /* memory in allocated objects */
  2212.     long frem;            /* memory in free list */
  2213.     long startsize;            /* size at loop start */
  2214.     long endsize;            /* size at loop exit */
  2215.     long maxiter = 0;        /* real max # iterations */
  2216.  
  2217.     extern char end;        /* memory before heap */
  2218.     char *calloc();
  2219.     char *malloc();
  2220.     char *sbrk();
  2221.     long atol();
  2222.  
  2223. # ifndef SYS5
  2224.     /* your milage may vary... */
  2225.     vadvise( VA_ANOM );
  2226. # endif
  2227.  
  2228.     if (argc > 1)
  2229.         maxiter = atol (argv[1]);
  2230.     if (maxiter <= 0)
  2231.         maxiter = MAXITER;
  2232.  
  2233.     printf("MAXITER %d MAXOBJS %d ", maxiter, MAXOBJS );
  2234.     printf("BIGOBJ %d, TINYOBJ %d, nbig/ntiny 1/%d\n",
  2235.     BIGOBJ, TINYOBJ, BIGMOD );
  2236.     fflush( stdout );
  2237.  
  2238.     if( NULL == (objs = (int **)calloc( MAXOBJS, sizeof( *objs ) ) ) )
  2239.     {
  2240.         fprintf(stderr, "Can't allocate memory for objs array\n");
  2241.         exit(1);
  2242.     }
  2243.  
  2244.     if( NULL == ( sizes = (int *)calloc( MAXOBJS, sizeof( *sizes ) ) ) )
  2245.     {
  2246.         fprintf(stderr, "Can't allocate memory for sizes array\n");
  2247.         exit(1);
  2248.     }
  2249.  
  2250.     /* as per recent discussion on net.lang.c, calloc does not 
  2251.     ** necessarily fill in NULL pointers...
  2252.     */
  2253.     for( i = 0; i < MAXOBJS; i++ )
  2254.         objs[ i ] = NULL;
  2255.  
  2256.     startsize = sbrk(0) - &end;
  2257.     printf( "Memory use at start: %d bytes\n", startsize );
  2258.     fflush(stdout);
  2259.  
  2260.     printf("Starting the test...\n");
  2261.     fflush(stdout);
  2262.     for( n = 0; n < maxiter ; n++ )
  2263.     {
  2264.         if( !(n % STATMOD) )
  2265.         {
  2266.             printf("%d iterations\n", n);
  2267.             fflush(stdout);
  2268.         }
  2269.  
  2270.         /* determine object of interst and it's size */
  2271.  
  2272.         r = random();
  2273.         objmax = ( r % BIGMOD ) ? TINYOBJ : BIGOBJ;
  2274.         size = r % objmax;
  2275.         i = r % (MAXOBJS - 1);
  2276.  
  2277.         /* either replace the object of get a new one */
  2278.  
  2279.         if( objs[ i ] == NULL )
  2280.         {
  2281.             objs[ i ] = (int *)malloc( size );
  2282.             nm++;
  2283.         }
  2284.         else
  2285.         {
  2286.             /* don't keep bigger objects around */
  2287.             if( size > sizes[ i ] )
  2288.             {
  2289.                 objs[ i ] = (int *)realloc( objs[ i ], size );
  2290.                 nre++;
  2291.             }
  2292.             else
  2293.             {
  2294.                 free( objs[ i ] );
  2295.                 objs[ i ] = (int *)malloc( size );
  2296.                 nm++;
  2297.             }
  2298.         }
  2299.  
  2300.         sizes[ i ] = size;
  2301.         if( objs[ i ] == NULL )
  2302.         {
  2303.             printf("\nCouldn't allocate %d byte object!\n", 
  2304.                 size );
  2305.             break;
  2306.         }
  2307.     } /* for() */
  2308.  
  2309.     printf( "\n" );
  2310.     cnt = 0;
  2311.     for( i = 0; i < MAXOBJS; i++ )
  2312.         if( objs[ i ] )
  2313.             cnt++;
  2314.  
  2315.     printf( "Did %d iterations, %d objects, %d mallocs, %d reallocs\n",
  2316.         n, cnt, nm, nre );
  2317.     printf( "Memory use at end: %d bytes\n", sbrk(0) - &end );
  2318.     fflush( stdout );
  2319.  
  2320.     /* free all the objects */
  2321.     for( i = 0; i < MAXOBJS; i++ )
  2322.         if( objs[ i ] != NULL )
  2323.             free( objs[ i ] );
  2324.  
  2325.     endsize = sbrk(0) - &end;
  2326.     printf( "Memory use after free: %d bytes\n", endsize );
  2327.     fflush( stdout );
  2328.  
  2329.     if( startsize != endsize )
  2330.         printf("startsize %d != endsize %d\n", startsize, endsize );
  2331.  
  2332.     free( objs );
  2333.     free( sizes );
  2334.  
  2335.     exit( 0 );
  2336. }
  2337.  
  2338. @@@End of mtest3.c
  2339. echo x - realloc.c 1>&2
  2340. cat >realloc.c <<'@@@End of realloc.c'
  2341. #include "malloc.h"
  2342. #define NULL 0
  2343.  
  2344. /* NOT copyright by SoftQuad. - msb, 1988 */
  2345. #ifndef lint
  2346. static char *SQ_SccsId = "@(#)realloc.c    1.7 88/08/24";
  2347. #endif
  2348. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2349.  *  realloc                William L. Sebok
  2350.  * A  "smarter" malloc v1.0        Sept. 24, 1984 rev. Oct 17,1986
  2351.  *            Then modified by Arthur David Olsen
  2352.  *            MALLOCTRACE added by Mark Brader
  2353.  *
  2354.  *    realloc takes previously malloc-allocated area at mem, and tries
  2355.  *     to change its size to nbytes bytes, moving it and copying its
  2356.  *     contents if necessary.
  2357.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2358.  
  2359. #ifdef    MALLOCTRACE    /* See ./TRACE_README */
  2360. unsigned old_nbytes;
  2361. #endif
  2362.  
  2363. char *
  2364. realloc(mem,nbytes)
  2365. register char *mem; unsigned nbytes;    /* for 4.3 compat. */
  2366.  
  2367. #ifdef    MALLOCTRACE
  2368.     /*
  2369.      * The (real) realloc function may call malloc or not; we want
  2370.      * to generate a trace message from here if it doesn't.  And
  2371.      * likewise for free.  Since the function is somewhat complicated,
  2372.      * this goal is most easily achieved by wrapping a dummy realloc
  2373.      * function -- this one -- around the real realloc.  The real
  2374.      * realloc is imaginatively renamed real_realloc.
  2375.      */
  2376. {
  2377.  
  2378.     char *real_realloc(), *newmem;
  2379.     Size new_nbytes;
  2380.     extern enum _malstate _malstate;
  2381.  
  2382. #define    BYTES(mem)    (((struct overhead *)(mem - sizeof(struct overhead))) \
  2383.         ->ov_length)    /* How realloc finds the allocated length */
  2384.  
  2385.     old_nbytes = 0;        /* Normally changed in real_realloc */
  2386.  
  2387.     if (_malstate == S_INITIAL) _mal_init_trace();
  2388.  
  2389.     if (_malstate == S_TRACING)
  2390.         _malstate = S_IN_REALLOC;
  2391.  
  2392.     newmem = real_realloc (mem, nbytes);
  2393.  
  2394.     if (_malstate == S_IN_REALLOC) {
  2395.         _malstate = S_TRACING;
  2396.  
  2397.         if (newmem) new_nbytes = BYTES (newmem);
  2398.         _mal_write_trace ("realloc", (Size) old_nbytes,
  2399.                         (Size) old_nbytes, mem);
  2400.         _mal_write_trace ("realloc-to", (Size) nbytes,
  2401.                         (Size) new_nbytes, newmem);
  2402.     }
  2403.  
  2404.     return newmem;
  2405. }
  2406.  
  2407.     /*
  2408.      * And now, the real realloc.  If MALLOCTRACE is not defined,
  2409.      * this function will of course compile as realloc.
  2410.      */
  2411.  
  2412. static char *
  2413. real_realloc(mem,nbytes)
  2414. register char *mem; unsigned nbytes;
  2415.  
  2416. #endif
  2417. {
  2418.     register char *newmem = NULL;
  2419.     register struct overhead *p;
  2420.     Size surplus, length;
  2421.     Size oldlength;
  2422.  
  2423.     if (mem == NULL)
  2424.         return(malloc(nbytes));
  2425.  
  2426.     /* if beyond current arena it has to be bad */
  2427.     if (mem > (char*)FROMADJ(adjhead.q_back) + sizeof(struct overhead))
  2428.         return(NULL);
  2429.     
  2430.     p = (struct overhead *)(mem - sizeof(struct overhead));
  2431.  
  2432.     if (p->ov_magic != MAGIC_BUSY && p->ov_magic != MAGIC_FREE)
  2433.         return(NULL);    /* already gone */
  2434.  
  2435.     oldlength = p->ov_length;
  2436.  
  2437. #ifdef    MALLOCTRACE
  2438.     old_nbytes = oldlength;
  2439. #endif
  2440.  
  2441.     nbytes = ((nbytes + (NALIGN-1)) & (~(NALIGN-1)))
  2442.          + sizeof(struct overhead);
  2443.  
  2444.     if (p->ov_magic == MAGIC_BUSY) {
  2445.         /* free may claim adjacent free memory, compacting storage */
  2446.         char oendfree = endfree;
  2447.         endfree = 0;
  2448.         free(mem);    /* free it but don't let it contract break */
  2449.         endfree = oendfree;
  2450.         if (p->ov_magic != MAGIC_FREE) {    /* check if moved */
  2451.             p = FROMADJ(p->ov_adj.q_back);
  2452.             newmem = (char *)p + sizeof(struct overhead);
  2453.         }
  2454.     }
  2455.  
  2456.     /* at this point p->ov_magic should be MAGIC_FREE */
  2457.     ASSERT(p->ov_magic == MAGIC_FREE, "\nrealloc: bad magic number.\n");
  2458.  
  2459.     /*
  2460.     ** We wait to set length until after any possible compaction.
  2461.     */
  2462.     length = p->ov_length;
  2463.     surplus = length - nbytes;
  2464.     if (surplus >= 0) {
  2465.         /* present location large enough */
  2466.         remque(TOBUK(p));
  2467.         p->ov_magic = MAGIC_BUSY;
  2468.     } else if ( ((char *)p + p->ov_length) == CURBRK) {
  2469.         /* if at break, grow in place */
  2470.         (void) BRK((char *)p + nbytes);
  2471.         p->ov_length = nbytes;
  2472.         remque(TOBUK(p));
  2473.         p->ov_magic = MAGIC_BUSY;
  2474.     } else {
  2475.         newmem = malloc(nbytes - sizeof(struct overhead));
  2476.         if (newmem == NULL)
  2477.             return(NULL);
  2478.         surplus = 0;
  2479.     }
  2480.  
  2481.     /* if returned address is different, move data */
  2482.     if (newmem != NULL) {
  2483.         /* note: it is assumed that bcopy does the right thing on
  2484.          * overlapping extents (true on the vax)
  2485.          */
  2486.         (void)bcopy(mem, newmem,
  2487.             ((oldlength < nbytes) ? oldlength : nbytes) -
  2488.                 sizeof(struct overhead));
  2489.          mem = newmem;
  2490.     }
  2491.  
  2492.     /* if more memory than we need then return excess to buckets */
  2493.     if (surplus > (int) sizeof(struct overhead)) {
  2494.         register struct overhead *q;
  2495.         q = (struct overhead *)( (char *)p + nbytes);
  2496.         q->ov_length = surplus;
  2497.         q->ov_magic = MAGIC_FREE;
  2498.         insque(TOADJ(q),TOADJ(p));
  2499.         {
  2500.             register struct qelem *    bp;
  2501.  
  2502.             bp = &buckets[mlindx(surplus)];
  2503.             if (bp > hifreebp)
  2504.                 hifreebp = bp;
  2505.             insque(TOBUK(q),bp);
  2506.         }
  2507.         p->ov_length -= surplus;
  2508.     }
  2509.  
  2510.     if (endfree)
  2511.         mlfree_end();
  2512.  
  2513.     return(mem);
  2514. }
  2515. @@@End of realloc.c
  2516. echo x - write_trace.c 1>&2
  2517. cat >write_trace.c <<'@@@End of write_trace.c'
  2518. #ifdef    MALLOCTRACE
  2519.  
  2520.  
  2521. /* NOT copyright by SoftQuad. - msb, 1988 */
  2522. #ifndef lint
  2523. static char *SQ_SccsId = "@(#)write_trace.c    1.4 88/08/24";
  2524. #endif
  2525. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2526.  *  _mal_write_trace                See ./ORIGINS for credits
  2527.  *
  2528.  *     _mal_write_trace writes a line to the malloc trace file.
  2529.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2530.  
  2531. #include    <stdio.h>
  2532. #include    "malloc.h"
  2533.  
  2534. /* Machine-dependent stuff:  the Sun's stack format. */
  2535.  
  2536. struct    stackframe {
  2537.     struct stackframe    *link;
  2538.     char            *ret_addr;
  2539. };
  2540.  
  2541. typedef struct stackframe    *FRAMEPTR;
  2542.  
  2543. #define    MYFRAME(myfirstarg)     ((FRAMEPTR) (((Size *) &(myfirstarg)) - 2))
  2544.  
  2545. #define    NEXTFRAME(myframe)    ((myframe)->link)
  2546. #define    RET_ADDR(myframe)    ((myframe)->ret_addr)
  2547.  
  2548. /* Test whether a stdio file is still writable */
  2549.  
  2550. #define    STDIO_WRITABLE(fp)    (((fp)->_flag & _IOWRT) != NULL)
  2551.  
  2552.  
  2553. void
  2554. _mal_write_trace (event_label, req_nbytes, act_nbytes, mem)
  2555. char *event_label;
  2556. Size req_nbytes, act_nbytes;
  2557. char *mem;
  2558. {
  2559.     extern enum _malstate _malstate;
  2560.     extern FILE *_malfp;
  2561.     extern int _malbuff;
  2562.     FRAMEPTR frame;
  2563.  
  2564.     if (_malstate != S_TRACING || !STDIO_WRITABLE(_malfp))
  2565.         return;
  2566.  
  2567.     /* Reset the state in case stdio does any mallocing */
  2568.     _malstate = S_IN_STDIO;
  2569.  
  2570.     if (req_nbytes == act_nbytes)
  2571.         fprintf (_malfp, "%s of %ld at %ld\n",
  2572.             event_label, (long) req_nbytes, (long) mem);
  2573.     else
  2574.         fprintf (_malfp, "%s of %ld gets %ld at %ld\n",
  2575.             event_label, (long) req_nbytes, (long) act_nbytes,
  2576.                                 (long) mem);
  2577.  
  2578.     for (frame = NEXTFRAME (MYFRAME (event_label));
  2579.             frame;
  2580.             frame = NEXTFRAME (frame))
  2581.             
  2582.         fprintf (_malfp, "caller %8.8lx\n", (long) RET_ADDR (frame));
  2583.  
  2584.     fprintf (_malfp, "\n");
  2585.  
  2586.     /* Flush if desired */
  2587.     if (!_malbuff) fflush (_malfp);
  2588.  
  2589.     /* And back to normal */
  2590.     _malstate = S_TRACING;
  2591. }
  2592. #endif
  2593. @@@End of write_trace.c
  2594. echo x - Makefile 1>&2
  2595. cat >Makefile <<'@@@End of Makefile'
  2596. #
  2597. #    SQ sccsid @(#)Makefile    1.4 88/08/25
  2598. #    NOT copyright by SoftQuad.  - msb, 1988
  2599. #
  2600. # This is configured to make the traced version of malloc; see mallck(1)
  2601. # and ./TRACE_README.  To make the regular version, delete -DMALLOCTRACE.
  2602. #                            Mark Brader
  2603. #
  2604.  
  2605. CARGS= -O -DMALLOCTRACE
  2606.  
  2607. MALLOC_C    = malloc.c free.c realloc.c forget.c write_trace.c init_trace.c
  2608. MALLOC_O    = malloc.o free.o realloc.o forget.o write_trace.o init_trace.o
  2609.  
  2610. all:    malloctrace.a
  2611.  
  2612. mtests:    mtest1 mtest2 mtest3
  2613.  
  2614. install: malloctrace.a
  2615.     mv malloctrace.a /usr/lib/malloctrace.a
  2616.     
  2617. .c.o:    $*.c
  2618.     ${CC} -c ${CARGS} $*.c
  2619.  
  2620. $(MALLOC_O):    malloc.h
  2621.  
  2622. malloctrace.a:    $(MALLOC_O)
  2623.     ar rv malloctrace.a $(MALLOC_O)
  2624.     ranlib malloctrace.a
  2625.  
  2626. mtest1:    mtest1.c
  2627.  
  2628. mtest2:    mtest2.c
  2629.  
  2630. mtest3:    mtest3.c
  2631.  
  2632. mtest1 mtest2 mtest3:    malloctrace.a
  2633.     ${CC} -O $@.c malloctrace.a -o $@
  2634.  
  2635. clean:
  2636.     rm -f *.o tstmalloc core
  2637. @@@End of Makefile
  2638. exit 0
  2639.