source: trunk/dll/fortify.c@ 1078

Last change on this file since 1078 was 1078, checked in by Steven Levine, 17 years ago

More Fortify infrastructure enhancements
Rework Fortify_SetOwner
Add Fortify_BecomeOwner
Avoid more spurious leak reports

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.0 KB
Line 
1
2/* $Id: fortify.c 1078 2008-07-19 04:08:02Z stevenhl $ */
3/* fortify.cxx - A fortified memory allocation shell - V2.2 */
4 /* vim: tabs 4 */
5
6/*
7 * This software is not public domain. All material in
8 * this archive is (C) Copyright 1995 Simon P. Bullen. The
9 * software is freely distributable, with the condition that
10 * no more than a nominal fee is charged for media.
11 * Everything in this distribution must be kept together, in
12 * original, unmodified form.
13 * The software may be modified for your own personal use,
14 * but modified files may not be distributed.
15 * The material is provided "as is" without warranty of
16 * any kind. The author accepts no responsibility for damage
17 * caused by this software.
18 * This software may not be used in any way by Microsoft
19 * Corporation or its subsidiaries, or current employees of
20 * Microsoft Corporation or its subsidiaries.
21 * This software may not be used for the construction,
22 * development, production, or testing of weapon systems of
23 * any kind.
24 * This software may not be used for the construction,
25 * development, production, or use of plants/installations
26 * which include the processing of radioactive/fissionable
27 * material.
28 */
29
30/*
31 * If you use this software at all, I'd love to hear from
32 * you. All questions, criticisms, suggestions, praise and
33 * postcards are most welcome.
34 *
35 * email: sbullen@cybergraphic.com.au
36 *
37 * snail: Simon P. Bullen
38 * PO BOX 12138
39 * A'Beckett St.
40 * Melbourne 3000
41 * Australia
42 */
43
44 /* 06 May 08 SHL Rework scope logic to be MT capable
45 26 May 08 SHL Show TID for leaking scope
46 17 Jul 08 SHL Add Fortify_PresetOwner Fortify_BecomeOwner Fortify_ChangeScope
47 18 Jul 08 SHL Add FORTIFY_VERBOSE_SCOPE_ENTER_EXIT
48 18 Jul 08 SHL Add Fortify_SetScope
49 18 Jul 08 SHL Rename Fortify_ChangeOwner to Fortify_BecomeOwner
50 18 Jul 08 SHL Add reworked Fortify_SetOwner
51 */
52
53#ifdef FORTIFY
54
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58#include <assert.h>
59#include <math.h>
60#include <ctype.h>
61#include <time.h>
62
63
64/* the user's options */
65#include "ufortify.h"
66
67/* Prototypes and such */
68#define __FORTIFY_C__ // Suppress malloc replacement etc.
69#include "fortify.h"
70
71
72#ifdef MT_SCOPES
73unsigned long Get_TID_Ordinal(void);
74// Get tib_ptib2 from TIB
75// Get thread id from TIB2
76#pragma aux Get_TID_Ordinal = \
77 "mov ebx, fs:[0xc]" \
78 "mov eax, [ebx+0]" \
79 modify exact [eax ebx] \
80 value [eax]
81#endif
82
83/*
84 * Round x up to the nearest multiple of n.
85 */
86#define ROUND_UP(x, n) ((((x) + (n)-1)/(n))*(n))
87
88/*
89 * struct Header - this structure is used
90 * internally by Fortify to manage it's
91 * own private lists of memory.
92 */
93struct Header
94{
95 unsigned short Checksum; /* For the integrity of our goodies */
96 const char *File; /* The sourcefile of the allocator */
97 unsigned long Line; /* The sourceline of the allocator */
98# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
99 const char *FreedFile; /* The sourcefile of the deallocator */
100 unsigned long FreedLine; /* The sourceline of the deallocator */
101 unsigned char Deallocator; /* The deallocator used */
102# endif
103 size_t Size; /* The size of the malloc'd block */
104 struct Header *Prev; /* Previous link */
105 struct Header *Next; /* Next link */
106 char *Label; /* User's Label (may be null) */
107 unsigned char Scope; /* Scope level of the owner */
108 unsigned char Allocator; /* malloc/realloc/new/etc */
109# ifdef MT_SCOPES
110 unsigned short Owner; /* TID ordinal of block owner */
111# endif
112};
113
114#define FORTIFY_HEADER_SIZE ROUND_UP(sizeof(struct Header), sizeof(unsigned short))
115
116
117/*
118 * FORTIFY_ALIGNED_BEFORE_SIZE is FORTIFY_BEFORE_SIZE rounded up to the
119 * next multiple of FORTIFY_ALIGNMENT. This is so that we can guarantee
120 * the alignment of user memory for such systems where this is important
121 * (eg storing doubles on a SPARC)
122 */
123#define FORTIFY_ALIGNED_BEFORE_SIZE ( \
124 ROUND_UP(FORTIFY_HEADER_SIZE + FORTIFY_BEFORE_SIZE, FORTIFY_ALIGNMENT) \
125 - FORTIFY_HEADER_SIZE)
126
127/*
128 * FORTIFY_OVERHEAD is the total overhead added by Fortify to each
129 * memory block.
130 */
131#define FORTIFY_OVERHEAD ( FORTIFY_HEADER_SIZE \
132 + FORTIFY_ALIGNED_BEFORE_SIZE \
133 + FORTIFY_AFTER_SIZE)
134
135
136/*
137 *
138 * Static Function Prototypes
139 *
140 */
141static int st_CheckBlock(struct Header *h, const char *file, unsigned long line);
142static int st_CheckFortification (unsigned char *ptr, unsigned char value, size_t size);
143static void st_SetFortification (unsigned char *ptr, unsigned char value, size_t size);
144static void st_OutputFortification(unsigned char *ptr, unsigned char value, size_t size);
145static void st_HexDump(unsigned char *ptr, size_t offset, size_t size, int title);
146static int st_IsHeaderValid(struct Header *h);
147static void st_MakeHeaderValid(struct Header *h);
148static unsigned short st_ChecksumHeader(struct Header *h);
149static int st_IsOnAllocatedList(struct Header *h);
150static void st_OutputHeader(struct Header *h);
151static void st_OutputMemory(struct Header *h);
152static void st_OutputLastVerifiedPoint(void);
153static void st_DefaultOutput(const char *String);
154static const char *st_MemoryBlockString(struct Header *h);
155static void st_OutputDeleteTrace();
156
157#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
158#ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
159
160#ifdef FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
161static const char *st_DeallocatedMemoryBlockString(struct Header *h);
162#endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
163
164#endif /* FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
165static int st_IsOnDeallocatedList(struct Header *h);
166static int st_PurgeDeallocatedBlocks(unsigned long Bytes, const char *file, unsigned long line);
167static int st_PurgeDeallocatedScope(unsigned char Scope, const char *file, unsigned long line);
168static int st_CheckDeallocatedBlock(struct Header *h, const char *file, unsigned long line);
169static void st_FreeDeallocatedBlock(struct Header *h, const char *file, unsigned long line);
170#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
171
172
173/*
174 *
175 * Static variables
176 *
177 */
178static struct Header *st_AllocatedHead;
179static int st_AllocateFailRate;
180static char st_Buffer[256];
181static Fortify_OutputFuncPtr st_Output = st_DefaultOutput;
182static const char *st_LastVerifiedFile = "unknown";
183static unsigned long st_LastVerifiedLine;
184
185#ifdef MT_SCOPES
186static unsigned volatile st_cOrdinals; // Number of known threads
187static volatile unsigned char* st_pScopes; // Scope level of blocks allocated by thread
188static volatile unsigned long* st_pOwners; // Owner of blocks allocated by thread
189#else
190static unsigned char st_Scope = 0;
191#endif
192
193static unsigned char st_Disabled = 0;
194
195#ifdef __cplusplus
196int FORTIFY_STORAGE gbl_FortifyMagic = 0; // 28 Jan 08 SHL
197static const char *st_DeleteFile[FORTIFY_DELETE_STACK_SIZE];
198static unsigned long st_DeleteLine[FORTIFY_DELETE_STACK_SIZE];
199static unsigned long st_DeleteStackTop;
200#endif /* __cplusplus */
201
202/* statistics */
203static unsigned long st_MaxBlocks = 0;
204static unsigned long st_MaxAllocation = 0;
205static unsigned long st_CurBlocks = 0;
206static unsigned long st_CurAllocation = 0;
207static unsigned long st_Allocations = 0;
208static unsigned long st_Frees = 0;
209static unsigned long st_TotalAllocation = 0;
210static unsigned long st_AllocationLimit = 0xffffffff;
211
212#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
213static struct Header *st_DeallocatedHead = 0;
214static struct Header *st_DeallocatedTail = 0;
215static unsigned long st_TotalDeallocated = 0;
216#endif
217
218
219/* allocators */
220static const char *st_AllocatorName[] =
221{
222 "malloc()",
223 "calloc()",
224 "realloc()",
225 "strdup()",
226 "new",
227 "new[]"
228};
229
230/* deallocators */
231static const char *st_DeallocatorName[] =
232{
233 "nobody",
234 "free()",
235 "realloc()",
236 "delete",
237 "delete[]"
238};
239
240static const unsigned char st_ValidDeallocator[] =
241{
242 (1<<Fortify_Deallocator_free) | (1<<Fortify_Deallocator_realloc),
243 (1<<Fortify_Deallocator_free) | (1<<Fortify_Deallocator_realloc),
244 (1<<Fortify_Deallocator_free) | (1<<Fortify_Deallocator_realloc),
245 (1<<Fortify_Deallocator_free) | (1<<Fortify_Deallocator_realloc),
246#if defined(FORTIFY_PROVIDE_ARRAY_NEW) && defined(FORTIFY_PROVIDE_ARRAY_DELETE)
247 (1<<Fortify_Deallocator_delete),
248 (1<<Fortify_Deallocator_array_delete)
249#else
250 (1<<Fortify_Deallocator_delete) | (1<<Fortify_Deallocator_array_delete),
251 (1<<Fortify_Deallocator_delete) | (1<<Fortify_Deallocator_array_delete)
252#endif
253};
254
255
256/*
257 * Fortify_Allocate() - allocate a block of fortified memory
258 */
259void *FORTIFY_STORAGE
260Fortify_Allocate(size_t size, unsigned char allocator, const char *file, unsigned long line)
261{
262 unsigned char *ptr;
263 struct Header *h;
264 int another_try;
265
266#ifdef MT_SCOPES
267 unsigned ordinal;
268#endif
269
270 /*
271 * If Fortify has been disabled, then it's easy
272 */
273 if(st_Disabled)
274 {
275# ifdef FORTIFY_FAIL_ON_ZERO_MALLOC
276 if(size == 0 && (allocator == Fortify_Allocator_new
277 || allocator == Fortify_Allocator_array_new))
278 {
279 /*
280 * A new of zero bytes must succeed, but a malloc of
281 * zero bytes probably won't
282 */
283 return malloc(1);
284 }
285# endif
286
287 return malloc(size);
288 }
289
290#ifdef FORTIFY_CHECK_ALL_MEMORY_ON_ALLOCATE
291 Fortify_CheckAllMemory(file, line);
292#endif
293
294 if(st_AllocateFailRate > 0)
295 {
296 if(rand() % 100 < st_AllocateFailRate)
297 {
298# ifdef FORTIFY_WARN_ON_FALSE_FAIL
299 sprintf(st_Buffer,
300 "\nFortify: A \"%s\" of %lu bytes \"false failed\" at %s.%lu\n",
301 st_AllocatorName[allocator], (unsigned long)size, file, line);
302 st_Output(st_Buffer);
303# endif
304 return(0);
305 }
306 }
307
308 /* Check to see if this allocation will
309 * push us over the artificial limit
310 */
311 if(st_CurAllocation + size > st_AllocationLimit)
312 {
313# ifdef FORTIFY_WARN_ON_FALSE_FAIL
314 sprintf(st_Buffer,
315 "\nFortify: A \"%s\" of %lu bytes \"false failed\" at %s.%lu\n",
316 st_AllocatorName[allocator], (unsigned long)size, file, line);
317 st_Output(st_Buffer);
318# endif
319 return(0);
320 }
321
322#ifdef FORTIFY_WARN_ON_ZERO_MALLOC
323 if(size == 0 && (allocator == Fortify_Allocator_malloc ||
324 allocator == Fortify_Allocator_calloc ||
325 allocator == Fortify_Allocator_realloc ))
326 {
327 sprintf(st_Buffer,
328 "\nFortify: A \"%s\" of 0 bytes attempted at %s.%lu\n",
329 st_AllocatorName[allocator], file, line);
330 st_Output(st_Buffer);
331 }
332#endif /* FORTIFY_WARN_ON_ZERO_MALLOC */
333
334#ifdef FORTIFY_FAIL_ON_ZERO_MALLOC
335 if(size == 0 && (allocator == Fortify_Allocator_malloc ||
336 allocator == Fortify_Allocator_calloc ||
337 allocator == Fortify_Allocator_realloc ))
338 {
339#ifdef FORTIFY_WARN_ON_ALLOCATE_FAIL
340 sprintf(st_Buffer, "\nFortify: A \"%s\" of %lu bytes failed at %s.%lu\n",
341 st_AllocatorName[allocator], (unsigned long)size, file, line);
342 st_Output(st_Buffer);
343#endif /* FORTIFY_WARN_ON_ALLOCATE_FAIL */
344 return 0;
345 }
346#endif /* FORTIFY_FAIL_ON_ZERO_MALLOC */
347
348#ifdef FORTIFY_WARN_ON_SIZE_T_OVERFLOW
349 /*
350 * Ensure the size of the memory block
351 * plus the overhead isn't bigger than
352 * size_t (that'd be a drag)
353 */
354 {
355 size_t private_size = FORTIFY_HEADER_SIZE
356 + FORTIFY_ALIGNED_BEFORE_SIZE + size + FORTIFY_AFTER_SIZE;
357
358 if(private_size < size)
359 {
360 sprintf(st_Buffer,
361 "\nFortify: A \"%s\" of %lu bytes has overflowed size_t at %s.%lu\n",
362 st_AllocatorName[allocator], (unsigned long)size, file, line);
363 st_Output(st_Buffer);
364 return(0);
365 }
366 }
367#endif
368
369 another_try = 1;
370 do
371 {
372 /*
373 * malloc the memory, including the space
374 * for the header and fortification buffers
375 */
376 ptr = (unsigned char *)malloc( FORTIFY_HEADER_SIZE
377 + FORTIFY_ALIGNED_BEFORE_SIZE
378 + size
379 + FORTIFY_AFTER_SIZE );
380
381# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
382 /*
383 * If we're tracking deallocated memory, then
384 * we can free some of it, rather than let
385 * this malloc fail
386 */
387 if(!ptr)
388 {
389 another_try = st_PurgeDeallocatedBlocks(size, file, line);
390 }
391# endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
392
393 }
394 while(!ptr && another_try);
395
396 if(!ptr)
397 {
398# ifdef FORTIFY_WARN_ON_ALLOCATE_FAIL
399 sprintf(st_Buffer, "\nFortify: A \"%s\" of %lu bytes failed at %s.%lu\n",
400 st_AllocatorName[allocator], (unsigned long)size, file, line);
401 st_Output(st_Buffer);
402# endif
403 return(0);
404 }
405
406 /*
407 * Begin Critical Region
408 */
409 FORTIFY_LOCK();
410
411
412 /*
413 * Make the head's prev pointer point to us
414 * ('cos we're about to become the head)
415 */
416 if(st_AllocatedHead)
417 {
418 st_CheckBlock(st_AllocatedHead, file, line);
419 /* what should we do if this fails? (apart from panic) */
420
421 st_AllocatedHead->Prev = (struct Header *)ptr;
422 st_MakeHeaderValid(st_AllocatedHead);
423 }
424
425# ifdef MT_SCOPES
426 ordinal = Get_TID_Ordinal();
427# endif
428
429 /*
430 * Initialize and validate the header
431 */
432 h = (struct Header *)ptr;
433 h->Size = size;
434 h->File = file;
435 h->Line = line;
436 h->Next = st_AllocatedHead;
437 h->Prev = 0;
438# ifdef MT_SCOPES
439 h->Owner = ordinal < st_cOrdinals ? st_pOwners[ordinal] : ordinal;
440 h->Scope = h->Owner < st_cOrdinals ? st_pScopes[h->Owner] : 0;
441# else
442 h->Scope = st_Scope;
443# endif
444 h->Allocator = allocator;
445 h->Label = 0;
446#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
447 h->FreedFile = 0;
448 h->FreedLine = 0;
449 h->Deallocator = Fortify_Deallocator_nobody;
450#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
451 st_MakeHeaderValid(h);
452 st_AllocatedHead = h;
453
454 /*
455 * Initialize the fortifications
456 */
457 st_SetFortification(ptr + FORTIFY_HEADER_SIZE,
458 FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
459 st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + size,
460 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
461
462# ifdef FORTIFY_FILL_ON_ALLOCATE
463 /*
464 * Fill the actual user memory
465 */
466 st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
467 FORTIFY_FILL_ON_ALLOCATE_VALUE, size);
468# endif
469
470 /*
471 * End Critical Region
472 */
473 FORTIFY_UNLOCK();
474
475
476 /*
477 * update the statistics
478 */
479 st_TotalAllocation += size;
480 st_Allocations++;
481 st_CurBlocks++;
482 st_CurAllocation += size;
483 if(st_CurBlocks > st_MaxBlocks)
484 st_MaxBlocks = st_CurBlocks;
485 if(st_CurAllocation > st_MaxAllocation)
486 st_MaxAllocation = st_CurAllocation;
487
488 /*
489 * We return the address of the user's memory, not the start of the block,
490 * which points to our magic cookies
491 */
492 return(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE);
493}
494
495
496
497/*
498 * Fortify_Deallocate() - Free a block of memory allocated with Fortify_Allocate()
499 */
500void FORTIFY_STORAGE
501Fortify_Deallocate(void *uptr, unsigned char deallocator, const char *file, unsigned long line)
502{
503 unsigned char *ptr = (unsigned char *)uptr
504 - FORTIFY_HEADER_SIZE
505 - FORTIFY_ALIGNED_BEFORE_SIZE;
506 struct Header *h = (struct Header *)ptr;
507
508# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
509# ifdef MT_SCOPES
510 unsigned ordinal = Get_TID_Ordinal();
511# endif
512# endif
513
514# ifdef FORTIFY_CHECK_ALL_MEMORY_ON_DEALLOCATE
515 Fortify_CheckAllMemory(file, line);
516# endif
517
518 /*
519 * If Fortify has been disabled, then it's easy
520 * (well, almost)
521 */
522 if(st_Disabled)
523 {
524 /* there is a possibility that this memory
525 * block was allocated when Fortify was
526 * enabled, so we must check the Allocated
527 * list before we free it.
528 */
529 if(!st_IsOnAllocatedList(h))
530 {
531 free(uptr);
532 return;
533 }
534 else
535 {
536 /* the block was allocated by Fortify, so we
537 * gotta free it differently.
538 */
539 /*
540 * Begin critical region
541 */
542 FORTIFY_LOCK();
543
544 /*
545 * Remove the block from the list
546 */
547 if(h->Prev)
548 h->Prev->Next = h->Next;
549 else
550 st_AllocatedHead = h->Next;
551
552 if(h->Next)
553 h->Next->Prev = h->Prev;
554
555 /*
556 * End Critical Region
557 */
558 FORTIFY_UNLOCK();
559
560 /*
561 * actually free the memory
562 */
563 free(ptr);
564 return;
565 }
566 }
567
568
569# ifdef FORTIFY_PARANOID_DEALLOCATE
570 if(!st_IsOnAllocatedList(h))
571 {
572# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
573 if(st_IsOnDeallocatedList(h))
574 {
575 sprintf(st_Buffer, "\nFortify: \"%s\" twice of %s detected at %s.%lu\n",
576 st_DeallocatorName[deallocator],
577 st_MemoryBlockString(h), file, line);
578 st_Output(st_Buffer);
579
580 sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
581 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
582 st_Output(st_Buffer);
583 st_OutputDeleteTrace();
584 return;
585 }
586# endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
587
588# ifdef FORTIFY_NO_PERCENT_P
589 sprintf(st_Buffer, "\nFortify: Possible \"%s\" twice of (0x%08lx) was detected at %s.%lu\n",
590# else
591 sprintf(st_Buffer, "\nFortify: Possible \"%s\" twice of (%p) was detected at %s.%lu\n",
592# endif
593 st_DeallocatorName[deallocator],
594 uptr, file, line);
595 st_Output(st_Buffer);
596 st_OutputDeleteTrace();
597 return;
598 }
599# endif /* FORTIFY_PARANOID_DEALLOCATE */
600
601 /*
602 * Make sure the block is okay before we free it.
603 * If it's not okay, don't free it - it might not
604 * be a real memory block. Or worse still, someone
605 * might still be writing to it
606 */
607 if(!st_CheckBlock(h, file, line))
608 {
609 st_OutputDeleteTrace();
610 return;
611 }
612
613# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
614 /*
615 * Make sure the block hasn't been freed already
616 * (we can get to here if FORTIFY_PARANOID_DEALLOCATE
617 * is off, but FORTIFY_TRACK_DEALLOCATED_MEMORY
618 * is on).
619 */
620 if(h->Deallocator != Fortify_Deallocator_nobody)
621 {
622 sprintf(st_Buffer, "\nFortify: \"%s\" twice of %s detected at %s.%lu\n",
623 st_DeallocatorName[deallocator],
624 st_MemoryBlockString(h), file, line);
625 st_Output(st_Buffer);
626
627 sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
628 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
629 st_Output(st_Buffer);
630 st_OutputDeleteTrace();
631 return;
632 }
633# endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
634
635 /*
636 * Make sure the block is being freed with a valid
637 * deallocator. If not, complain. (but free it anyway)
638 */
639 if((st_ValidDeallocator[h->Allocator] & (1<<deallocator)) == 0)
640 {
641 sprintf(st_Buffer, "\nFortify: Incorrect deallocator \"%s\" detected at %s.%lu\n",
642 st_DeallocatorName[deallocator], file, line);
643 st_Output(st_Buffer);
644 sprintf(st_Buffer, " %s was allocated with \"%s\"\n",
645 st_MemoryBlockString(h), st_AllocatorName[h->Allocator]);
646 st_Output(st_Buffer);
647 st_OutputDeleteTrace();
648 }
649
650 /*
651 * Begin critical region
652 */
653 FORTIFY_LOCK();
654
655 /*
656 * Remove the block from the list
657 */
658 if(h->Prev)
659 {
660 if(!st_CheckBlock(h->Prev, file, line))
661 {
662 FORTIFY_UNLOCK();
663 st_OutputDeleteTrace();
664 return;
665 }
666
667 h->Prev->Next = h->Next;
668 st_MakeHeaderValid(h->Prev);
669 }
670 else
671 st_AllocatedHead = h->Next;
672
673 if(h->Next)
674 {
675 if(!st_CheckBlock(h->Next, file, line))
676 {
677 FORTIFY_UNLOCK();
678 st_OutputDeleteTrace();
679 return;
680 }
681
682 h->Next->Prev = h->Prev;
683 st_MakeHeaderValid(h->Next);
684 }
685
686 /*
687 * End Critical Region
688 */
689 FORTIFY_UNLOCK();
690
691 /*
692 * update the statistics
693 */
694 st_Frees++;
695 st_CurBlocks--;
696 st_CurAllocation -= h->Size;
697
698#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
699#ifdef MT_SCOPES
700 ordinal = Get_TID_Ordinal();
701 if (ordinal < st_cOrdinals && st_pScopes[ordinal] > 0)
702#else
703 if(st_Scope > 0)
704#endif
705 {
706 /*
707 * Don't _actually_ free the memory block, just yet.
708 * Place it onto the deallocated list, instead, so
709 * we can check later to see if it's been written to.
710 */
711# ifdef FORTIFY_FILL_ON_DEALLOCATE
712 /*
713 * Nuke out all user memory that is about to be freed
714 */
715 st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
716 FORTIFY_FILL_ON_DEALLOCATE_VALUE,
717 h->Size);
718# endif /* FORTIFY_FILL_ON_DEALLOCATE */
719
720 /*
721 * Begin critical region
722 */
723 FORTIFY_LOCK();
724
725 /*
726 * Place the block on the deallocated list
727 */
728 if(st_DeallocatedHead)
729 {
730 st_DeallocatedHead->Prev = (struct Header *)ptr;
731 st_MakeHeaderValid(st_DeallocatedHead);
732 }
733
734 h = (struct Header *)ptr;
735 h->FreedFile = file;
736 h->FreedLine = line;
737 h->Deallocator = deallocator;
738 h->Next = st_DeallocatedHead;
739 h->Prev = 0;
740 st_MakeHeaderValid(h);
741 st_DeallocatedHead = h;
742
743 if(!st_DeallocatedTail)
744 st_DeallocatedTail = h;
745
746 st_TotalDeallocated += h->Size;
747
748# ifdef FORTIFY_DEALLOCATED_MEMORY_LIMIT
749 /*
750 * If we've got too much on the deallocated list; free some
751 */
752 if(st_TotalDeallocated > FORTIFY_DEALLOCATED_MEMORY_LIMIT)
753 {
754 st_PurgeDeallocatedBlocks(st_TotalDeallocated - FORTIFY_DEALLOCATED_MEMORY_LIMIT, file, line);
755 }
756# endif
757
758 /*
759 * End critical region
760 */
761 FORTIFY_UNLOCK();
762 }
763 else
764# endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
765 {
766 /*
767 * Free the User Label
768 */
769 if(h->Label)
770 {
771 free(h->Label);
772 }
773
774# ifdef FORTIFY_FILL_ON_DEALLOCATE
775 /*
776 * Nuke out all memory that is about to be freed, including the header
777 */
778 st_SetFortification(ptr, FORTIFY_FILL_ON_DEALLOCATE_VALUE,
779 FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size + FORTIFY_AFTER_SIZE);
780# endif /* FORTIFY_FILL_ON_DEALLOCATE */
781
782 /*
783 * And do the actual free
784 */
785 free(ptr);
786 }
787}
788
789
790/*
791 * Fortify_LabelPointer() - Labels the memory block
792 * with a string provided by the user. This function
793 * takes a copy of the passed in string.
794 * The block MUST be one returned by a Fortify
795 * allocation function.
796 */
797void
798Fortify_LabelPointer(void *uptr, const char *label, const char *file, unsigned long line)
799{
800 if(!st_Disabled)
801 {
802 unsigned char *ptr = (unsigned char *)uptr
803 - FORTIFY_HEADER_SIZE - FORTIFY_ALIGNED_BEFORE_SIZE;
804 struct Header *h = (struct Header *)ptr;
805
806 /* make sure the pointer is okay */
807 Fortify_CheckPointer(uptr, file, line);
808
809 /* free the previous label */
810 if(h->Label)
811 {
812 free(h->Label);
813 }
814
815 /* make sure the label is sensible */
816 assert(label);
817
818 /* copy it in */
819 h->Label = (char*)malloc(strlen(label)+1);
820 strcpy(h->Label, label);
821
822 /* update the checksum */
823 st_MakeHeaderValid(h);
824 }
825}
826
827/*
828 * Fortify_CheckPointer() - Returns true if the uptr
829 * points to a valid piece of Fortify_Allocated()'d
830 * memory. The memory must be on the allocated list,
831 * and it's fortifications must be intact.
832 * Always returns TRUE if Fortify is disabled.
833 */
834int FORTIFY_STORAGE
835Fortify_CheckPointer(void *uptr, const char *file, unsigned long line)
836{
837 unsigned char *ptr = (unsigned char *)uptr
838 - FORTIFY_HEADER_SIZE - FORTIFY_ALIGNED_BEFORE_SIZE;
839 struct Header *h = (struct Header *)ptr;
840 int r;
841
842 if(st_Disabled)
843 return 1;
844
845 FORTIFY_LOCK();
846
847 if(!st_IsOnAllocatedList(h))
848 {
849# ifdef FORTIFY_NO_PERCENT_P
850 sprintf(st_Buffer, "\nFortify: Invalid pointer (0x%08lx) detected at %s.%lu\n",
851 uptr, file, line);
852# else
853 sprintf(st_Buffer, "\nFortify: Invalid pointer (%p) detected at %s.%lu\n",
854 uptr, file, line);
855# endif
856 st_Output(st_Buffer);
857 FORTIFY_UNLOCK();
858 return(0);
859 }
860
861#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
862 if(st_IsOnDeallocatedList(h))
863 {
864# ifdef FORTIFY_NO_PERCENT_P
865 sprintf(st_Buffer, "\nFortify: Deallocated pointer (0x%08lx) detected at %s.%lu\n",
866 uptr, file, line);
867# else
868 sprintf(st_Buffer, "\nFortify: Deallocated pointer (%p) detected at %s.%lu\n",
869 uptr, file, line);
870# endif
871 st_Output(st_Buffer);
872 sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
873 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
874 st_Output(st_Buffer);
875 FORTIFY_UNLOCK();
876 return(0);
877 }
878#endif
879
880 r = st_CheckBlock(h, file, line);
881 FORTIFY_UNLOCK();
882 return r;
883}
884
885/*
886 * Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output) -
887 * Sets the function used to output all error and
888 * diagnostic messages. The output function takes
889 * a single const unsigned char * argument, and must be
890 * able to handle newlines. This function returns the
891 * old output function.
892 */
893Fortify_OutputFuncPtr FORTIFY_STORAGE
894Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output)
895{
896 Fortify_OutputFuncPtr Old = st_Output;
897
898 st_Output = Output;
899
900 return(Old);
901}
902
903/*
904 * Fortify_SetAllocateFailRate(int Percent) -
905 * Fortify_Allocate() will "fail" this Percent of
906 * the time, even if the memory is available.
907 * Useful to "stress-test" an application.
908 * Returns the old value.
909 * The fail rate defaults to 0 (a good default I think).
910 */
911int FORTIFY_STORAGE
912Fortify_SetAllocateFailRate(int Percent)
913{
914 int Old = st_AllocateFailRate;
915
916 st_AllocateFailRate = Percent;
917
918 return(Old);
919}
920
921
922/*
923 * Fortify_CheckAllMemory() - Checks the fortifications
924 * of all memory on the allocated list. And, if
925 * FORTIFY_DEALLOCATED_MEMORY is enabled, all the
926 * known deallocated memory as well.
927 * Returns the number of blocks that failed.
928 * Always returns 0 if Fortify is disabled.
929 */
930unsigned long FORTIFY_STORAGE
931Fortify_CheckAllMemory(const char *file, unsigned long line)
932{
933 struct Header *curr = st_AllocatedHead;
934 unsigned long count = 0;
935
936 if(st_Disabled)
937 return 0;
938
939 FORTIFY_LOCK();
940
941 /*
942 * Check the allocated memory
943 */
944 while(curr)
945 {
946 if(!st_CheckBlock(curr, file, line))
947 count++;
948
949 curr = curr->Next;
950 }
951
952 /*
953 * Check the deallocated memory while you're at it
954 */
955# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
956 curr = st_DeallocatedHead;
957 while(curr)
958 {
959 if(!st_CheckDeallocatedBlock(curr, file, line))
960 count++;
961
962 curr = curr->Next;
963 }
964# endif
965
966 /*
967 * If we know where we are, and everything is cool,
968 * remember that. It might be important.
969 */
970 if(file && count == 0)
971 {
972 st_LastVerifiedFile = file;
973 st_LastVerifiedLine = line;
974 }
975
976 FORTIFY_UNLOCK();
977 return(count);
978}
979
980
981/*
982 * Fortify_EnterScope() - enters a new Fortify scope
983 * level. Returns the new scope level.
984 */
985unsigned char FORTIFY_STORAGE
986Fortify_EnterScope(const char *file, unsigned long line)
987{
988#ifdef MT_SCOPES
989 unsigned ordinal = Get_TID_Ordinal();
990 unsigned i;
991 unsigned c;
992
993 if (ordinal >= st_cOrdinals) {
994 // Expand arrays
995 FORTIFY_LOCK();
996 i = st_cOrdinals;
997 c = ordinal + 1;
998 st_pScopes = realloc((void*)st_pScopes, sizeof(*st_pScopes) * c);
999 st_pOwners = realloc((void*)st_pOwners, sizeof(*st_pOwners) * c);
1000 for (; i <= ordinal; i++) {
1001 st_pScopes[i] = 0; // Default to scope level 0
1002 st_pOwners[i] = i; // Default block owner to self
1003 }
1004 st_cOrdinals = c;
1005 FORTIFY_UNLOCK();
1006 }
1007 i = ++st_pScopes[ordinal];
1008# ifdef FORTIFY_VERBOSE_SCOPE_ENTER_EXIT
1009 sprintf(st_Buffer,
1010 "Fortify: Entering scope %u in TID %u at %s.%lu\n",
1011 i, ordinal,
1012 file, line); // 26 May 08 SHL
1013 st_Output(st_Buffer);
1014# endif
1015 return(i);
1016#else
1017 return(++st_Scope);
1018#endif
1019}
1020
1021/* Fortify_LeaveScope - leaves a Fortify scope level,
1022 * also prints a memory dump of all non-freed memory
1023 * that was allocated during the scope being exited.
1024 * Does nothing and returns 0 if Fortify is disabled.
1025 */
1026unsigned char FORTIFY_STORAGE
1027Fortify_LeaveScope(const char *file, unsigned long line)
1028{
1029 struct Header *curr = st_AllocatedHead;
1030 unsigned long size = 0, count = 0;
1031# ifdef MT_SCOPES
1032 unsigned ordinal;
1033# endif
1034
1035 if(st_Disabled)
1036 return 0;
1037
1038 FORTIFY_LOCK();
1039
1040# ifdef MT_SCOPES
1041 // Complain on leave without enter 06 May 08 SHL
1042 ordinal = Get_TID_Ordinal();
1043 if (ordinal < st_cOrdinals && st_pScopes[ordinal] > 0) {
1044 st_pScopes[ordinal]--;
1045 }
1046 else {
1047 sprintf(st_Buffer,
1048 "\nFortify: Attempting to leave scope before enter in TID %u at %s.%lu\n",
1049 ordinal, file, line); // 26 May 08 SHL
1050 st_Output(st_Buffer);
1051 }
1052# else
1053 if (st_Scope > 0)
1054 st_Scope--;
1055 else {
1056 sprintf(st_Buffer, "\nFortify: Attempting to leave scope before enter at %s.%lu\n", file, line);
1057 st_Output(st_Buffer);
1058 }
1059#endif
1060 while(curr)
1061 {
1062# ifdef MT_SCOPES
1063 if(curr->Owner == ordinal && ordinal < st_cOrdinals && curr->Scope > st_pScopes[ordinal])
1064# else
1065 if(curr->Scope > st_Scope)
1066# endif
1067 {
1068 if(count == 0)
1069 {
1070 // Output leak report and header just once
1071# ifdef MT_SCOPES
1072 sprintf(st_Buffer,
1073 "\nFortify: Memory leak detected leaving scope %d in TID %u at %s.%lu\n",
1074 ordinal < st_cOrdinals ? st_pScopes[ordinal] + 1 : 0,
1075 ordinal,
1076 file, line);
1077# else // not MT_SCOPES
1078 sprintf(st_Buffer, "\nFortify: Memory leak detected leaving scope at %s.%lu\n", file, line);
1079# endif
1080 st_Output(st_Buffer);
1081 sprintf(st_Buffer, "%10s %8s %s\n", "Address", "Size", "Allocator");
1082 st_Output(st_Buffer);
1083 }
1084
1085 st_OutputHeader(curr);
1086 count++;
1087 size += curr->Size;
1088 }
1089
1090 curr = curr->Next;
1091 } // while
1092
1093 if(count)
1094 {
1095 sprintf(st_Buffer,"%10s %8lu bytes in %lu blocks with %lu bytes overhead\n",
1096 "total", size, count, count * FORTIFY_OVERHEAD);
1097 st_Output(st_Buffer);
1098 }
1099# ifdef FORTIFY_VERBOSE_SCOPE_ENTER_EXIT
1100 else {
1101 sprintf(st_Buffer,
1102 "Fortify: Leaving scope %u in TID %u at %s.%lu\n",
1103 ordinal < st_cOrdinals ? st_pScopes[ordinal] + 1 : 0,
1104 ordinal,
1105 file, line); // 26 May 08 SHL
1106 st_Output(st_Buffer);
1107 }
1108# endif
1109
1110# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
1111 /*
1112 * Quietly free all the deallocated memory
1113 * that was allocated in this scope that
1114 * we are still tracking
1115 */
1116# ifdef MT_SCOPES
1117 st_PurgeDeallocatedScope( ordinal < st_cOrdinals ? st_pScopes[ordinal] : 0,
1118 file, line );
1119# else
1120 st_PurgeDeallocatedScope( st_Scope, file, line );
1121# endif
1122# endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
1123
1124 FORTIFY_UNLOCK();
1125# ifdef MT_SCOPES
1126 return(ordinal < st_cOrdinals ? st_pScopes[ordinal] : 0);
1127# else
1128 return(st_Scope);
1129# endif
1130}
1131
1132/*
1133 * Fortify_ListAllMemory() - Outputs the entire
1134 * list of currently allocated memory. For each block
1135 * is output it's Address, Size, and the SourceFile and
1136 * Line that allocated it.
1137 *
1138 * If there is no memory on the list, this function
1139 * outputs nothing.
1140 *
1141 * It returns the number of blocks on the list, unless
1142 * Fortify has been disabled, in which case it always
1143 * returns 0.
1144 */
1145unsigned long FORTIFY_STORAGE
1146Fortify_ListAllMemory(const char *file, unsigned long line)
1147{
1148 struct Header *curr = st_AllocatedHead;
1149 unsigned long size = 0, count = 0;
1150
1151 if(st_Disabled)
1152 return 0;
1153
1154 Fortify_CheckAllMemory(file, line);
1155
1156 FORTIFY_LOCK();
1157
1158 if(curr)
1159 {
1160 sprintf(st_Buffer, "\nFortify: Memory List at %s.%lu\n", file, line);
1161 st_Output(st_Buffer);
1162 sprintf(st_Buffer, "%10s %8s %s\n", "Address", "Size", "Allocator");
1163 st_Output(st_Buffer);
1164
1165 while(curr)
1166 {
1167 st_OutputHeader(curr);
1168 count++;
1169 size += curr->Size;
1170 curr = curr->Next;
1171 }
1172
1173 sprintf(st_Buffer, "%10s %8lu bytes in %lu blocks and %lu bytes overhead\n",
1174 "total", size, count, count * FORTIFY_OVERHEAD);
1175 st_Output(st_Buffer);
1176 }
1177
1178 FORTIFY_UNLOCK();
1179 return(count);
1180}
1181
1182/*
1183 * Fortify_DumpAllMemory() - Outputs the entire list of
1184 * currently allocated memory. For each allocated block
1185 * is output it's Address, Size, the SourceFile and Line
1186 * that allocated it, a hex dump of the contents of the
1187 * memory and an ascii dump of printable characters.
1188 *
1189 * If there is no memory on the list, this function outputs nothing.
1190 */
1191unsigned long FORTIFY_STORAGE
1192Fortify_DumpAllMemory(const char *file, unsigned long line)
1193{
1194 struct Header *curr = st_AllocatedHead;
1195 unsigned long count = 0;
1196
1197 if(st_Disabled)
1198 return 0;
1199
1200 Fortify_CheckAllMemory(file, line);
1201
1202 FORTIFY_LOCK();
1203
1204 while(curr)
1205 {
1206 sprintf(st_Buffer, "\nFortify: Hex Dump of %s at %s.%lu\n",
1207 st_MemoryBlockString(curr), file, line);
1208 st_Output(st_Buffer);
1209 st_OutputMemory(curr);
1210 st_Output("\n");
1211 count++;
1212
1213 curr = curr->Next;
1214 }
1215
1216 FORTIFY_UNLOCK();
1217 return(count);
1218}
1219
1220/* Fortify_OutputStatistics() - displays statistics
1221 * about the maximum amount of memory that was
1222 * allocated at any one time.
1223 */
1224void FORTIFY_STORAGE
1225Fortify_OutputStatistics(const char *file, unsigned long line)
1226{
1227 if(st_Disabled)
1228 return;
1229
1230 sprintf(st_Buffer, "\nFortify: Statistics at %s.%lu\n", file, line);
1231 st_Output(st_Buffer);
1232
1233 sprintf(st_Buffer, " Memory currently allocated: %lu bytes in %lu blocks\n",
1234 st_CurAllocation, st_CurBlocks);
1235 st_Output(st_Buffer);
1236 sprintf(st_Buffer, " Maximum memory allocated at one time: %lu bytes in %lu blocks\n",
1237 st_MaxAllocation, st_MaxBlocks);
1238 st_Output(st_Buffer);
1239 sprintf(st_Buffer, " There have been %lu allocations and %lu deallocations\n",
1240 st_Allocations, st_Frees);
1241 st_Output(st_Buffer);
1242 sprintf(st_Buffer, " There was a total of %lu bytes allocated\n",
1243 st_TotalAllocation);
1244 st_Output(st_Buffer);
1245
1246 if(st_Allocations > 0)
1247 {
1248 sprintf(st_Buffer, " The average allocation was %lu bytes\n",
1249 st_TotalAllocation / st_Allocations);
1250 st_Output(st_Buffer);
1251 }
1252}
1253
1254/* Fortify_GetCurrentAllocation() - returns the number of
1255 * bytes currently allocated.
1256 */
1257unsigned long FORTIFY_STORAGE
1258Fortify_GetCurrentAllocation(const char *file, unsigned long line)
1259{
1260 if(st_Disabled)
1261 return 0;
1262
1263 return st_CurAllocation;
1264}
1265
1266/* Fortify_SetAllocationLimit() - set a limit on the total
1267 * amount of memory allowed for this application.
1268 */
1269void FORTIFY_STORAGE
1270Fortify_SetAllocationLimit(unsigned long NewLimit, const char *file, unsigned long line)
1271{
1272 st_AllocationLimit = NewLimit;
1273}
1274
1275/*
1276 * Fortify_Disable() - Run time method of disabling Fortify.
1277 * Useful if you need to turn off Fortify without recompiling
1278 * everything. Not as effective as compiling out, of course.
1279 * The less memory allocated by Fortify when it is disabled
1280 * the better.
1281 * (Previous versions of Fortify did not allow it to be
1282 * disabled if there was any memory allocated at the time,
1283 * but since in C++ memory is often allocated before main
1284 * is even entered, this was useless so Fortify is now
1285 * able to cope).
1286 */
1287void FORTIFY_STORAGE
1288Fortify_Disable(const char *file, unsigned long line)
1289{
1290# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
1291 /* free all deallocated memory we might be tracking */
1292 st_PurgeDeallocatedScope( 0, file, line );
1293# endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
1294
1295 st_Disabled = 1;
1296}
1297
1298
1299
1300/*
1301 * st_CheckBlock - Check a block's header and fortifications.
1302 * Returns true if the block is happy.
1303 */
1304static int
1305st_CheckBlock(struct Header *h, const char *file, unsigned long line)
1306{
1307 unsigned char *ptr = (unsigned char *)h;
1308 int result = 1;
1309
1310 if(!st_IsHeaderValid(h))
1311 {
1312# ifdef FORTIFY_NO_PERCENT_P
1313 sprintf(st_Buffer,
1314 "\nFortify: Invalid pointer (0x%08lx) or corrupted header detected at %s.%lu\n",
1315 ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE, file, line);
1316# else
1317 sprintf(st_Buffer,
1318 "\nFortify: Invalid pointer (%p) or corrupted header detected at %s.%lu\n",
1319 ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE, file, line);
1320# endif
1321 st_Output(st_Buffer);
1322 st_OutputLastVerifiedPoint();
1323 return(0);
1324 }
1325
1326 if(!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE,
1327 FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE))
1328 {
1329 sprintf(st_Buffer, "\nFortify: Underwrite detected before block %s at %s.%lu\n",
1330 st_MemoryBlockString(h), file, line);
1331 st_Output(st_Buffer);
1332
1333 st_OutputLastVerifiedPoint();
1334 st_OutputFortification(ptr + FORTIFY_HEADER_SIZE,
1335 FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
1336 result = 0;
1337
1338# ifdef FORTIFY_FILL_ON_CORRUPTION
1339 st_SetFortification(ptr + FORTIFY_HEADER_SIZE, FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
1340# endif
1341 }
1342
1343 if(!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
1344 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE))
1345 {
1346 sprintf(st_Buffer, "\nFortify: Overwrite detected after block %s at %s.%lu\n",
1347 st_MemoryBlockString(h), file, line);
1348 st_Output(st_Buffer);
1349
1350 st_OutputLastVerifiedPoint();
1351 st_OutputFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
1352 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
1353 result = 0;
1354
1355# ifdef FORTIFY_FILL_ON_CORRUPTION
1356 st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
1357 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
1358# endif
1359 }
1360
1361 return(result);
1362}
1363
1364#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
1365
1366/*
1367 * st_CheckDeallocatedBlock - Check a deallocated block's header and fortifications.
1368 * Returns true if the block is happy.
1369 */
1370static int
1371st_CheckDeallocatedBlock(struct Header *h, const char *file, unsigned long line)
1372{
1373 unsigned char *ptr = (unsigned char *)h;
1374 int result = 1;
1375
1376 if(!st_IsHeaderValid(h))
1377 {
1378#ifdef FORTIFY_NO_PERCENT_P
1379 sprintf(st_Buffer,
1380 "\nFortify: Invalid deallocated pointer (0x%08lx) or corrupted header detected at %s.%lu\n",
1381 ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE, file, line);
1382#else
1383 sprintf(st_Buffer,
1384 "\nFortify: Invalid deallocated pointer (%p) or corrupted header detected at %s.%lu\n",
1385 ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE, file, line);
1386#endif
1387 st_Output(st_Buffer);
1388 st_OutputLastVerifiedPoint();
1389 return(0);
1390 }
1391
1392 if(!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE,
1393 FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE))
1394 {
1395 sprintf(st_Buffer, "\nFortify: Underwrite detected before deallocated block %s at %s.%lu\n",
1396 st_MemoryBlockString(h), file, line);
1397 st_Output(st_Buffer);
1398 sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
1399 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
1400 st_Output(st_Buffer);
1401
1402 st_OutputLastVerifiedPoint();
1403 st_OutputFortification(ptr + FORTIFY_HEADER_SIZE,
1404 FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
1405
1406# ifdef FORTIFY_FILL_ON_CORRUPTION
1407 st_SetFortification(ptr + FORTIFY_HEADER_SIZE, FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
1408# endif
1409 result = 0;
1410 }
1411
1412 if(!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
1413 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE))
1414 {
1415 sprintf(st_Buffer, "\nFortify: Overwrite detected after deallocated block %s at %s.%lu\n",
1416 st_MemoryBlockString(h), file, line);
1417 st_Output(st_Buffer);
1418 sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
1419 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
1420 st_Output(st_Buffer);
1421
1422 st_OutputLastVerifiedPoint();
1423 st_OutputFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
1424 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
1425
1426# ifdef FORTIFY_FILL_ON_CORRUPTION
1427 st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
1428 FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
1429# endif
1430 result = 0;
1431 }
1432
1433#ifdef FORTIFY_FILL_ON_DEALLOCATE
1434 if(!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1435 FORTIFY_FILL_ON_DEALLOCATE_VALUE, h->Size))
1436 {
1437 sprintf(st_Buffer, "\nFortify: Write to deallocated block %s detected at %s.%lu\n",
1438 st_MemoryBlockString(h), file, line);
1439 st_Output(st_Buffer);
1440
1441 sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
1442 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
1443 st_Output(st_Buffer);
1444 st_OutputLastVerifiedPoint();
1445
1446 st_OutputFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1447 FORTIFY_FILL_ON_DEALLOCATE_VALUE, h->Size);
1448
1449# ifdef FORTIFY_FILL_ON_CORRUPTION
1450 st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1451 FORTIFY_FILL_ON_DEALLOCATE_VALUE, h->Size);
1452# endif /* FORTIFY_FILL_ON_CORRUPTION */
1453 result = 0;
1454 }
1455#endif /* FORTIFY_FILL_ON_DEALLOCATE */
1456 return result;
1457 }
1458
1459#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
1460
1461
1462/*
1463 * st_CheckFortification - Checks if the _size_
1464 * bytes from _ptr_ are all set to _value_
1465 * Returns true if all is happy.
1466 */
1467static int
1468st_CheckFortification(unsigned char *ptr, unsigned char value, size_t size)
1469{
1470 while(size--)
1471 if(*ptr++ != value)
1472 return(0);
1473
1474 return(1);
1475}
1476
1477/*
1478 * st_SetFortification - Set the _size_ bytes from _ptr_ to _value_.
1479 */
1480static void
1481st_SetFortification(unsigned char *ptr, unsigned char value, size_t size)
1482{
1483 memset(ptr, value, size);
1484}
1485
1486/*
1487 * st_OutputFortification - Output the corrupted section of the fortification
1488 */
1489static void
1490st_OutputFortification(unsigned char *ptr, unsigned char value, size_t size)
1491{
1492 size_t offset, skipped, advance;
1493 offset = 0;
1494
1495 sprintf(st_Buffer, " Address Offset Data (%02x)", value);
1496 st_Output(st_Buffer);
1497
1498 while(offset < size)
1499 {
1500 /*
1501 * Skip 3 or more 'correct' lines
1502 */
1503 if((size - offset) < 3 * 16)
1504 advance = size - offset;
1505 else
1506 advance = 3 * 16;
1507 if(advance > 0 && st_CheckFortification(ptr+offset, value, advance))
1508 {
1509 offset += advance;
1510 skipped = advance;
1511
1512 if(size - offset < 16)
1513 advance = size - offset;
1514 else
1515 advance = 16;
1516
1517 while(advance > 0 && st_CheckFortification(ptr+offset, value, advance))
1518 {
1519 offset += advance;
1520 skipped += advance;
1521 if(size - offset < 16)
1522 advance = size - offset;
1523 else
1524 advance = 16;
1525 }
1526 sprintf(st_Buffer, "\n ...%lu bytes skipped...", (unsigned long)skipped);
1527 st_Output(st_Buffer);
1528 continue;
1529 }
1530 else
1531 {
1532 if(size - offset < 16)
1533 st_HexDump(ptr, offset, size-offset, 0);
1534 else
1535 st_HexDump(ptr, offset, 16, 0);
1536
1537 offset += 16;
1538 }
1539 }
1540
1541 st_Output("\n");
1542}
1543
1544/*
1545 * st_HexDump - output a nice hex dump of "size" bytes, starting at "ptr" + "offset"
1546 */
1547static void
1548st_HexDump(unsigned char *ptr, size_t offset, size_t size, int title)
1549{
1550 char ascii[17];
1551 int column;
1552 int output;
1553
1554 if(title)
1555 st_Output(" Address Offset Data");
1556
1557 column = 0;
1558 ptr += offset;
1559 output = 0;
1560
1561 while(output < size)
1562 {
1563 if(column == 0)
1564 {
1565# ifdef FORTIFY_NO_PERCENT_P
1566 sprintf(st_Buffer, "\n0x%08lx %8lu ", ptr, (unsigned long)offset);
1567# else
1568 sprintf(st_Buffer, "\n%10p %8lu ", ptr, (unsigned long)offset);
1569# endif
1570 st_Output(st_Buffer);
1571 }
1572
1573 sprintf(st_Buffer, "%02x%s", *ptr, ((column % 4) == 3) ? " " : "");
1574 st_Output(st_Buffer);
1575
1576 ascii[ column ] = isprint( *ptr ) ? (char)(*ptr) : (char)('.');
1577 ascii[ column + 1 ] = '\0';
1578
1579 ptr++;
1580 offset++;
1581 output++;
1582 column++;
1583
1584 if(column == 16)
1585 {
1586 st_Output( " \"" );
1587 st_Output( ascii );
1588 st_Output( "\"" );
1589 column = 0;
1590 }
1591 }
1592
1593 if ( column != 0 )
1594 {
1595 while ( column < 16 )
1596 {
1597 if( column % 4 == 3 )
1598 st_Output( " " );
1599 else
1600 st_Output( " " );
1601
1602 column++;
1603 }
1604 st_Output( " \"" );
1605 st_Output( ascii );
1606 st_Output( "\"" );
1607 }
1608}
1609
1610/*
1611 * st_IsHeaderValid - Returns true if the
1612 * supplied pointer does indeed point to a
1613 * real Header
1614 */
1615static int
1616st_IsHeaderValid(struct Header *h)
1617{
1618 return(st_ChecksumHeader(h) == FORTIFY_CHECKSUM_VALUE);
1619}
1620
1621/*
1622 * st_MakeHeaderValid - Updates the checksum
1623 * to make the header valid
1624 */
1625static void
1626st_MakeHeaderValid(struct Header *h)
1627{
1628 h->Checksum = 0;
1629 h->Checksum = (unsigned short)(FORTIFY_CHECKSUM_VALUE - st_ChecksumHeader(h));
1630}
1631
1632/*
1633 * st_ChecksumHeader - Calculate (and return)
1634 * the checksum of the header. (Including the
1635 * Checksum field itself. If all is well, the
1636 * checksum returned by this function should
1637 * be FORTIFY_CHECKSUM_VALUE
1638 */
1639static unsigned short
1640st_ChecksumHeader(struct Header *h)
1641{
1642 unsigned short c, checksum, *p;
1643
1644 for(c = 0, checksum = 0, p = (unsigned short *)h;
1645 c < FORTIFY_HEADER_SIZE/sizeof(unsigned short); c++)
1646 {
1647 checksum += *p++;
1648 }
1649
1650 return(checksum);
1651}
1652
1653/*
1654 * st_IsOnAllocatedList - Examines the allocated
1655 * list to see if the given header is on it.
1656 */
1657static int
1658st_IsOnAllocatedList(struct Header *h)
1659{
1660 struct Header *curr;
1661
1662 curr = st_AllocatedHead;
1663 while(curr)
1664 {
1665 if(curr == h)
1666 return(1);
1667
1668 curr = curr->Next;
1669 }
1670
1671 return(0);
1672}
1673
1674#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
1675/*
1676 * st_IsOnDeallocatedList - Examines the deallocated
1677 * list to see if the given header is on it.
1678 */
1679static int
1680st_IsOnDeallocatedList(struct Header *h)
1681{
1682 struct Header *curr;
1683
1684 curr = st_DeallocatedHead;
1685 while(curr)
1686 {
1687 if(curr == h)
1688 return(1);
1689
1690 curr = curr->Next;
1691 }
1692
1693 return(0);
1694}
1695
1696/*
1697 * st_PurgeDeallocatedBlocks - free at least "Bytes"
1698 * worth of deallocated memory, starting at the
1699 * oldest deallocated block.
1700 * Returns true if any blocks were freed.
1701 */
1702static int
1703st_PurgeDeallocatedBlocks(unsigned long Bytes, const char *file, unsigned long line)
1704{
1705 unsigned long FreedBytes = 0;
1706 unsigned long FreedBlocks = 0;
1707
1708# ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
1709 sprintf(st_Buffer, "\nFortify: Warning - Discarding deallocated memory at %s.%lu\n",
1710 file, line);
1711 st_Output(st_Buffer);
1712# endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
1713
1714 while(st_DeallocatedTail && FreedBytes < Bytes)
1715 {
1716 st_CheckDeallocatedBlock(st_DeallocatedTail, file, line);
1717 FreedBytes += st_DeallocatedTail->Size;
1718 FreedBlocks++;
1719# ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
1720# ifdef FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
1721 sprintf(st_Buffer, " %s\n",
1722 st_DeallocatedMemoryBlockString(st_DeallocatedTail));
1723 st_Output(st_Buffer);
1724# endif /* FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
1725# endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
1726 st_FreeDeallocatedBlock(st_DeallocatedTail, file, line);
1727 }
1728
1729 return FreedBlocks != 0;
1730}
1731
1732/*
1733 * st_PurgeDeallocatedScope - free all deallocated
1734 * memory blocks that were allocated within "Scope"
1735 */
1736static int
1737st_PurgeDeallocatedScope(unsigned char Scope, const char *file, unsigned long line)
1738{
1739 struct Header *curr, *next;
1740 unsigned long FreedBlocks = 0;
1741# ifdef MT_SCOPES
1742 unsigned ordinal = Get_TID_Ordinal();
1743# endif
1744
1745 curr = st_DeallocatedHead;
1746 while(curr)
1747 {
1748 next = curr->Next;
1749# ifdef MT_SCOPES
1750 if(curr->Owner == ordinal && curr->Scope >= Scope)
1751# else
1752 if(curr->Scope >= Scope)
1753# endif
1754 {
1755 st_FreeDeallocatedBlock(curr, file, line);
1756 FreedBlocks++;
1757 }
1758
1759 curr = next;
1760 }
1761
1762 return FreedBlocks != 0;
1763}
1764
1765/*
1766 * st_FreeDeallocatedBlock - actually remove
1767 * a deallocated block from the deallocated
1768 * list, and actually free it's memory.
1769 */
1770static void
1771st_FreeDeallocatedBlock(struct Header *h, const char *file, unsigned long line)
1772{
1773 st_CheckDeallocatedBlock( h, file, line );
1774
1775 /*
1776 * Begin Critical region
1777 */
1778 FORTIFY_LOCK();
1779
1780 st_TotalDeallocated -= h->Size;
1781
1782 if(st_DeallocatedHead == h)
1783 {
1784 st_DeallocatedHead = h->Next;
1785 }
1786
1787 if(st_DeallocatedTail == h)
1788 {
1789 st_DeallocatedTail = h->Prev;
1790 }
1791
1792 if(h->Prev)
1793 {
1794 st_CheckDeallocatedBlock(h->Prev, file, line);
1795 h->Prev->Next = h->Next;
1796 st_MakeHeaderValid(h->Prev);
1797 }
1798
1799 if(h->Next)
1800 {
1801 st_CheckDeallocatedBlock(h->Next, file, line);
1802 h->Next->Prev = h->Prev;
1803 st_MakeHeaderValid(h->Next);
1804 }
1805
1806 /*
1807 * Free the label
1808 */
1809 if(h->Label)
1810 {
1811 free(h->Label);
1812 }
1813
1814 /*
1815 * Nuke out all memory that is about to be freed, including the header
1816 */
1817 st_SetFortification((unsigned char*)h, FORTIFY_FILL_ON_DEALLOCATE_VALUE,
1818 FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size + FORTIFY_AFTER_SIZE);
1819
1820 /*
1821 * And do the actual free
1822 */
1823 free(h);
1824
1825 /*
1826 * End critical region
1827 */
1828 FORTIFY_UNLOCK();
1829}
1830
1831#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
1832
1833/*
1834 * st_OutputMemory - Hex and ascii dump the
1835 * user memory of a block.
1836 */
1837static void
1838st_OutputMemory(struct Header *h)
1839{
1840 st_HexDump((unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1841 0, h->Size, 1);
1842}
1843
1844
1845/*
1846 * st_OutputHeader - Output the header
1847 */
1848static void
1849st_OutputHeader(struct Header *h)
1850{
1851 if(h->Label == NULL)
1852 {
1853# ifdef MT_SCOPES
1854# ifdef FORTIFY_NO_PERCENT_P
1855 sprintf(st_Buffer, "0x%08lx %8lu %s.%lu TID %u\n",
1856 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1857 (unsigned long)h->Size,
1858 h->File, h->Line, h->Owner);
1859# else
1860 sprintf(st_Buffer, "%10p %8lu %s.%lu TID %u\n",
1861 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1862 (unsigned long)h->Size,
1863 h->File, h->Line, h->Owner);
1864# endif
1865# else
1866# ifdef FORTIFY_NO_PERCENT_P
1867 sprintf(st_Buffer, "0x%08lx %8lu %s.%lu\n",
1868 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1869 (unsigned long)h->Size,
1870 h->File, h->Line);
1871# else
1872 sprintf(st_Buffer, "%10p %8lu %s.%lu\n",
1873 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1874 (unsigned long)h->Size,
1875 h->File, h->Line);
1876# endif
1877# endif // MT_SCOPES
1878 }
1879 else
1880 {
1881# ifdef MT_SCOPES
1882# ifdef FORTIFY_NO_PERCENT_P
1883 sprintf(st_Buffer, "%10p %8lu %s.%lu TID %u %s\n",
1884 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1885 (unsigned long)h->Size,
1886 h->File, h->Line, h->Owner, h->Label);
1887#else
1888 sprintf(st_Buffer, "0x%08lx %8lu %s.%lu TID %u %s\n",
1889 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1890 (unsigned long)h->Size,
1891 h->File, h->Line, h->Owner, h->Label);
1892# endif
1893# else // not MT_SCOPES
1894# ifdef FORTIFY_NO_PERCENT_P
1895 sprintf(st_Buffer, "0x%08lx %8lu %s.%lu %s\n",
1896 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1897 (unsigned long)h->Size,
1898 h->File, h->Line, h->Label);
1899# else
1900 sprintf(st_Buffer, "%10p %8lu %s.%lu %s\n",
1901 (unsigned char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1902 (unsigned long)h->Size,
1903 h->File, h->Line, h->Label);
1904# endif
1905# endif // MT_SCOPES
1906 }
1907 st_Output(st_Buffer);
1908}
1909
1910/*
1911 * st_OutputLastVerifiedPoint - output the last
1912 * known point where everything was hoopy.
1913 */
1914static void
1915st_OutputLastVerifiedPoint()
1916{
1917 sprintf(st_Buffer, " Memory integrity was last verified at %s.%lu\n",
1918 st_LastVerifiedFile,
1919 st_LastVerifiedLine);
1920 st_Output(st_Buffer);
1921}
1922
1923/*
1924 * st_MemoryBlockString - constructs a string that
1925 * desribes a memory block. (pointer,size,allocator,label)
1926 */
1927static const char *
1928st_MemoryBlockString(struct Header *h)
1929{
1930 static char st_BlockString[512];
1931
1932 if(h->Label == 0)
1933 {
1934# ifdef FORTIFY_NO_PERCENT_P
1935 sprintf(st_BlockString,"(0x%08lx,%lu,%s.%lu)",
1936 (char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1937 (unsigned long)h->Size, h->File, h->Line);
1938# else
1939 sprintf(st_BlockString,"(%p,%lu,%s.%lu)",
1940 (char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1941 (unsigned long)h->Size, h->File, h->Line);
1942# endif
1943 }
1944 else
1945 {
1946# ifdef FORTIFY_NO_PERCENT_P
1947 sprintf(st_BlockString,"(0x%08lx,%lu,%s.%lu,%s)",
1948 (char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1949 (unsigned long)h->Size, h->File, h->Line, h->Label);
1950# else
1951 sprintf(st_BlockString,"(%p,%lu,%s.%lu,%s)",
1952 (char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1953 (unsigned long)h->Size, h->File, h->Line, h->Label);
1954# endif
1955 }
1956
1957 return st_BlockString;
1958}
1959
1960#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
1961#ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
1962#ifdef FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
1963/*
1964 * st_DeallocatedMemoryBlockString - constructs
1965 * a string that desribes a deallocated memory
1966 * block. (pointer,size,allocator,deallocator)
1967 */
1968
1969static const char *
1970st_DeallocatedMemoryBlockString(struct Header *h)
1971{
1972 static char st_BlockString[256];
1973
1974 if(h->Label == 0)
1975 {
1976 #ifdef FORTIFY_NO_PERCENT_P
1977 sprintf(st_BlockString,"(0x%08lx,%lu,%s.%lu,%s.%lu)",
1978# else
1979 sprintf(st_BlockString,"(%p,%lu,%s.%lu,%s.%lu)",
1980# endif
1981 (char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1982 (unsigned long)h->Size, h->File, h->Line, h->FreedFile, h->FreedLine);
1983 }
1984 else
1985 {
1986# ifdef FORTIFY_NO_PERCENT_P
1987 sprintf(st_BlockString,"(0x%08lx,%lu,%s.%lu,%s.%lu,%s)",
1988# else
1989 sprintf(st_BlockString,"(%p,%lu,%s.%lu,%s.%lu,%s)",
1990# endif
1991 (char*)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
1992 (unsigned long)h->Size, h->File, h->Line, h->FreedFile, h->FreedLine, h->Label);
1993 }
1994
1995 return st_BlockString;
1996}
1997#endif /* FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
1998#endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
1999#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
2000
2001
2002/*
2003 * st_DefaultOutput - the default output function
2004 */
2005static void
2006st_DefaultOutput(const char *String)
2007{
2008 fprintf(stdout, String);
2009 fflush(stdout);
2010}
2011
2012/*
2013 * Fortify_malloc - Fortify's replacement malloc()
2014 */
2015void *FORTIFY_STORAGE
2016Fortify_malloc(size_t size, const char *file, unsigned long line)
2017{
2018 return Fortify_Allocate(size, Fortify_Allocator_malloc, file, line);
2019}
2020
2021/*
2022 * Fortify_realloc - Fortify's replacement realloc()
2023 */
2024void * FORTIFY_STORAGE // 28 Jan 08 SHL
2025Fortify_realloc(void *uptr, size_t new_size, const char *file, unsigned long line)
2026{
2027 unsigned char *ptr = (unsigned char *)uptr - FORTIFY_HEADER_SIZE - FORTIFY_ALIGNED_BEFORE_SIZE;
2028 struct Header *h = (struct Header *)ptr;
2029 void *new_ptr;
2030
2031 /*
2032 * If Fortify is disabled, we gotta do this a little
2033 * differently.
2034 */
2035 if(!st_Disabled)
2036 {
2037 if(!uptr)
2038 return(Fortify_Allocate(new_size, Fortify_Allocator_realloc, file, line));
2039
2040 if(!st_IsOnAllocatedList(h))
2041 {
2042# ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
2043 if(st_IsOnDeallocatedList(h))
2044 {
2045 sprintf(st_Buffer, "\nFortify: Deallocated memory block passed to \"%s\" at %s.%lu\n",
2046 st_AllocatorName[Fortify_Allocator_realloc], file, line);
2047 st_Output(st_Buffer);
2048 sprintf(st_Buffer, " Memory block %s was deallocated by \"%s\" at %s.%lu\n",
2049 st_MemoryBlockString(h),
2050 st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
2051 st_Output(st_Buffer);
2052 return 0;
2053 }
2054# endif
2055
2056 sprintf(st_Buffer,
2057# ifdef FORTIFY_NO_PERCENT_P
2058 "\nFortify: Invalid pointer (0x%08lx) passed to realloc at %s.%lu\n",
2059# else
2060 "\nFortify: Invalid pointer (%p) passed to realloc at %s.%lu\n",
2061# endif
2062 ptr, file, line);
2063 st_Output(st_Buffer);
2064 return 0;
2065 }
2066
2067 if(!st_CheckBlock(h, file, line))
2068 return 0;
2069
2070 new_ptr = Fortify_Allocate(new_size, Fortify_Allocator_realloc, file, line);
2071 if(!new_ptr)
2072 {
2073 return(0);
2074 }
2075
2076 if(h->Size < new_size)
2077 memcpy(new_ptr, uptr, h->Size);
2078 else
2079 memcpy(new_ptr, uptr, new_size);
2080
2081 Fortify_Deallocate(uptr, Fortify_Deallocator_realloc, file, line);
2082 return(new_ptr);
2083 }
2084 else
2085 {
2086 /*
2087 * If the old block was fortified, we can't use normal realloc.
2088 */
2089 if(st_IsOnAllocatedList(h))
2090 {
2091 new_ptr = Fortify_Allocate(new_size, Fortify_Allocator_realloc, file, line);
2092 if(!new_ptr)
2093 return(0);
2094
2095 if(h->Size < new_size)
2096 memcpy(new_ptr, uptr, h->Size);
2097 else
2098 memcpy(new_ptr, uptr, new_size);
2099
2100 Fortify_Deallocate(uptr, Fortify_Deallocator_realloc, file, line);
2101 return(new_ptr);
2102 }
2103 else /* easy */
2104 {
2105 return realloc(uptr, new_size);
2106 }
2107 }
2108}
2109
2110/*
2111 * Fortify_calloc - Fortify's replacement calloc
2112 */
2113void *
2114Fortify_calloc(size_t num, size_t size, const char *file, unsigned long line)
2115{
2116 if(!st_Disabled)
2117 {
2118 void *ptr = Fortify_Allocate(size * num, Fortify_Allocator_calloc, file, line);
2119 if(ptr)
2120 {
2121 memset(ptr, 0, size*num);
2122 }
2123 return ptr;
2124 }
2125 else
2126 {
2127 return calloc(num, size);
2128 }
2129}
2130
2131/*
2132 * Fortify_free - Fortify's replacement free
2133 */
2134void FORTIFY_STORAGE // 28 Jan 08 SHL
2135Fortify_free(void *uptr, const char *file, unsigned long line)
2136{
2137 /* it is defined to be safe to free(0) */
2138 if(uptr == 0)
2139 return;
2140
2141 Fortify_Deallocate(uptr, Fortify_Deallocator_free, file, line);
2142}
2143
2144/*
2145 * Fortify_strdup - Fortify's replacement strdup. Since strdup isn't
2146 * ANSI, it is only provided if FORTIFY_STRDUP is defined.
2147 */
2148#ifdef FORTIFY_STRDUP
2149char *FORTIFY_STORAGE
2150Fortify_strdup(const char *oldStr, const char *file, unsigned long line)
2151{
2152 if(!st_Disabled)
2153 {
2154 char *newStr = (char *)Fortify_Allocate(strlen(oldStr)+1, Fortify_Allocator_strdup, file, line);
2155 if(newStr)
2156 {
2157 strcpy(newStr, oldStr);
2158 }
2159
2160 return newStr;
2161 }
2162 else
2163 {
2164 return strdup(oldStr);
2165 }
2166}
2167#endif /* FORTIFY_STRDUP */
2168
2169static void
2170st_OutputDeleteTrace()
2171{
2172# ifdef __cplusplus
2173 if(st_DeleteStackTop > 1)
2174 {
2175 sprintf(st_Buffer, "Delete Trace: %s.%lu\n", st_DeleteFile[st_DeleteStackTop-1],
2176 st_DeleteLine[st_DeleteStackTop-1]);
2177 st_Output(st_Buffer);
2178 for(int c = st_DeleteStackTop-2; c >= 0; c--)
2179 {
2180 sprintf(st_Buffer, " %s.%lu\n", st_DeleteFile[c],
2181 st_DeleteLine[c]);
2182 st_Output(st_Buffer);
2183 }
2184 }
2185# endif
2186}
2187
2188#ifdef __cplusplus
2189
2190/*
2191 * st_NewHandler() - there is no easy way to get
2192 * the new handler function. And isn't it great
2193 * how the new handler doesn't take a parameter
2194 * giving the size of the request that failed.
2195 * Thanks Bjarne!
2196 */
2197Fortify_NewHandlerFunc
2198st_NewHandler()
2199{
2200 /* get the current handler */
2201 Fortify_NewHandlerFunc handler = set_new_handler(0);
2202
2203 /* and set it back (since we cant
2204 * get it without changing it)
2205 */
2206 set_new_handler(handler);
2207
2208 return handler;
2209}
2210
2211/*
2212 * operator new - Fortify's replacement new,
2213 * without source-code information.
2214 */
2215void *FORTIFY_STORAGE
2216operator new(size_t size)
2217{
2218 void *p;
2219
2220 while((p = Fortify_Allocate(size, Fortify_Allocator_new,
2221 st_AllocatorName[Fortify_Allocator_new], 0)) == 0)
2222 {
2223 if(st_NewHandler())
2224 (*st_NewHandler())();
2225 else
2226 return 0;
2227 }
2228
2229 return p;
2230}
2231
2232/*
2233 * operator new - Fortify's replacement new,
2234 * with source-code information
2235 */
2236void *FORTIFY_STORAGE
2237operator new(size_t size, const char *file, int line)
2238{
2239 void *p;
2240
2241 while((p = Fortify_Allocate(size, Fortify_Allocator_new, file, line)) == 0)
2242 {
2243 if(st_NewHandler())
2244 (*st_NewHandler())();
2245 else
2246 return 0;
2247 }
2248
2249 return p;
2250}
2251
2252#ifdef FORTIFY_PROVIDE_ARRAY_NEW
2253
2254/*
2255 * operator new[], without source-code info
2256 */
2257void *FORTIFY_STORAGE
2258operator new[](size_t size)
2259{
2260 void *p;
2261
2262 while((p = Fortify_Allocate(size, Fortify_Allocator_array_new,
2263 st_AllocatorName[Fortify_Allocator_array_new], 0)) == 0)
2264 {
2265 if(st_NewHandler())
2266 (*st_NewHandler())();
2267 else
2268 return 0;
2269 }
2270
2271 return p;
2272}
2273
2274/*
2275 * operator new[], with source-code info
2276 */
2277void *FORTIFY_STORAGE
2278operator new[](size_t size, const char *file, unsigned long line)
2279{
2280 void *p;
2281
2282 while((p = Fortify_Allocate(size, Fortify_Allocator_array_new, file, line)) == 0)
2283 {
2284 if(st_NewHandler())
2285 (*st_NewHandler())();
2286 else
2287 return 0;
2288 }
2289
2290 return p;
2291}
2292
2293#endif /* FORTIFY_PROVIDE_ARRAY_NEW */
2294
2295/*
2296 * Fortify_PreDelete - C++ does not allow overloading
2297 * of delete, so the delete macro calls Fortify_PreDelete
2298 * with the source-code info, and then calls delete.
2299 */
2300void FORTIFY_STORAGE
2301Fortify_PreDelete(const char *file, int line)
2302{
2303 FORTIFY_LOCK();
2304
2305 /*
2306 * Push the source code info for the delete onto the delete stack
2307 * (if we have enough room, of course)
2308 */
2309 if(st_DeleteStackTop < FORTIFY_DELETE_STACK_SIZE)
2310 {
2311 st_DeleteFile[st_DeleteStackTop] = file;
2312 st_DeleteLine[st_DeleteStackTop] = line;
2313 }
2314
2315 st_DeleteStackTop++;
2316}
2317
2318/*
2319 * Fortify_PostDelete() - Pop the delete source-code info
2320 * off the source stack.
2321 */
2322void FORTIFY_STORAGE
2323Fortify_PostDelete()
2324{
2325 st_DeleteStackTop--;
2326
2327 FORTIFY_UNLOCK();
2328}
2329
2330/*
2331 * operator delete - fortify's replacement delete
2332 */
2333void FORTIFY_STORAGE
2334operator delete(void *uptr)
2335{
2336 const char *file;
2337 unsigned long line;
2338
2339 /*
2340 * It is defined to be harmless to delete 0
2341 */
2342 if(uptr == 0)
2343 return;
2344
2345 /*
2346 * find the source-code info
2347 */
2348 if(st_DeleteStackTop)
2349 {
2350 if(st_DeleteStackTop < FORTIFY_DELETE_STACK_SIZE)
2351 {
2352 file = st_DeleteFile[st_DeleteStackTop-1];
2353 line = st_DeleteLine[st_DeleteStackTop-1];
2354 }
2355 else
2356 {
2357 file = st_DeleteFile[FORTIFY_DELETE_STACK_SIZE-1];
2358 line = st_DeleteLine[FORTIFY_DELETE_STACK_SIZE-1];
2359 }
2360 }
2361 else
2362 {
2363 file = st_DeallocatorName[Fortify_Deallocator_delete];
2364 line = 0;
2365 }
2366
2367 Fortify_Deallocate(uptr, Fortify_Deallocator_delete, file, line);
2368}
2369
2370#ifdef FORTIFY_PROVIDE_ARRAY_DELETE
2371
2372/*
2373 * operator delete[] - fortify's replacement delete[]
2374 */
2375void FORTIFY_STORAGE
2376operator delete[](void *uptr)
2377{
2378 const char *file;
2379 unsigned long line;
2380
2381 /*
2382 * It is defined to be harmless to delete 0
2383 */
2384 if(uptr == 0)
2385 return;
2386
2387 /*
2388 * find the source-code info
2389 */
2390 if(st_DeleteStackTop)
2391 {
2392 if(st_DeleteStackTop < FORTIFY_DELETE_STACK_SIZE)
2393 {
2394 file = st_DeleteFile[st_DeleteStackTop-1];
2395 line = st_DeleteLine[st_DeleteStackTop-1];
2396 }
2397 else
2398 {
2399 file = st_DeleteFile[FORTIFY_DELETE_STACK_SIZE-1];
2400 line = st_DeleteLine[FORTIFY_DELETE_STACK_SIZE-1];
2401 }
2402 }
2403 else
2404 {
2405 file = st_DeallocatorName[Fortify_Deallocator_array_delete];
2406 line = 0;
2407 }
2408
2409 Fortify_Deallocate(uptr, Fortify_Deallocator_array_delete, file, line);
2410}
2411
2412#endif /* FORTIFY_PROVIDE_ARRAY_DELETE */
2413
2414#ifdef FORTIFY_AUTOMATIC_LOG_FILE
2415/* Automatic log file stuff!
2416 *
2417 * AutoLogFile class. There can only ever be ONE of these
2418 * instantiated! It is a static class, which means that
2419 * it's constructor will be called at program initialization,
2420 * and it's destructor will be called at program termination.
2421 * We don't know if the other static class objects have been
2422 * constructed/destructed yet, but this pretty much the best
2423 * we can do with standard C++ language features.
2424 */
2425class Fortify_AutoLogFile
2426{
2427 static FILE *fp;
2428 static int written_something;
2429 static char *init_string, *term_string;
2430
2431public:
2432 Fortify_AutoLogFile()
2433 {
2434 written_something = 0;
2435 Fortify_SetOutputFunc(Fortify_AutoLogFile::Output);
2436 Fortify_EnterScope(init_string, 0);
2437 }
2438
2439 static void Output(const char *s)
2440 {
2441 if(written_something == 0)
2442 {
2443 FORTIFY_FIRST_ERROR_FUNCTION;
2444 fp = fopen(FORTIFY_LOG_FILENAME, "w");
2445 if(fp)
2446 {
2447 time_t t;
2448 time(&t);
2449 fprintf(fp, "Fortify log started at %s\n", ctime(&t));
2450 written_something = 1;
2451 }
2452 }
2453
2454 if(fp)
2455 {
2456 fputs(s, fp);
2457 fflush(fp);
2458 }
2459 }
2460
2461 ~Fortify_AutoLogFile()
2462 {
2463 Fortify_LeaveScope(term_string, 0);
2464 Fortify_CheckAllMemory(term_string, 0);
2465 if(fp)
2466 {
2467 time_t t;
2468 time(&t);
2469 fprintf(fp, "\nFortify log closed at %s\n", ctime(&t));
2470 fclose(fp);
2471 fp = 0;
2472 }
2473 }
2474};
2475
2476FILE *Fortify_AutoLogFile::fp = 0;
2477int Fortify_AutoLogFile::written_something = 0;
2478char *Fortify_AutoLogFile::init_string = "Program Initialization";
2479char *Fortify_AutoLogFile::term_string = "Program Termination";
2480
2481static Fortify_AutoLogFile Abracadabra;
2482
2483#endif /* FORTIFY_AUTOMATIC_LOG_FILE */
2484
2485#endif /* __cplusplus */
2486
2487#ifdef MT_SCOPES
2488
2489#if 0 // 18 Jul 08 SHL fixme to be gone
2490
2491/**
2492 * Set/reset owner of blocks allocated by this thread
2493 * Use when worker thread will allocate blocks for another thread
2494 * and other thread is known
2495 * Slightly more efficient than Fortify_BecomeOwner
2496 * @param lOwnerTID is new owner TID, -1 requests reset of self
2497 */
2498
2499void Fortify_PresetOwner(long lOwnerTID)
2500{
2501 unsigned ordinal = Get_TID_Ordinal();
2502
2503 if (ordinal >= st_cOrdinals) {
2504 // Expand arrays
2505 unsigned i;
2506 unsigned c;
2507 FORTIFY_LOCK();
2508 i = st_cOrdinals;
2509 c = ordinal + 1;
2510 st_pScopes = realloc((void*)st_pScopes, sizeof(*st_pScopes) * c);
2511 st_pOwners = realloc((void*)st_pOwners, sizeof(*st_pOwners) * c);
2512 for (; i <= ordinal; i++) {
2513 st_pScopes[i] = 0;
2514 st_pOwners[i] = i; // Block owner is self
2515 }
2516 st_cOrdinals = c;
2517 FORTIFY_UNLOCK();
2518 }
2519 // Set owner for blocks allocated by this thread
2520 st_pOwners[ordinal] = lOwnerTID != -1 ? lOwnerTID : ordinal;
2521}
2522#endif // 18 Jul 08 SHL fixme to be gone
2523
2524/**
2525 * Take ownership of block allocated by some other thread
2526 * Allows scope enter/exit logic to correctly report leaks in
2527 * cross thread allocations
2528 * @param pBlock points to block allocated by Fortify
2529 */
2530
2531void Fortify_BecomeOwner(void *pBlock)
2532{
2533 unsigned char *ptr = (unsigned char *)pBlock -
2534 FORTIFY_HEADER_SIZE -
2535 FORTIFY_ALIGNED_BEFORE_SIZE;
2536 struct Header *h = (struct Header *)ptr;
2537
2538 unsigned ordinal = Get_TID_Ordinal();
2539
2540 h->Owner = ordinal; // Take ownership
2541 h->Scope = ordinal < st_cOrdinals ? st_pScopes[ordinal] : 0;
2542 st_MakeHeaderValid(h);
2543}
2544
2545/**
2546 * Take ownership of block allocated by some other thread
2547 * Allows scope enter/exit logic to correctly report leaks in
2548 * cross thread allocations
2549 * @param pBlock points to block allocated by Fortify
2550 */
2551
2552void Fortify_SetOwner(void *pBlock, unsigned ordinal)
2553{
2554 unsigned char *ptr = (unsigned char *)pBlock -
2555 FORTIFY_HEADER_SIZE -
2556 FORTIFY_ALIGNED_BEFORE_SIZE;
2557 struct Header *h = (struct Header *)ptr;
2558
2559 h->Owner = (unsigned short)ordinal; // Take ownership
2560 h->Scope = ordinal < st_cOrdinals ? st_pScopes[ordinal] : 0;
2561 st_MakeHeaderValid(h);
2562}
2563
2564/**
2565 * Adjust scope level of allocated block
2566 * Allows scope enter/exit logic to correctly report leaks in
2567 * window procedure related allocations
2568 * @param pBlock points to block allocated by Fortify
2569 */
2570
2571void Fortify_ChangeScope(void *pBlock, int delta)
2572{
2573 unsigned char *ptr = (unsigned char *)pBlock -
2574 FORTIFY_HEADER_SIZE -
2575 FORTIFY_ALIGNED_BEFORE_SIZE;
2576 struct Header *h = (struct Header *)ptr;
2577 h->Scope += delta;
2578 st_MakeHeaderValid(h);
2579}
2580
2581/**
2582 * Force scope level of allocated block
2583 * Allows scope enter/exit logic to correctly report leaks in
2584 * window procedure related allocations
2585 * @param pBlock points to block allocated by Fortify
2586 */
2587
2588void Fortify_SetScope(void *pBlock, unsigned char scope)
2589{
2590 unsigned char *ptr = (unsigned char *)pBlock -
2591 FORTIFY_HEADER_SIZE -
2592 FORTIFY_ALIGNED_BEFORE_SIZE;
2593 struct Header *h = (struct Header *)ptr;
2594 h->Scope = scope;
2595 st_MakeHeaderValid(h);
2596}
2597
2598#endif // MT_SCOPES
2599
2600#endif /* FORTIFY */
Note: See TracBrowser for help on using the repository browser.