Coverage Report

Created: 2026-12-01 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gpac/src/utils/alloc.c
Line
Count
Source
1
/*
2
 *      GPAC - Multimedia Framework C SDK
3
 *
4
 *          Authors: Romain Bouqueau - Jean Le Feuvre
5
 *      Copyright (c) Telecom ParisTech 2010-2023
6
 *          All rights reserved
7
 *
8
 *  This file is part of GPAC / common tools sub-project
9
 *
10
 *  GPAC is free software; you can redistribute it and/or modify
11
 *  it under the terms of the GNU Lesser General Public License as published by
12
 *  the Free Software Foundation; either version 2, or (at your option)
13
 *  any later version.
14
 *
15
 *  GPAC is distributed in the hope that it will be useful,
16
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 *  GNU Lesser General Public License for more details.
19
 *
20
 *  You should have received a copy of the GNU Lesser General Public
21
 *  License along with this library; see the file COPYING.  If not, write to
22
 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
 *
24
 */
25
26
#if defined(__GNUC__) && __GNUC__ >= 4
27
#define _GNU_SOURCE
28
#endif
29
#include <stdio.h>
30
#include <stdarg.h>
31
#include <string.h>
32
33
34
#define STD_MALLOC  0
35
#define GOOGLE_MALLOC 1
36
#define INTEL_MALLOC  2
37
#define DL_MALLOC   3
38
39
#ifdef WIN32
40
#define USE_MALLOC  STD_MALLOC
41
#else
42
#define USE_MALLOC  STD_MALLOC
43
#endif
44
45
46
#if defined(_WIN32_WCE) && !defined(strdup)
47
#define strdup  _strdup
48
#endif
49
50
/*
51
  WARNING - you must enable C++ style compilation of this file (error.c) to be able to compile
52
  with google malloc. This is not set by default in the project settings.
53
*/
54
#if (USE_MALLOC==GOOGLE_MALLOC)
55
#include <config.h>
56
#include <base/commandlineflags.h>
57
#include <google/malloc_extension.h>
58
59
#ifdef WIN32
60
#pragma comment(lib, "libtcmalloc_minimal")
61
#endif
62
63
#define MALLOC  malloc
64
#define CALLOC  calloc
65
#define REALLOC realloc
66
#define FREE  free
67
#define STRDUP(a) return strdup(a);
68
69
/*we must use c++ compiler for google malloc :( */
70
#define CDECL extern "C"
71
#endif
72
73
#if (USE_MALLOC==INTEL_MALLOC)
74
#define CDECL
75
CDECL void * scalable_malloc(size_t size);
76
CDECL void * scalable_realloc(void* ptr, size_t size);
77
CDECL void * scalable_calloc(size_t num, size_t size);
78
CDECL void   scalable_free(void* ptr);
79
80
#ifdef WIN32
81
#pragma comment(lib, "tbbmalloc.lib")
82
#endif
83
84
#define MALLOC  scalable_malloc
85
#define CALLOC  scalable_calloc
86
#define REALLOC scalable_realloc
87
#define FREE  scalable_free
88
#define STRDUP(_a) if (_a) { unsigned int len = strlen(_a)+1; char *ptr = (char *) scalable_malloc(len); gf_strcpy(ptr, _a); return ptr; } else { return NULL; }
89
90
#endif
91
92
#ifndef CDECL
93
#define CDECL
94
#endif
95
96
#ifndef SYMBOL_EXPORT
97
#if defined(__GNUC__) && __GNUC__ >= 4
98
#define SYMBOL_EXPORT __attribute__((visibility("default")))
99
#endif
100
#endif
101
102
#if (USE_MALLOC==DL_MALLOC)
103
104
CDECL void * dlmalloc(size_t size);
105
CDECL void * dlrealloc(void* ptr, size_t size);
106
CDECL void * dlcalloc(size_t num, size_t size);
107
CDECL void   dlfree(void* ptr);
108
109
#define MALLOC  dlmalloc
110
#define CALLOC  dlcalloc
111
#define REALLOC dlrealloc
112
#define FREE  dlfree
113
#define STRDUP(_a) if (_a) { unsigned int len = strlen(_a)+1; char *ptr = (char *) dlmalloc(len); gf_strcpy(ptr, _a); return ptr; } else { return NULL; }
114
115
#endif
116
117
#if (USE_MALLOC==STD_MALLOC)
118
119
#include <stdlib.h>
120
121
53.0M
#define MALLOC  malloc
122
15.9k
#define CALLOC  calloc
123
33.7M
#define REALLOC realloc
124
85.8M
#define FREE  free
125
2.28M
#define STRDUP(a) return strdup(a);
126
127
#endif
128
129
130
131
#ifndef _WIN32_WCE
132
#include <assert.h>
133
#endif
134
135
/*This is to handle cases where config.h is generated at the root of the gpac build tree (./configure)
136
This is only needed when building libgpac and modules when libgpac is not installed*/
137
#ifdef GPAC_HAVE_CONFIG_H
138
# include "config.h"
139
#else
140
# include <gpac/configuration.h>
141
#endif
142
143
/*GPAC memory tracking*/
144
#ifndef GPAC_MEMORY_TRACKING
145
146
#include <gpac/setup.h>
147
GF_EXPORT
148
void *gf_malloc(size_t size)
149
53.0M
{
150
53.0M
  return MALLOC(size);
151
53.0M
}
152
GF_EXPORT
153
void *gf_calloc(size_t num, size_t size_of)
154
15.9k
{
155
15.9k
  return CALLOC(num, size_of);
156
15.9k
}
157
GF_EXPORT
158
void *gf_realloc(void *ptr, size_t size)
159
33.7M
{
160
33.7M
  return REALLOC(ptr, size);
161
33.7M
}
162
GF_EXPORT
163
void gf_free(void *ptr)
164
85.8M
{
165
85.8M
  FREE(ptr);
166
85.8M
}
167
GF_EXPORT
168
char *gf_strdup(const char *str)
169
2.28M
{
170
2.28M
  STRDUP(str);
171
0
}
172
173
#else /*GPAC_MEMORY_TRACKING**/
174
175
176
static void gf_memory_log(unsigned int level, const char *fmt, ...);
177
enum
178
{
179
  /*! Disable all Log message*/
180
  GF_MEMORY_QUIET = 0,
181
  /*! Log message describes an error*/
182
  GF_MEMORY_ERROR = 1,
183
  /*! Log message describes a warning*/
184
  GF_MEMORY_WARNING,
185
  /*! Log message is informational (state, etc..)*/
186
  GF_MEMORY_INFO,
187
  /*! Log message is a debug info*/
188
  GF_MEMORY_DEBUG,
189
};
190
191
192
size_t gpac_allocated_memory = 0;
193
size_t gpac_nb_alloc_blocs = 0;
194
195
//defs for gf_assert
196
#include <gpac/setup.h>
197
198
//backtrace not supported on these platforms
199
#if defined(GPAC_CONFIG_IOS) || defined(GPAC_CONFIG_ANDROID)
200
#define GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
201
#endif
202
203
int gf_mem_track_enabled = 0;
204
205
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
206
static int gf_mem_backtrace_enabled = 0;
207
208
/*malloc dynamic storage needed for each alloc is STACK_PRINT_SIZE*SYMBOL_MAX_SIZE+1, keep them small!*/
209
#define STACK_FIRST_IDX  5 //remove the gpac memory allocator self trace
210
#define STACK_PRINT_SIZE 10
211
212
#ifdef WIN32
213
#define SYMBOL_MAX_SIZE  50
214
#include <windows.h>
215
/* on visual studio 2015 windows sdk 8.1 dbghelp has a typedef enum with no name that throws a warning */
216
#if !defined(__GNUC__)
217
#pragma warning(disable: 4091)
218
#endif
219
#include <dbghelp.h>
220
#if !defined(__GNUC__)
221
#pragma comment(lib, "dbghelp.lib")
222
#endif
223
/*memory ownership to the caller*/
224
static void store_backtrace(char *s_backtrace)
225
{
226
  void *stack[STACK_PRINT_SIZE];
227
  size_t i, frames, bt_idx = 0;
228
  SYMBOL_INFO *symbol;
229
  HANDLE process;
230
231
  process = GetCurrentProcess();
232
  SymInitialize(process, NULL, TRUE);
233
234
  symbol = (SYMBOL_INFO*)_alloca(sizeof(SYMBOL_INFO) + SYMBOL_MAX_SIZE);
235
  symbol->MaxNameLen = SYMBOL_MAX_SIZE-1;
236
  symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
237
238
  frames = CaptureStackBackTrace(STACK_FIRST_IDX, STACK_PRINT_SIZE, stack, NULL);
239
240
  for (i=0; i<frames; i++) {
241
    int len;
242
    int bt_len;
243
    char *symbol_name = "unresolved";
244
    SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
245
    if (symbol->Name) symbol_name = (char*)symbol->Name;
246
247
    bt_len = (int) strlen(symbol_name) + 10;
248
    if (bt_idx + bt_len > STACK_PRINT_SIZE*SYMBOL_MAX_SIZE) {
249
      gf_memory_log(GF_MEMORY_WARNING, "[MemoryInfo] Not enough space to hold backtrace - truncating\n");
250
      break;
251
    }
252
253
    len = _snprintf(s_backtrace+bt_idx, SYMBOL_MAX_SIZE-1, "\t%02u 0x%I64X %s", (unsigned int) (frames-i-1), symbol->Address, symbol_name);
254
    if (len<0) len = SYMBOL_MAX_SIZE-1;
255
    s_backtrace[bt_idx+len]='\n';
256
    bt_idx += (len+1);
257
  }
258
  gf_assert(bt_idx < STACK_PRINT_SIZE*SYMBOL_MAX_SIZE);
259
  s_backtrace[bt_idx-1] = '\0';
260
}
261
262
#else /*WIN32*/
263
264
#define SYMBOL_MAX_SIZE  100
265
266
#ifndef GPAC_CONFIG_EMSCRIPTEN
267
#include <execinfo.h>
268
#endif
269
270
/*memory ownership to the caller*/
271
static void store_backtrace(char *s_backtrace)
272
{
273
#ifndef GPAC_CONFIG_EMSCRIPTEN
274
  size_t i, size, bt_idx=0;
275
  void *stack[STACK_PRINT_SIZE+STACK_FIRST_IDX];
276
  char **messages;
277
278
  size = backtrace(stack, STACK_PRINT_SIZE+STACK_FIRST_IDX);
279
  messages = backtrace_symbols(stack, size);
280
281
  for (i=STACK_FIRST_IDX; i<size && messages!=NULL; ++i) {
282
    int bt_len = strlen(messages[i]) + 10;
283
    int len;
284
285
    if (bt_idx + bt_len > STACK_PRINT_SIZE*SYMBOL_MAX_SIZE) {
286
      gf_memory_log(GF_MEMORY_WARNING, "[MemoryInfo] Not enough space to hold backtrace - truncating\n");
287
      break;
288
    }
289
290
    len = snprintf(s_backtrace+bt_idx, SYMBOL_MAX_SIZE-1, "\t%02zu %s", i, messages[i]);
291
    if (len<0) len = SYMBOL_MAX_SIZE-1;
292
    s_backtrace[bt_idx+len]='\n';
293
    bt_idx += (len+1);
294
295
  }
296
  gf_assert(bt_idx < STACK_PRINT_SIZE*SYMBOL_MAX_SIZE);
297
  s_backtrace[bt_idx-1] = '\0';
298
  free(messages);
299
#endif
300
}
301
#endif /*WIN32*/
302
303
304
#endif /*GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE*/
305
306
307
static void register_address(void *ptr, size_t size, const char *filename, int line);
308
static int unregister_address(void *ptr, const char *filename, int line);
309
310
311
static void *gf_mem_malloc_basic(size_t size, const char *filename, int line)
312
{
313
  return MALLOC(size);
314
}
315
static void *gf_mem_calloc_basic(size_t num, size_t size_of, const char *filename, int line)
316
{
317
  return CALLOC(num, size_of);
318
}
319
static void *gf_mem_realloc_basic(void *ptr, size_t size, const char *filename, int line)
320
{
321
  return REALLOC(ptr, size);
322
}
323
static void gf_mem_free_basic(void *ptr, const char *filename, int line)
324
{
325
  FREE(ptr);
326
}
327
static char *gf_mem_strdup_basic(const char *str, const char *filename, int line)
328
{
329
  STRDUP(str);
330
}
331
332
static unsigned int nb_calls_alloc = 0;
333
static unsigned int nb_calls_calloc = 0;
334
static unsigned int nb_calls_realloc = 0;
335
static unsigned int nb_calls_free = 0;
336
337
void *gf_mem_malloc_tracker(size_t size, const char *filename, int line)
338
{
339
  void *ptr = MALLOC(size);
340
  if (!ptr) {
341
    gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] malloc() has returned a NULL pointer\n");
342
    gf_assert(0);
343
  } else {
344
    register_address(ptr, size, filename, line);
345
  }
