Imported Upstream version 1.22.4
[platform/upstream/groff.git] / src / libs / libgroff / new.cpp
1 /* Copyright (C) 1989-2018 Free Software Foundation, Inc.
2      Written by James Clark (jjc@jclark.com)
3
4 This file is part of groff.
5
6 groff is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 groff is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program.  If not, see <http://www.gnu.org/licenses/>. */
18
19 #include "lib.h"
20
21 #include <stddef.h>
22 #include <stdlib.h>
23
24 #include "posix.h"
25 #include "nonposix.h"
26
27 extern "C" const char *program_name;
28
29 static void ewrite(const char *s)
30 {
31   write(2, s, strlen(s));
32 }
33
34 void *operator new(size_t size)
35 {
36   // Avoid relying on the behaviour of malloc(0).
37   if (size == 0)
38     size++;
39 #ifdef COOKIE_BUG
40   char *p = (char *)malloc(unsigned(size + 8));
41 #else /* not COOKIE_BUG */
42   char *p = (char *)malloc(unsigned(size));
43 #endif /* not COOKIE_BUG */
44   if (p == 0) {
45     if (program_name) {
46       ewrite(program_name);
47       ewrite(": ");
48     }
49     ewrite("out of memory\n");
50     _exit(-1);
51   }
52 #ifdef COOKIE_BUG
53   ((unsigned *)p)[1] = 0;
54   return p + 8;
55 #else /* not COOKIE_BUG */
56   return p;
57 #endif /* not COOKIE_BUG */
58 }
59
60 void operator delete(void *p)
61 {
62 #ifdef COOKIE_BUG
63   if (p)
64     free((void *)((char *)p - 8));
65 #else
66   if (p)
67     free(p);
68 #endif /* COOKIE_BUG */
69 }
70
71 void operator delete(void *p,
72                      __attribute__((__unused__)) long unsigned int size)
73 {
74   // It's ugly to duplicate the code from delete(void *) above, but if
75   // we don't, g++ 6.3 can't figure out we're calling through it to
76   // free().
77   //
78   // In function 'void operator delete(void*, long unsigned int)':
79   //   warning: deleting 'void*' is undefined [-Wdelete-incomplete]
80   //delete p;
81 #ifdef COOKIE_BUG
82   if (p)
83     free((void *)((char *)p - 8));
84 #else
85   if (p)
86     free(p);
87 #endif /* COOKIE_BUG */
88 }