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