346
  gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] malloc %3d bytes at %p in:\n", size, ptr);
347
  gf_memory_log(GF_MEMORY_DEBUG, "             file %s at line %d\n" , filename, line);
348
  nb_calls_alloc++;
349
  return ptr;
350
}
351
352
void *gf_mem_calloc_tracker(size_t num, size_t size_of, const char *filename, int line)
353
{
354
  size_t size = num*size_of;
355
  void *ptr = CALLOC(num, size_of);
356
  if (!ptr) {
357
    gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] calloc() has returned a NULL pointer\n");
358
    gf_assert(0);
359
  } else {
360
    register_address(ptr, size, filename, line);
361
  }
362
  gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] calloc %3d bytes at %p in:\n", ptr, size);
363
  gf_memory_log(GF_MEMORY_DEBUG, "             file %s at line %d\n" , filename, line);
364
  nb_calls_calloc++;
365
  return ptr;
366
}
367
368
void gf_mem_free_tracker(void *ptr, const char *filename, int line)
369
{
370
  int size_prev;
371
  if (ptr && (size_prev=unregister_address(ptr, filename, line))) {
372
    gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] free   %3d bytes at %p in:\n", size_prev, ptr);
373
    gf_memory_log(GF_MEMORY_DEBUG, "             file %s at line %d\n" , filename, line);
374
    FREE(ptr);
375
  }
