msvcrt: NULL terminate strings returned by _Getdays and _Getmonths.
[wine] / dlls / msvcrt / heap.c
1 /*
2  * msvcrt.dll heap functions
3  *
4  * Copyright 2000 Jon Griffiths
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Note: Win32 heap operations are MT safe. We only lock the new
21  *       handler and non atomic heap operations
22  */
23
24 #include "msvcrt.h"
25 #include "mtdll.h"
26 #include "wine/debug.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
29
30 /* MT */
31 #define LOCK_HEAP   _mlock( _HEAP_LOCK )
32 #define UNLOCK_HEAP _munlock( _HEAP_LOCK )
33
34 /* _aligned */
35 #define SAVED_PTR(x) ((void *)((DWORD_PTR)((char *)x - sizeof(void *)) & \
36                                ~(sizeof(void *) - 1)))
37 #define ALIGN_PTR(ptr, alignment, offset) ((void *) \
38     ((((DWORD_PTR)((char *)ptr + alignment + sizeof(void *) + offset)) & \
39       ~(alignment - 1)) - offset))
40
41
42 typedef int (CDECL *MSVCRT_new_handler_func)(MSVCRT_size_t size);
43
44 static MSVCRT_new_handler_func MSVCRT_new_handler;
45 static int MSVCRT_new_mode;
46
47 /* FIXME - According to documentation it should be 8*1024, at runtime it returns 16 */ 
48 static unsigned int MSVCRT_amblksiz = 16;
49 /* FIXME - According to documentation it should be 480 bytes, at runtime default is 0 */
50 static MSVCRT_size_t MSVCRT_sbh_threshold = 0;
51
52 /*********************************************************************
53  *              ??2@YAPAXI@Z (MSVCRT.@)
54  */
55 void* CDECL MSVCRT_operator_new(MSVCRT_size_t size)
56 {
57   void *retval;
58   int freed;
59
60   do
61   {
62     retval = HeapAlloc(GetProcessHeap(), 0, size);
63     if(retval)
64     {
65       TRACE("(%ld) returning %p\n", size, retval);
66       return retval;
67     }
68
69     LOCK_HEAP;
70     if(MSVCRT_new_handler)
71       freed = (*MSVCRT_new_handler)(size);
72     else
73       freed = 0;
74     UNLOCK_HEAP;
75   } while(freed);
76
77   TRACE("(%ld) out of memory\n", size);
78   return NULL;
79 }
80
81
82 /*********************************************************************
83  *              ??2@YAPAXIHPBDH@Z (MSVCRT.@)
84  */
85 void* CDECL MSVCRT_operator_new_dbg(MSVCRT_size_t size, int type, const char *file, int line)
86 {
87     return MSVCRT_operator_new( size );
88 }
89
90
91 /*********************************************************************
92  *              ??3@YAXPAX@Z (MSVCRT.@)
93  */
94 void CDECL MSVCRT_operator_delete(void *mem)
95 {
96   TRACE("(%p)\n", mem);
97   HeapFree(GetProcessHeap(), 0, mem);
98 }
99
100
101 /*********************************************************************
102  *              ?_query_new_handler@@YAP6AHI@ZXZ (MSVCRT.@)
103  */
104 MSVCRT_new_handler_func CDECL MSVCRT__query_new_handler(void)
105 {
106   return MSVCRT_new_handler;
107 }
108
109
110 /*********************************************************************
111  *              ?_query_new_mode@@YAHXZ (MSVCRT.@)
112  */
113 int CDECL MSVCRT__query_new_mode(void)
114 {
115   return MSVCRT_new_mode;
116 }
117
118 /*********************************************************************
119  *              ?_set_new_handler@@YAP6AHI@ZP6AHI@Z@Z (MSVCRT.@)
120  */
121 MSVCRT_new_handler_func CDECL MSVCRT__set_new_handler(MSVCRT_new_handler_func func)
122 {
123   MSVCRT_new_handler_func old_handler;
124   LOCK_HEAP;
125   old_handler = MSVCRT_new_handler;
126   MSVCRT_new_handler = func;
127   UNLOCK_HEAP;
128   return old_handler;
129 }
130
131 /*********************************************************************
132  *              ?set_new_handler@@YAP6AXXZP6AXXZ@Z (MSVCRT.@)
133  */
134 MSVCRT_new_handler_func CDECL MSVCRT_set_new_handler(void *func)
135 {
136   TRACE("(%p)\n",func);
137   MSVCRT__set_new_handler(NULL);
138   return NULL;
139 }
140
141 /*********************************************************************
142  *              ?_set_new_mode@@YAHH@Z (MSVCRT.@)
143  */
144 int CDECL MSVCRT__set_new_mode(int mode)
145 {
146   int old_mode;
147   LOCK_HEAP;
148   old_mode = MSVCRT_new_mode;
149   MSVCRT_new_mode = mode;
150   UNLOCK_HEAP;
151   return old_mode;
152 }
153
154 /*********************************************************************
155  *              _callnewh (MSVCRT.@)
156  */
157 int CDECL _callnewh(MSVCRT_size_t size)
158 {
159   if(MSVCRT_new_handler)
160     (*MSVCRT_new_handler)(size);
161   return 0;
162 }
163
164 /*********************************************************************
165  *              _expand (MSVCRT.@)
166  */
167 void* CDECL _expand(void* mem, MSVCRT_size_t size)
168 {
169   return HeapReAlloc(GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, mem, size);
170 }
171
172 /*********************************************************************
173  *              _heapchk (MSVCRT.@)
174  */
175 int CDECL _heapchk(void)
176 {
177   if (!HeapValidate( GetProcessHeap(), 0, NULL))
178   {
179     msvcrt_set_errno(GetLastError());
180     return MSVCRT__HEAPBADNODE;
181   }
182   return MSVCRT__HEAPOK;
183 }
184
185 /*********************************************************************
186  *              _heapmin (MSVCRT.@)
187  */
188 int CDECL _heapmin(void)
189 {
190   if (!HeapCompact( GetProcessHeap(), 0 ))
191   {
192     if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
193       msvcrt_set_errno(GetLastError());
194     return -1;
195   }
196   return 0;
197 }
198
199 /*********************************************************************
200  *              _heapwalk (MSVCRT.@)
201  */
202 int CDECL _heapwalk(struct MSVCRT__heapinfo* next)
203 {
204   PROCESS_HEAP_ENTRY phe;
205
206   LOCK_HEAP;
207   phe.lpData = next->_pentry;
208   phe.cbData = next->_size;
209   phe.wFlags = next->_useflag == MSVCRT__USEDENTRY ? PROCESS_HEAP_ENTRY_BUSY : 0;
210
211   if (phe.lpData && phe.wFlags & PROCESS_HEAP_ENTRY_BUSY &&
212       !HeapValidate( GetProcessHeap(), 0, phe.lpData ))
213   {
214     UNLOCK_HEAP;
215     msvcrt_set_errno(GetLastError());
216     return MSVCRT__HEAPBADNODE;
217   }
218
219   do
220   {
221     if (!HeapWalk( GetProcessHeap(), &phe ))
222     {
223       UNLOCK_HEAP;
224       if (GetLastError() == ERROR_NO_MORE_ITEMS)
225          return MSVCRT__HEAPEND;
226       msvcrt_set_errno(GetLastError());
227       if (!phe.lpData)
228         return MSVCRT__HEAPBADBEGIN;
229       return MSVCRT__HEAPBADNODE;
230     }
231   } while (phe.wFlags & (PROCESS_HEAP_REGION|PROCESS_HEAP_UNCOMMITTED_RANGE));
232
233   UNLOCK_HEAP;
234   next->_pentry = phe.lpData;
235   next->_size = phe.cbData;
236   next->_useflag = phe.wFlags & PROCESS_HEAP_ENTRY_BUSY ? MSVCRT__USEDENTRY : MSVCRT__FREEENTRY;
237   return MSVCRT__HEAPOK;
238 }
239
240 /*********************************************************************
241  *              _heapset (MSVCRT.@)
242  */
243 int CDECL _heapset(unsigned int value)
244 {
245   int retval;
246   struct MSVCRT__heapinfo heap;
247
248   memset( &heap, 0, sizeof(heap) );
249   LOCK_HEAP;
250   while ((retval = _heapwalk(&heap)) == MSVCRT__HEAPOK)
251   {
252     if (heap._useflag == MSVCRT__FREEENTRY)
253       memset(heap._pentry, value, heap._size);
254   }
255   UNLOCK_HEAP;
256   return retval == MSVCRT__HEAPEND? MSVCRT__HEAPOK : retval;
257 }
258
259 /*********************************************************************
260  *              _heapadd (MSVCRT.@)
261  */
262 int CDECL _heapadd(void* mem, MSVCRT_size_t size)
263 {
264   TRACE("(%p,%ld) unsupported in Win32\n", mem,size);
265   *MSVCRT__errno() = MSVCRT_ENOSYS;
266   return -1;
267 }
268
269 /*********************************************************************
270  *              _heapadd (MSVCRT.@)
271  */
272 MSVCRT_intptr_t CDECL _get_heap_handle(void)
273 {
274     return (MSVCRT_intptr_t)GetProcessHeap();
275 }
276
277 /*********************************************************************
278  *              _msize (MSVCRT.@)
279  */
280 MSVCRT_size_t CDECL _msize(void* mem)
281 {
282   MSVCRT_size_t size = HeapSize(GetProcessHeap(),0,mem);
283   if (size == ~(MSVCRT_size_t)0)
284   {
285     WARN(":Probably called with non wine-allocated memory, ret = -1\n");
286     /* At least the Win32 crtdll/msvcrt also return -1 in this case */
287   }
288   return size;
289 }
290
291 /*********************************************************************
292  *              calloc (MSVCRT.@)
293  */
294 void* CDECL MSVCRT_calloc(MSVCRT_size_t size, MSVCRT_size_t count)
295 {
296   return HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size * count );
297 }
298
299 /*********************************************************************
300  *              free (MSVCRT.@)
301  */
302 void CDECL MSVCRT_free(void* ptr)
303 {
304   HeapFree(GetProcessHeap(),0,ptr);
305 }
306
307 /*********************************************************************
308  *                  malloc (MSVCRT.@)
309  */
310 void* CDECL MSVCRT_malloc(MSVCRT_size_t size)
311 {
312   void *ret = HeapAlloc(GetProcessHeap(),0,size);
313   if (!ret)
314       *MSVCRT__errno() = MSVCRT_ENOMEM;
315   return ret;
316 }
317
318 /*********************************************************************
319  *              realloc (MSVCRT.@)
320  */
321 void* CDECL MSVCRT_realloc(void* ptr, MSVCRT_size_t size)
322 {
323   if (!ptr) return MSVCRT_malloc(size);
324   if (size) return HeapReAlloc(GetProcessHeap(), 0, ptr, size);
325   MSVCRT_free(ptr);
326   return NULL;
327 }
328
329 /*********************************************************************
330  *              __p__amblksiz (MSVCRT.@)
331  */
332 unsigned int* CDECL __p__amblksiz(void)
333 {
334   return &MSVCRT_amblksiz;
335 }
336
337 /*********************************************************************
338  *              _get_sbh_threshold (MSVCRT.@)
339  */
340 MSVCRT_size_t CDECL _get_sbh_threshold(void)
341 {
342   return MSVCRT_sbh_threshold;
343 }
344
345 /*********************************************************************
346  *              _set_sbh_threshold (MSVCRT.@)
347  */
348 int CDECL _set_sbh_threshold(MSVCRT_size_t threshold)
349 {
350   if(threshold > 1016)
351      return 0;
352   else
353      MSVCRT_sbh_threshold = threshold;
354   return 1;
355 }
356
357 /*********************************************************************
358  *              _aligned_free (MSVCRT.@)
359  */
360 void CDECL _aligned_free(void *memblock)
361 {
362     TRACE("(%p)\n", memblock);
363
364     if (memblock)
365     {
366         void **saved = SAVED_PTR(memblock);
367         MSVCRT_free(*saved);
368     }
369 }
370
371 /*********************************************************************
372  *              _aligned_offset_malloc (MSVCRT.@)
373  */
374 void * CDECL _aligned_offset_malloc(MSVCRT_size_t size, MSVCRT_size_t alignment, MSVCRT_size_t offset)
375 {
376     void *memblock, *temp, **saved;
377     TRACE("(%lu, %lu, %lu)\n", size, alignment, offset);
378
379     /* alignment must be a power of 2 */
380     if ((alignment & (alignment - 1)) != 0)
381     {
382         *MSVCRT__errno() = MSVCRT_EINVAL;
383         return NULL;
384     }
385
386     /* offset must be less than size */
387     if (offset >= size)
388     {
389         *MSVCRT__errno() = MSVCRT_EINVAL;
390         return NULL;
391     }
392
393     /* don't align to less than void pointer size */
394     if (alignment < sizeof(void *))
395         alignment = sizeof(void *);
396
397     /* allocate enough space for void pointer and alignment */
398     temp = MSVCRT_malloc(size + alignment + sizeof(void *));
399
400     if (!temp)
401         return NULL;
402
403     /* adjust pointer for proper alignment and offset */
404     memblock = ALIGN_PTR(temp, alignment, offset);
405
406     /* Save the real allocation address below returned address */
407     /* so it can be found later to free. */
408     saved = SAVED_PTR(memblock);
409     *saved = temp;
410
411     return memblock;
412 }
413
414 /*********************************************************************
415  *              _aligned_malloc (MSVCRT.@)
416  */
417 void * CDECL _aligned_malloc(MSVCRT_size_t size, MSVCRT_size_t alignment)
418 {
419     TRACE("(%lu, %lu)\n", size, alignment);
420     return _aligned_offset_malloc(size, alignment, 0);
421 }
422
423 /*********************************************************************
424  *              _aligned_offset_realloc (MSVCRT.@)
425  */
426 void * CDECL _aligned_offset_realloc(void *memblock, MSVCRT_size_t size,
427                                      MSVCRT_size_t alignment, MSVCRT_size_t offset)
428 {
429     void * temp, **saved;
430     MSVCRT_size_t old_padding, new_padding, old_size;
431     TRACE("(%p, %lu, %lu, %lu)\n", memblock, size, alignment, offset);
432
433     if (!memblock)
434         return _aligned_offset_malloc(size, alignment, offset);
435
436     /* alignment must be a power of 2 */
437     if ((alignment & (alignment - 1)) != 0)
438     {
439         *MSVCRT__errno() = MSVCRT_EINVAL;
440         return NULL;
441     }
442
443     /* offset must be less than size */
444     if (offset >= size)
445     {
446         *MSVCRT__errno() = MSVCRT_EINVAL;
447         return NULL;
448     }
449
450     if (size == 0)
451     {
452         _aligned_free(memblock);
453         return NULL;
454     }
455
456     /* don't align to less than void pointer size */
457     if (alignment < sizeof(void *))
458         alignment = sizeof(void *);
459
460     /* make sure alignment and offset didn't change */
461     saved = SAVED_PTR(memblock);
462     if (memblock != ALIGN_PTR(*saved, alignment, offset))
463     {
464         *MSVCRT__errno() = MSVCRT_EINVAL;
465         return NULL;
466     }
467
468     old_padding = (char *)memblock - (char *)*saved;
469
470     /* Get previous size of block */
471     old_size = _msize(*saved);
472     if (old_size == -1)
473     {
474         /* It seems this function was called with an invalid pointer. Bail out. */
475         return NULL;
476     }
477
478     /* Adjust old_size to get amount of actual data in old block. */
479     if (old_size < old_padding)
480     {
481         /* Shouldn't happen. Something's weird, so bail out. */
482         return NULL;
483     }
484     old_size -= old_padding;
485
486     temp = MSVCRT_realloc(*saved, size + alignment + sizeof(void *));
487
488     if (!temp)
489         return NULL;
490
491     /* adjust pointer for proper alignment and offset */
492     memblock = ALIGN_PTR(temp, alignment, offset);
493
494     /* Save the real allocation address below returned address */
495     /* so it can be found later to free. */
496     saved = SAVED_PTR(memblock);
497
498     new_padding = (char *)memblock - (char *)temp;
499
500 /*
501    Memory layout of old block is as follows:
502    +-------+---------------------+-+--------------------------+-----------+
503    |  ...  | "old_padding" bytes | | ... "old_size" bytes ... |    ...    |
504    +-------+---------------------+-+--------------------------+-----------+
505            ^                     ^ ^
506            |                     | |
507         *saved               saved memblock
508
509    Memory layout of new block is as follows:
510    +-------+-----------------------------+-+----------------------+-------+
511    |  ...  |    "new_padding" bytes      | | ... "size" bytes ... |  ...  |
512    +-------+-----------------------------+-+----------------------+-------+
513            ^                             ^ ^
514            |                             | |
515           temp                       saved memblock
516
517    However, in the new block, actual data is still written as follows
518    (because it was copied by MSVCRT_realloc):
519    +-------+---------------------+--------------------------------+-------+
520    |  ...  | "old_padding" bytes |   ... "old_size" bytes ...     |  ...  |
521    +-------+---------------------+--------------------------------+-------+
522            ^                             ^ ^
523            |                             | |
524           temp                       saved memblock
525
526    Therefore, min(old_size,size) bytes of actual data have to be moved
527    from the offset they were at in the old block (temp + old_padding),
528    to the offset they have to be in the new block (temp + new_padding == memblock).
529 */
530     if (new_padding != old_padding)
531         memmove((char *)memblock, (char *)temp + old_padding, (old_size < size) ? old_size : size);
532
533     *saved = temp;
534
535     return memblock;
536 }
537
538 /*********************************************************************
539  *              _aligned_realloc (MSVCRT.@)
540  */
541 void * CDECL _aligned_realloc(void *memblock, MSVCRT_size_t size, MSVCRT_size_t alignment)
542 {
543     TRACE("(%p, %lu, %lu)\n", memblock, size, alignment);
544     return _aligned_offset_realloc(memblock, size, alignment, 0);
545 }
546
547 /*********************************************************************
548  *              memmove_s (MSVCRT.@)
549  */
550 int CDECL memmove_s(void *dest, MSVCRT_size_t numberOfElements, const void *src, MSVCRT_size_t count)
551 {
552     TRACE("(%p %lu %p %lu)\n", dest, numberOfElements, src, count);
553
554     if(!count)
555         return 0;
556
557     if(!dest || !src) {
558         if(dest)
559             memset(dest, 0, numberOfElements);
560
561         *MSVCRT__errno() = MSVCRT_EINVAL;
562         return MSVCRT_EINVAL;
563     }
564
565     if(count > numberOfElements) {
566         memset(dest, 0, numberOfElements);
567
568         *MSVCRT__errno() = MSVCRT_ERANGE;
569         return MSVCRT_ERANGE;
570     }
571
572     memmove(dest, src, count);
573     return 0;
574 }
575
576 /*********************************************************************
577  *              strncpy_s (MSVCRT.@)
578  */
579 int CDECL strncpy_s(char *dest, MSVCRT_size_t numberOfElements,
580         const char *src, MSVCRT_size_t count)
581 {
582     MSVCRT_size_t i, end;
583
584     TRACE("(%s %lu %s %lu)\n", dest, numberOfElements, src, count);
585
586     if(!count)
587         return 0;
588
589     if (!MSVCRT_CHECK_PMT(dest != NULL) || !MSVCRT_CHECK_PMT(src != NULL) || !MSVCRT_CHECK_PMT(numberOfElements != 0)) {
590         *MSVCRT__errno() = MSVCRT_EINVAL;
591         return MSVCRT_EINVAL;
592     }
593
594     if(count!=MSVCRT__TRUNCATE && count<numberOfElements)
595         end = count;
596     else
597         end = numberOfElements-1;
598
599     for(i=0; i<end && src[i]; i++)
600         dest[i] = src[i];
601
602     if(!src[i] || end==count || count==MSVCRT__TRUNCATE) {
603         dest[i] = '\0';
604         return 0;
605     }
606
607     MSVCRT_INVALID_PMT("dest[numberOfElements] is too small");
608     dest[0] = '\0';
609     *MSVCRT__errno() = MSVCRT_EINVAL;
610     return MSVCRT_EINVAL;
611 }