376
  nb_calls_free++;
377
}
378
379
void *gf_mem_realloc_tracker(void *ptr, size_t size, const char *filename, int line)
380
{
381
  void *ptr_g;
382
  int size_prev;
383
  if (!ptr) {
384
    gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] realloc() from a null pointer: calling malloc() instead\n");
385
    return gf_mem_malloc_tracker(size, filename, line);
386
  }
387
  /*a) The return value is NULL if the size is zero and the buffer argument is not NULL. In this case, the original block is freed.*/
388
  if (!size) {
389
    gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] realloc() with a null size: calling free() instead\n");
390
    gf_mem_free_tracker(ptr, filename, line);
391
    return NULL;
392
  }
393
  size_prev = unregister_address(ptr, filename, line);
394
  ptr_g = REALLOC(ptr, size);
395
  if (!ptr_g) {
396
    /*b) The return value is NULL if there is not enough available memory to expand the block to the given size. In this case, the original block is unchanged.*/
397
    gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] realloc() has returned a NULL pointer\n");
398
    register_address(ptr, size_prev, filename, line);
399
    gf_assert(0);
400
  } else {
401
    register_address(ptr_g, size, filename, line);
402
//    gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] realloc %3d (instead of %3d) bytes at %p (instead of %p)\n", size, size_prev, ptr_g, ptr);
403
    gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] realloc %3d (instead of %3d) bytes at %p\n", size, size_prev, ptr_g);
404
    gf_memory_log(GF_MEMORY_DEBUG, "             file %s at line %d\n" , filename, line);
405
  }
406
  nb_calls_realloc++;
407
  return ptr_g;
408
}
409
410
char *gf_mem_strdup_tracker(const char *str, const char *filename, int line)
411
{
412
  char *ptr;
413
  if (!str) return NULL;
414
  u32 alen = (u32) strlen(str);
415
  ptr = (char*)gf_mem_malloc_tracker(alen+1, filename, line);
416
  memcpy(ptr, str, alen+1);
417
  return ptr;
418
}
419
420
421
static void *(*gf_mem_malloc_proto)(size_t size, const char *filename, int line) = gf_mem_malloc_basic;
422
static void *(*gf_mem_calloc_proto)(size_t num, size_t size_of, const char *filename, int line) = gf_mem_calloc_basic;
423
static void *(*gf_mem_realloc_proto)(void *ptr, size_t size, const char *filename, int line) = gf_mem_realloc_basic;
424
static void (*gf_mem_free_proto)(void *ptr, const char *filename, int line) = gf_mem_free_basic;
425
static char *(*gf_mem_strdup_proto)(const char *str, const char *filename, int line) = gf_mem_strdup_basic;
426
427
#ifndef MY_GF_EXPORT
428
#if defined(__GNUC__) && __GNUC__ >= 4
429
#define MY_GF_EXPORT __attribute__((visibility("default")))
430
#else
431
/*use def files for windows or let compiler decide*/
432
#define MY_GF_EXPORT
433
#endif
434
#endif
435
436
MY_GF_EXPORT void *gf_mem_malloc(size_t size, const char *filename, int line)
437
{
438
  return gf_mem_malloc_proto(size, filename, line);
439
}
440
441
MY_GF_EXPORT void *gf_mem_calloc(size_t num, size_t size_of, const char *filename, int line)
442
{
443
  return gf_mem_calloc_proto(num, size_of, filename, line);
444
}
445
446
MY_GF_EXPORT
447
void *gf_mem_realloc(void *ptr, size_t size, const char *filename, int line)
448
{
449
  return gf_mem_realloc_proto(ptr, size, filename, line);
450
}
451
452
MY_GF_EXPORT
453
void gf_mem_free(void *ptr, const char *filename, int line)
454
{
455
  gf_mem_free_proto(ptr, filename, line);
456
}
457
458
MY_GF_EXPORT
459
char *gf_mem_strdup(const char *str, const char *filename, int line)
460
{
461
  return gf_mem_strdup_proto(str, filename, line);
462
}
463
464
void gf_mem_enable_tracker(unsigned int mem_track_type)
465
{
466
  if (mem_track_type) {
467
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
468
    gf_mem_backtrace_enabled = (mem_track_type==2) ? 1 : 0;
469
#endif
470
    gf_mem_track_enabled = 1;
471
    gf_mem_malloc_proto = gf_mem_malloc_tracker;
472
    gf_mem_calloc_proto = gf_mem_calloc_tracker;
473
    gf_mem_realloc_proto = gf_mem_realloc_tracker;
474
    gf_mem_free_proto = gf_mem_free_tracker;
475
    gf_mem_strdup_proto = gf_mem_strdup_tracker;
476
  } else {
477
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
478
    gf_mem_backtrace_enabled = 0;
479
#endif
480
    gf_mem_track_enabled = 0;
481
    gf_mem_malloc_proto = gf_mem_malloc_basic;
482
    gf_mem_calloc_proto = gf_mem_calloc_basic;
483
    gf_mem_realloc_proto = gf_mem_realloc_basic;
484
    gf_mem_free_proto = gf_mem_free_basic;
485
    gf_mem_strdup_proto = gf_mem_strdup_basic;
486
  }
487
}
488
489
size_t gf_mem_get_stats(unsigned int *nb_allocs, unsigned int *nb_callocs, unsigned int *nb_reallocs, unsigned int *nb_free)
490
{
491
  if (nb_allocs) (*nb_allocs) = nb_calls_alloc;
492
  if (nb_callocs) (*nb_callocs) = nb_calls_calloc;
493
  if (nb_reallocs) (*nb_reallocs) = nb_calls_realloc;
494
  if (nb_free) (*nb_free) = nb_calls_free;
495
  return gpac_allocated_memory;
496
}
497
498
typedef struct s_memory_element
499
{
500
  void *ptr;
501
  unsigned int size;
502
  struct s_memory_element *next;
503
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
504
  char *backtrace_stack;
505
#endif
506
  int line;
507
  char *filename;
508
} memory_element;
509
510
/*pointer to the first element of the list*/
511
typedef memory_element** memory_list;
512
513
514
#define HASH_ENTRIES 4096
515
516
#if !defined(WIN32)
517
#include <stdint.h>
518
#endif
519
520
static unsigned int gf_memory_hash(void *ptr)
521
{
522
#if defined(WIN32)
523
  return (unsigned int) ( (((unsigned __int64)ptr>>4)+(unsigned __int64)ptr) % HASH_ENTRIES );
524
#else
525
  return (unsigned int) ( (((uint64_t) ((intptr_t) ptr)>>4) + (uint64_t) ((intptr_t)ptr) ) % HASH_ENTRIES );
526
#endif
527
}
528
529
530
/*base functions (add, find, del_item, del) are implemented upon a stack model*/
531
static void gf_memory_add_stack(memory_element **p, void *ptr, unsigned int size, const char *filename, int line)
532
{
533
  memory_element *element = (memory_element*)MALLOC(sizeof(memory_element));
534
  if (!element) {
535
    gf_memory_log(GF_MEMORY_ERROR, ("[Mem] Fail to register stack for allocation\n"));
536
    return;
537
  }
538
  element->ptr = ptr;
539
  element->size = size;
540
  element->line = line;
541
542
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
543
  if (gf_mem_backtrace_enabled) {
544
    element->backtrace_stack = MALLOC(sizeof(char) * STACK_PRINT_SIZE * SYMBOL_MAX_SIZE);
545
    if (!element->backtrace_stack) {
546
      gf_memory_log(GF_MEMORY_WARNING, ("[Mem] Fail to register backtrace of allocation\n"));
547
      element->backtrace_stack = NULL;
548
    } else {
549
      store_backtrace(element->backtrace_stack);
550
    }
551
  } else {
552
    element->backtrace_stack = NULL;
553
  }
554
#endif
555
556
  u32 alen = (u32) strlen(filename);
557
  element->filename = MALLOC(alen + 1);
558
  if (element->filename)
559
    memcpy(element->filename, filename, alen + 1);
560
561
  element->next = *p;
562
  *p = element;
563
}
564
565
/*returns the position of a ptr from a memory_element, 0 if not found*/
566
static int gf_memory_find_stack(memory_element *p, void *ptr)
567
{
568
  int i = 1;
569
  memory_element *element = p;
570
  while (element) {
571
    if (element->ptr == ptr) {
572
      return i;
573
    }
574
    element = element->next;
575
    i++;
576
  }
577
  return 0;
578
}
579
580
/*returns the size of the deleted item*/
581
static unsigned int gf_memory_del_item_stack(memory_element **p, void *ptr)
582
{
583
  unsigned int size;
584
  memory_element *curr_element=*p, *prev_element=NULL;
585
  while (curr_element) {
586
    if (curr_element->ptr == ptr) {
587
      if (prev_element) prev_element->next = curr_element->next;
588
      else *p = curr_element->next;
589
      size = curr_element->size;
590
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
591
      if (curr_element->backtrace_stack) {
592
        FREE(curr_element->backtrace_stack);
593
      }
594
#endif
595
      FREE(curr_element);
596
      return size;
597
    }
598
    prev_element = curr_element;
599
    curr_element = curr_element->next;
600
  }
601
  return 0;
602
}
603
604
/*this list is implemented as a stack to minimise the cost of freeing recent allocations*/
605
static void gf_memory_add(memory_list *p, void *ptr, unsigned int size, const char *filename, int line)
606
{
607
  unsigned int hash;
608
  if (!*p) *p = (memory_list) CALLOC(HASH_ENTRIES, sizeof(memory_element*));
609
  gf_fatal_assert(*p);
610
611
  hash = gf_memory_hash(ptr);
612
  gf_memory_add_stack(&((*p)[hash]), ptr, size, filename, line);
613
}
614
615
616
static int gf_memory_find(memory_list p, void *ptr)
617
{
618
  unsigned int hash;
619
  gf_assert(p);
620
  if (!p) return 0;
621
  hash = gf_memory_hash(ptr);
622
  return gf_memory_find_stack(p[hash], ptr);
623
}
624
625
static unsigned int gf_memory_del_item(memory_list *p, void *ptr)
626
{
627
  unsigned int hash;
628
  unsigned int ret;
629
  memory_element **sub_list;
630
  if (!*p) *p = (memory_list) CALLOC(HASH_ENTRIES, sizeof(memory_element*));
631
  gf_fatal_assert(*p);
632
  hash = gf_memory_hash(ptr);
633
  sub_list = &((*p)[hash]);
634
  //code does nothing as &((*p)[hash]) always evaluates to true - commenting it
635
//  if (!sub_list) return 0;
636
  ret = gf_memory_del_item_stack(sub_list, ptr);
637
638
  //code does nothing as &((*p)[i]) always evaluates to true - commenting it
639
#if 0
640
  if (ret && !((*p)[hash])) {
641
    /*check for deletion*/
642
    int i;
643
    for (i=0; i<HASH_ENTRIES; i++)
644
      if (&((*p)[i])) break;
645
    if (i==HASH_ENTRIES) {
646
      FREE(*p);
647
    }
648
  }
649
#endif
650
  return ret;
651
}
652
653
654
655
#endif /*GPAC_MEMORY_TRACKING*/
656
657
658
#include <gpac/tools.h>
659
660
661
/*GPAC memory tracking*/
662
#ifdef GPAC_MEMORY_TRACKING
663
664
#include <gpac/thread.h>
665
666
/*global lists of allocations and deallocations*/
667
memory_list memory_add = NULL, memory_rem = NULL;
668
GF_Mutex *gpac_allocations_lock = NULL;
669
670
static void register_address(void *ptr, size_t size, const char *filename, int line)
671
{
672
  /*mutex initialization*/
673
  if (gpac_allocations_lock == 0) {
674
    gf_assert(!memory_add);
675
    gf_assert(!memory_rem);
676
    gpac_allocations_lock = (GF_Mutex*)1; /*must be non-null to avoid a recursive infinite call*/
677
    gpac_allocations_lock = gf_mx_new("gpac_allocations_lock");
678
  }
679
  else if (gpac_allocations_lock == (void*)1) {
680
    /*we're initializing the mutex (ie called by the gf_mx_new() above)*/
681
    return;
682
  }
683
684
  /*lock*/
685
  gf_mx_p(gpac_allocations_lock);
686
687
  gf_memory_add(&memory_add, ptr, (unsigned int)size, filename, line);
688
  gf_memory_del_item(&memory_rem, ptr); /*the same block can be reallocated, so remove it from the deallocation list*/
689
690
  /*update stats*/
691
  gpac_allocated_memory += size;
692
  gpac_nb_alloc_blocs++;
693
694
  /*gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] register   %6d bytes at %p (%8d Bytes in %4d Blocks allocated)\n", size, ptr, gpac_allocated_memory, gpac_nb_alloc_blocs);*/
695
696
  /*unlock*/
697
  gf_mx_v(gpac_allocations_lock);
698
}
699
700
void log_backtrace(unsigned int log_level, memory_element *element)
701
{
702
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
703
  if (gf_mem_backtrace_enabled) {
704
    gf_memory_log(log_level, "file %s at line %d\n%s\n", element->filename, element->line, element->backtrace_stack);
705
  } else
706
#endif
707
  {
708
    gf_memory_log(log_level, "file %s at line %d\n", element->filename, element->line);
709
  }
710
}
711
712
713
#if 0 //unused
714
Bool gf_mem_check_address(void *ptr)
715
{
716
  Bool res = GF_TRUE;
717
  int pos;
718
719
  if (!gpac_allocations_lock) return res;
720
721
  /*lock*/
722
  gf_mx_p(gpac_allocations_lock);
723
724
  if ( (pos=gf_memory_find(memory_rem, ptr)) ) {
725
    int i;
726
    unsigned int hash = gf_memory_hash(ptr);
727
    memory_element *element = memory_rem[hash];
728
    gf_assert(element);
729
    for (i=1; i<pos; i++)
730
      element = element->next;
731
    gf_assert(element);
732
    gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] the block %p was already freed in:\n", ptr);
733
    res = GF_FALSE;
734
    log_backtrace(GF_MEMORY_ERROR, element);
735
  }
736
  /*unlock*/
737
  gf_mx_v(gpac_allocations_lock);
738
  return res;
739
}
740
#endif
741
742
/*returns the size of the unregistered block*/
743
static int unregister_address(void *ptr, const char *filename, int line)
744
{
745
  unsigned int size = 0; /*default: failure*/
746
747
  /*lock*/
748
  gf_mx_p(gpac_allocations_lock);
749
750
  if (!memory_add) {
751
    if (!memory_rem) {
752
      /*assume we're rather destroying the mutex (ie calling the gf_mx_del() below)
753
        than being called by free() before the first allocation occured*/
754
      return 1;
755
      /*gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] calling free() before the first allocation occured\n");
756
         gf_assert(0); */
757
    }
758
  } else {
759
    if (!gf_memory_find(memory_add, ptr)) {
760
      int pos;
761
      if (!(pos=gf_memory_find(memory_rem, ptr))) {
762
        gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] trying to free a never allocated block (%p)\n", ptr);
763
        /* gf_assert(0); */ /*don't assert since this is often due to allocations that occured out of gpac (fonts, etc.)*/
764
      } else {
765
        int i;
766
        unsigned int hash = gf_memory_hash(ptr);
767
        memory_element *element = memory_rem[hash];
768
769
        gf_assert(element);
770
        for (i=1; i<pos; i++)
771
          element = element->next;
772
        gf_assert(element);
773
        gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] the block %p trying to be deleted in:\n", ptr);
774
        gf_memory_log(GF_MEMORY_ERROR, "             file %s at line %d\n", filename, line);
775
        gf_memory_log(GF_MEMORY_ERROR, "             was already freed in:\n");
776
        log_backtrace(GF_MEMORY_ERROR, element);
777
        gf_fatal_assert(0);
778
      }
779
    } else {
780
      size = gf_memory_del_item(&memory_add, ptr);
781
782
      /*update stats*/
783
      gpac_allocated_memory -= size;
784
      gpac_nb_alloc_blocs--;
785
786
      /*gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] unregister %6d bytes at %p (%8d bytes in %4d blocks remaining)\n", size, ptr, gpac_allocated_memory, gpac_nb_alloc_blocs); */
787
788
      /*the allocation list is empty: free the lists to avoid a leak (we should be exiting)*/
789
      if (!memory_add) {
790
        gf_assert(!gpac_allocated_memory);
791
        gf_assert(!gpac_nb_alloc_blocs);
792
793
        /*we destroy the mutex we own, then we return*/
794
        gf_mx_del(gpac_allocations_lock);
795
        gpac_allocations_lock = NULL;
796
797
        gf_memory_log(GF_MEMORY_DEBUG, "[MemTracker] the allocated-blocks-list is empty: the freed-blocks-list will be emptied too.\n");
798
799
        //reset the freed block list
800
        memory_list *m_list = &memory_rem;
801
        int i;
802
        for (i=0; i<HASH_ENTRIES; i++) {
803
          memory_element **m_elt = &((*m_list)[i]) ;
804
805
          memory_element *curr_element=*m_elt, *next_element;
806
          while (curr_element) {
807
            next_element = curr_element->next;
808
#ifndef GPAC_MEMORY_TRACKING_DISABLE_STACKTRACE
809
            if (curr_element->backtrace_stack) {
810
              FREE(curr_element->backtrace_stack);
811
            }
812
#endif
813
            FREE(curr_element);
814
            curr_element = next_element;
815
          }
816
          *m_elt = NULL;
817
        }
818
819
        FREE(*m_list);
820
821
        return size;
822
      } else {
823
        gf_memory_add(&memory_rem, ptr, size, filename, line);
824
      }
825
    }
826
  }
827
828
  /*unlock*/
829
  gf_mx_v(gpac_allocations_lock);
830
831
  return size;
832
}
833
834
static void gf_memory_log(unsigned int level, const char *fmt, ...)
835
{
836
  va_list vl;
837
  char msg[1025];
838
  va_start(vl, fmt);
839
  vsnprintf(msg, 1024, fmt, vl);
840
  msg[1024] = 0;
841
  GF_LOG(level, GF_LOG_MEMORY, (msg));
842
  va_end(vl);
843
}
844
845
/*prints allocations sum-up*/
846
static void print_memory_size()
847
{
848
  GF_LOG(gpac_nb_alloc_blocs ? GF_MEMORY_ERROR : GF_MEMORY_INFO, GF_LOG_MEMORY, ("[MemTracker] Total: %d bytes allocated in %d blocks\n", (u32) gpac_allocated_memory,  (u32) gpac_nb_alloc_blocs ));
849
}
850
851
GF_EXPORT
852
u64 gf_memory_size()
853
{
854
  return (u64) gpac_allocated_memory;
855
}
856
857
/*prints the state of current allocations*/
858
GF_EXPORT
859
void gf_memory_print()
860
{
861
  /*if lists are empty, the mutex is also NULL*/
862
  if (!memory_add) {
863
    gf_assert(!gpac_allocations_lock);
864
    gf_memory_log(GF_MEMORY_INFO, "[MemTracker] gf_memory_print(): the memory tracker is not initialized, some file handles are not closed.\n");
865
  } else {
866
    int i=0;
867
    gf_assert(gpac_allocations_lock);
868
    const char *enum_open_handles(u32 *idx);
869
    u32 nb_handles = gf_file_handles_count();
870
871
872
    gf_memory_log(GF_MEMORY_INFO, "\n[MemTracker] Printing the current state of allocations (%d open file handles) :\n", nb_handles);
873
874
    /*lock*/
875
    gf_mx_p(gpac_allocations_lock);
876
    for (i=0; i<HASH_ENTRIES; i++) {
877
      memory_element *curr_element = memory_add[i], *next_element;
878
      while (curr_element) {
879
        char szVal[51], *sep;
880
        char szHexVal[101];
881
        u32 size, j;
882
        next_element = curr_element->next;
883
        size = curr_element->size>=50 ? 50 : curr_element->size;
884
        for (j=0 ; j<size ; j++) {
885
          unsigned char byte = *((unsigned char*)(curr_element->ptr) + j);
886
          szVal[j] = (byte > 31 && byte < 127) ? byte : '.';
887
          sprintf(szHexVal+2*j, "%02X", byte);
888
        }
889
        szVal[size] = 0;
890
        sep = strchr(szVal, '%');
891
        if (sep) sep[0] = 0;
892
        szHexVal[2*size] = 0;
893
        gf_memory_log(GF_MEMORY_INFO, "[MemTracker] Memory Block %p (size %d) allocated in:\n", curr_element->ptr, curr_element->size);
894
        log_backtrace(GF_MEMORY_INFO, curr_element);
895
        gf_memory_log(GF_MEMORY_INFO, "             string dump: %s\n", szVal);
896
        gf_memory_log(GF_MEMORY_INFO, "             hex dump: %s\n", szHexVal);
897
        curr_element = next_element;
898
      }
899
    }
900
    print_memory_size();
901
    /*unlock*/
902
    gf_mx_v(gpac_allocations_lock);
903
904
    i=0;
905
    while (1) {
906
      const char *n = enum_open_handles(&i);
907
      if (!n) break;
908
      gf_memory_log(GF_MEMORY_ERROR, "[MemTracker] File %s was not closed\n", n);
909
    }
910
  }
911
}
912
913
#endif /*GPAC_MEMORY_TRACKING*/
914
915
#if 0 //unused
916
917
/*gf_asprintf(): as_printf portable implementation*/
918
#if defined(WIN32) || defined(_WIN32_WCE) || (defined (__SVR4) && defined (__sun))
919
static GFINLINE int gf_vasprintf (char **strp, const char *fmt, va_list ap)
920
{
921
  int vsn_ret, size;
922
  char *buffer, *realloc_buffer;
923
924
  size = 2 * (u32) strlen(fmt); /*first guess for the size*/
925
  buffer = (char*)gf_malloc(size);
926
  if (buffer == NULL)
927
    return -1;
928
929
  while (1) {
930
#if !defined(WIN32) && !defined(_WIN32_WCE)
931
#define _vsnprintf vsnprintf
932
#endif
933
    vsn_ret = _vsnprintf(buffer, size, fmt, ap);
934
935
    /* If that worked, return the string. */
936
    if (vsn_ret>-1 && vsn_ret<size) {
937
      *strp = buffer;
938
      return vsn_ret;
939
    }
940
941
    /*else double the allocated size*/
942
    size *= 2;
943
    realloc_buffer = (char*)gf_realloc(buffer, size);
944
    if (!realloc_buffer)  {
945
      gf_free(buffer);
946
      return -1;
947
    } else {
948
      buffer = realloc_buffer;
949
    }
950
951
  }
952
}
953
#endif
954
955
GF_EXPORT
956
int gf_asprintf(char **strp, const char *fmt, ...)
957
{
958
  s32 size;
959
  va_list args;
960
  va_start(args, fmt);
961
#if defined(WIN32) || defined(_WIN32_WCE) || (defined (__SVR4) && defined (__sun))
962
  size = gf_vasprintf(strp, fmt, args);
963
#else
964
  size = asprintf(strp, fmt, args);
965
#endif
966
  va_end(args);
967
  return size;
968
}
969
970
#endif //unused