blob: 1032462805aea406261fc5fa6ba4b5b8bf8b6556 [file] [log] [blame]
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * alloc.c: functions for memory management
12 */
13
14#include "vim.h"
15
16/**********************************************************************
17 * Various routines dealing with allocation and deallocation of memory.
18 */
19
20#if defined(MEM_PROFILE) || defined(PROTO)
21
22# define MEM_SIZES 8200
23static long_u mem_allocs[MEM_SIZES];
24static long_u mem_frees[MEM_SIZES];
25static long_u mem_allocated;
26static long_u mem_freed;
27static long_u mem_peak;
28static long_u num_alloc;
29static long_u num_freed;
30
31 static void
32mem_pre_alloc_s(size_t *sizep)
33{
34 *sizep += sizeof(size_t);
35}
36
37 static void
38mem_pre_alloc_l(size_t *sizep)
39{
40 *sizep += sizeof(size_t);
41}
42
43 static void
44mem_post_alloc(
45 void **pp,
46 size_t size)
47{
48 if (*pp == NULL)
49 return;
50 size -= sizeof(size_t);
51 *(long_u *)*pp = size;
52 if (size <= MEM_SIZES-1)
53 mem_allocs[size-1]++;
54 else
55 mem_allocs[MEM_SIZES-1]++;
56 mem_allocated += size;
57 if (mem_allocated - mem_freed > mem_peak)
58 mem_peak = mem_allocated - mem_freed;
59 num_alloc++;
60 *pp = (void *)((char *)*pp + sizeof(size_t));
61}
62
63 static void
64mem_pre_free(void **pp)
65{
66 long_u size;
67
68 *pp = (void *)((char *)*pp - sizeof(size_t));
69 size = *(size_t *)*pp;
70 if (size <= MEM_SIZES-1)
71 mem_frees[size-1]++;
72 else
73 mem_frees[MEM_SIZES-1]++;
74 mem_freed += size;
75 num_freed++;
76}
77
78/*
79 * called on exit via atexit()
80 */
81 void
82vim_mem_profile_dump(void)
83{
84 int i, j;
85
86 printf("\r\n");
87 j = 0;
88 for (i = 0; i < MEM_SIZES - 1; i++)
89 {
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +010090 if (mem_allocs[i] == 0 && mem_frees[i] == 0)
91 continue;
92
93 if (mem_frees[i] > mem_allocs[i])
94 printf("\r\n%s", _("ERROR: "));
95 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
96 j++;
97 if (j > 3)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +020098 {
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +010099 j = 0;
100 printf("\r\n");
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200101 }
102 }
103
104 i = MEM_SIZES - 1;
105 if (mem_allocs[i])
106 {
107 printf("\r\n");
108 if (mem_frees[i] > mem_allocs[i])
109 puts(_("ERROR: "));
110 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
111 }
112
113 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
114 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
115 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
116 num_alloc, num_freed);
117}
118
119#endif // MEM_PROFILE
120
121#ifdef FEAT_EVAL
122 int
123alloc_does_fail(size_t size)
124{
125 if (alloc_fail_countdown == 0)
126 {
127 if (--alloc_fail_repeat <= 0)
128 alloc_fail_id = 0;
129 do_outofmem_msg(size);
130 return TRUE;
131 }
132 --alloc_fail_countdown;
133 return FALSE;
134}
135#endif
136
137/*
138 * Some memory is reserved for error messages and for being able to
139 * call mf_release_all(), which needs some memory for mf_trans_add().
140 */
141#define KEEP_ROOM (2 * 8192L)
142#define KEEP_ROOM_KB (KEEP_ROOM / 1024L)
143
144/*
145 * The normal way to allocate memory. This handles an out-of-memory situation
146 * as well as possible, still returns NULL when we're completely out.
147 */
148 void *
149alloc(size_t size)
150{
151 return lalloc(size, TRUE);
152}
153
Dominique Pelle748b3082022-01-08 12:41:16 +0000154#if defined(FEAT_QUICKFIX) || defined(PROTO)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200155/*
156 * alloc() with an ID for alloc_fail().
157 */
158 void *
159alloc_id(size_t size, alloc_id_T id UNUSED)
160{
Bram Moolenaarf80f40a2022-08-25 16:02:23 +0100161# ifdef FEAT_EVAL
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200162 if (alloc_fail_id == id && alloc_does_fail(size))
163 return NULL;
Bram Moolenaarf80f40a2022-08-25 16:02:23 +0100164# endif
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200165 return lalloc(size, TRUE);
166}
Dominique Pelle748b3082022-01-08 12:41:16 +0000167#endif
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200168
169/*
170 * Allocate memory and set all bytes to zero.
171 */
172 void *
173alloc_clear(size_t size)
174{
175 void *p;
176
177 p = lalloc(size, TRUE);
178 if (p != NULL)
179 (void)vim_memset(p, 0, size);
180 return p;
181}
182
183/*
184 * Same as alloc_clear() but with allocation id for testing
185 */
186 void *
187alloc_clear_id(size_t size, alloc_id_T id UNUSED)
188{
189#ifdef FEAT_EVAL
190 if (alloc_fail_id == id && alloc_does_fail(size))
191 return NULL;
192#endif
193 return alloc_clear(size);
194}
195
196/*
197 * Allocate memory like lalloc() and set all bytes to zero.
198 */
199 void *
200lalloc_clear(size_t size, int message)
201{
202 void *p;
203
204 p = lalloc(size, message);
205 if (p != NULL)
206 (void)vim_memset(p, 0, size);
207 return p;
208}
209
210/*
211 * Low level memory allocation function.
212 * This is used often, KEEP IT FAST!
213 */
214 void *
215lalloc(size_t size, int message)
216{
217 void *p; // pointer to new storage space
218 static int releasing = FALSE; // don't do mf_release_all() recursive
219 int try_again;
220#if defined(HAVE_AVAIL_MEM)
221 static size_t allocated = 0; // allocated since last avail check
222#endif
223
224 // Safety check for allocating zero bytes
225 if (size == 0)
226 {
227 // Don't hide this message
228 emsg_silent = 0;
Bram Moolenaarf1474d82021-12-31 19:59:55 +0000229 iemsg(_(e_internal_error_lalloc_zero));
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200230 return NULL;
231 }
232
233#ifdef MEM_PROFILE
234 mem_pre_alloc_l(&size);
235#endif
236
Yegappan Lakshmanan8ee52af2021-08-09 19:59:06 +0200237 // Loop when out of memory: Try to release some memfile blocks and
238 // if some blocks are released call malloc again.
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200239 for (;;)
240 {
Dominique Pelleaf4a61a2021-12-27 17:21:41 +0000241 // Handle three kinds of systems:
Yegappan Lakshmanan8ee52af2021-08-09 19:59:06 +0200242 // 1. No check for available memory: Just return.
243 // 2. Slow check for available memory: call mch_avail_mem() after
244 // allocating KEEP_ROOM amount of memory.
245 // 3. Strict check for available memory: call mch_avail_mem()
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200246 if ((p = malloc(size)) != NULL)
247 {
248#ifndef HAVE_AVAIL_MEM
249 // 1. No check for available memory: Just return.
250 goto theend;
251#else
252 // 2. Slow check for available memory: call mch_avail_mem() after
253 // allocating (KEEP_ROOM / 2) amount of memory.
254 allocated += size;
255 if (allocated < KEEP_ROOM / 2)
256 goto theend;
257 allocated = 0;
258
259 // 3. check for available memory: call mch_avail_mem()
260 if (mch_avail_mem(TRUE) < KEEP_ROOM_KB && !releasing)
261 {
262 free(p); // System is low... no go!
263 p = NULL;
264 }
265 else
266 goto theend;
267#endif
268 }
Yegappan Lakshmanan8ee52af2021-08-09 19:59:06 +0200269 // Remember that mf_release_all() is being called to avoid an endless
270 // loop, because mf_release_all() may call alloc() recursively.
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200271 if (releasing)
272 break;
273 releasing = TRUE;
274
275 clear_sb_text(TRUE); // free any scrollback text
276 try_again = mf_release_all(); // release as many blocks as possible
277
278 releasing = FALSE;
279 if (!try_again)
280 break;
281 }
282
283 if (message && p == NULL)
284 do_outofmem_msg(size);
285
286theend:
287#ifdef MEM_PROFILE
288 mem_post_alloc(&p, size);
289#endif
290 return p;
291}
292
293/*
294 * lalloc() with an ID for alloc_fail().
295 */
296#if defined(FEAT_SIGNS) || defined(PROTO)
297 void *
298lalloc_id(size_t size, int message, alloc_id_T id UNUSED)
299{
300#ifdef FEAT_EVAL
301 if (alloc_fail_id == id && alloc_does_fail(size))
302 return NULL;
303#endif
304 return (lalloc(size, message));
305}
306#endif
307
308#if defined(MEM_PROFILE) || defined(PROTO)
309/*
310 * realloc() with memory profiling.
311 */
312 void *
313mem_realloc(void *ptr, size_t size)
314{
315 void *p;
316
317 mem_pre_free(&ptr);
318 mem_pre_alloc_s(&size);
319
320 p = realloc(ptr, size);
321
322 mem_post_alloc(&p, size);
323
324 return p;
325}
326#endif
327
328/*
329* Avoid repeating the error message many times (they take 1 second each).
330* Did_outofmem_msg is reset when a character is read.
331*/
332 void
333do_outofmem_msg(size_t size)
334{
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100335 if (did_outofmem_msg)
336 return;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200337
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100338 // Don't hide this message
339 emsg_silent = 0;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200340
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100341 // Must come first to avoid coming back here when printing the error
342 // message fails, e.g. when setting v:errmsg.
343 did_outofmem_msg = TRUE;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200344
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100345 semsg(_(e_out_of_memory_allocating_nr_bytes), (long_u)size);
346
347 if (starting == NO_SCREEN)
348 // Not even finished with initializations and already out of
349 // memory? Then nothing is going to work, exit.
350 mch_exit(123);
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200351}
352
353#if defined(EXITFREE) || defined(PROTO)
354
355/*
356 * Free everything that we allocated.
357 * Can be used to detect memory leaks, e.g., with ccmalloc.
358 * NOTE: This is tricky! Things are freed that functions depend on. Don't be
359 * surprised if Vim crashes...
360 * Some things can't be freed, esp. things local to a library function.
361 */
362 void
363free_all_mem(void)
364{
365 buf_T *buf, *nextbuf;
366
367 // When we cause a crash here it is caught and Vim tries to exit cleanly.
368 // Don't try freeing everything again.
369 if (entered_free_all_mem)
370 return;
371 entered_free_all_mem = TRUE;
372 // Don't want to trigger autocommands from here on.
373 block_autocmds();
374
375 // Close all tabs and windows. Reset 'equalalways' to avoid redraws.
376 p_ea = FALSE;
377 if (first_tabpage != NULL && first_tabpage->tp_next != NULL)
378 do_cmdline_cmd((char_u *)"tabonly!");
379 if (!ONE_WINDOW)
380 do_cmdline_cmd((char_u *)"only!");
381
382# if defined(FEAT_SPELL)
383 // Free all spell info.
384 spell_free_all();
385# endif
386
387# if defined(FEAT_BEVAL_TERM)
388 ui_remove_balloon();
389# endif
390# ifdef FEAT_PROP_POPUP
391 if (curwin != NULL)
392 close_all_popups(TRUE);
393# endif
394
395 // Clear user commands (before deleting buffers).
396 ex_comclear(NULL);
397
398 // When exiting from mainerr_arg_missing curbuf has not been initialized,
399 // and not much else.
400 if (curbuf != NULL)
401 {
402# ifdef FEAT_MENU
403 // Clear menus.
404 do_cmdline_cmd((char_u *)"aunmenu *");
zeertzjq79ae1522022-07-01 12:13:15 +0100405 do_cmdline_cmd((char_u *)"tlunmenu *");
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200406# ifdef FEAT_MULTI_LANG
407 do_cmdline_cmd((char_u *)"menutranslate clear");
408# endif
409# endif
410 // Clear mappings, abbreviations, breakpoints.
411 do_cmdline_cmd((char_u *)"lmapclear");
412 do_cmdline_cmd((char_u *)"xmapclear");
413 do_cmdline_cmd((char_u *)"mapclear");
414 do_cmdline_cmd((char_u *)"mapclear!");
415 do_cmdline_cmd((char_u *)"abclear");
416# if defined(FEAT_EVAL)
417 do_cmdline_cmd((char_u *)"breakdel *");
418# endif
419# if defined(FEAT_PROFILE)
420 do_cmdline_cmd((char_u *)"profdel *");
421# endif
422# if defined(FEAT_KEYMAP)
423 do_cmdline_cmd((char_u *)"set keymap=");
424# endif
425 }
426
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200427 free_titles();
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200428 free_findfile();
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200429
430 // Obviously named calls.
431 free_all_autocmds();
432 clear_termcodes();
433 free_all_marks();
434 alist_clear(&global_alist);
435 free_homedir();
436 free_users();
437 free_search_patterns();
438 free_old_sub();
439 free_last_insert();
440 free_insexpand_stuff();
441 free_prev_shellcmd();
442 free_regexp_stuff();
443 free_tag_stuff();
Yegappan Lakshmanan7645da52021-12-04 14:02:30 +0000444 free_xim_stuff();
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200445 free_cd_dir();
446# ifdef FEAT_SIGNS
447 free_signs();
448# endif
449# ifdef FEAT_EVAL
450 set_expr_line(NULL, NULL);
451# endif
452# ifdef FEAT_DIFF
453 if (curtab != NULL)
454 diff_clear(curtab);
455# endif
456 clear_sb_text(TRUE); // free any scrollback text
457
458 // Free some global vars.
459 free_username();
460# ifdef FEAT_CLIPBOARD
461 vim_regfree(clip_exclude_prog);
462# endif
463 vim_free(last_cmdline);
464 vim_free(new_last_cmdline);
465 set_keep_msg(NULL, 0);
466
467 // Clear cmdline history.
468 p_hi = 0;
469 init_history();
470# ifdef FEAT_PROP_POPUP
471 clear_global_prop_types();
472# endif
473
474# ifdef FEAT_QUICKFIX
475 {
476 win_T *win;
477 tabpage_T *tab;
478
479 qf_free_all(NULL);
480 // Free all location lists
481 FOR_ALL_TAB_WINDOWS(tab, win)
482 qf_free_all(win);
483 }
484# endif
485
486 // Close all script inputs.
487 close_all_scripts();
488
489 if (curwin != NULL)
490 // Destroy all windows. Must come before freeing buffers.
491 win_free_all();
492
493 // Free all option values. Must come after closing windows.
494 free_all_options();
495
496 // Free all buffers. Reset 'autochdir' to avoid accessing things that
497 // were freed already.
498# ifdef FEAT_AUTOCHDIR
499 p_acd = FALSE;
500# endif
501 for (buf = firstbuf; buf != NULL; )
502 {
503 bufref_T bufref;
504
505 set_bufref(&bufref, buf);
506 nextbuf = buf->b_next;
507 close_buffer(NULL, buf, DOBUF_WIPE, FALSE, FALSE);
508 if (bufref_valid(&bufref))
509 buf = nextbuf; // didn't work, try next one
510 else
511 buf = firstbuf;
512 }
513
514# ifdef FEAT_ARABIC
515 free_arshape_buf();
516# endif
517
518 // Clear registers.
519 clear_registers();
520 ResetRedobuff();
521 ResetRedobuff();
522
523# if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
524 vim_free(serverDelayedStartName);
525# endif
526
527 // highlight info
528 free_highlight();
529
530 reset_last_sourcing();
531
532 if (first_tabpage != NULL)
533 {
534 free_tabpage(first_tabpage);
535 first_tabpage = NULL;
536 }
537
538# ifdef UNIX
539 // Machine-specific free.
540 mch_free_mem();
541# endif
542
543 // message history
544 for (;;)
545 if (delete_first_msg() == FAIL)
546 break;
547
548# ifdef FEAT_JOB_CHANNEL
549 channel_free_all();
550# endif
551# ifdef FEAT_TIMERS
552 timer_free_all();
553# endif
554# ifdef FEAT_EVAL
555 // must be after channel_free_all() with unrefs partials
556 eval_clear();
557# endif
558# ifdef FEAT_JOB_CHANNEL
559 // must be after eval_clear() with unrefs jobs
560 job_free_all();
561# endif
562
563 free_termoptions();
Bram Moolenaarb3a29552021-11-19 11:28:04 +0000564 free_cur_term();
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200565
566 // screenlines (can't display anything now!)
567 free_screenlines();
568
569# if defined(FEAT_SOUND)
570 sound_free();
571# endif
572# if defined(USE_XSMP)
573 xsmp_close();
574# endif
575# ifdef FEAT_GUI_GTK
576 gui_mch_free_all();
577# endif
Bram Moolenaarc7269f82021-12-05 11:36:23 +0000578# ifdef FEAT_TCL
579 vim_tcl_finalize();
580# endif
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200581 clear_hl_tables();
582
583 vim_free(IObuff);
584 vim_free(NameBuff);
585# ifdef FEAT_QUICKFIX
586 check_quickfix_busy();
587# endif
Bram Moolenaar44ddf192022-06-21 22:15:25 +0100588# ifdef FEAT_EVAL
589 free_resub_eval_result();
590# endif
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200591}
592#endif
593
594/*
595 * Copy "p[len]" into allocated memory, ignoring NUL characters.
596 * Returns NULL when out of memory.
597 */
598 char_u *
599vim_memsave(char_u *p, size_t len)
600{
601 char_u *ret = alloc(len);
602
603 if (ret != NULL)
604 mch_memmove(ret, p, len);
605 return ret;
606}
607
608/*
609 * Replacement for free() that ignores NULL pointers.
610 * Also skip free() when exiting for sure, this helps when we caught a deadly
611 * signal that was caused by a crash in free().
612 * If you want to set NULL after calling this function, you should use
613 * VIM_CLEAR() instead.
614 */
615 void
616vim_free(void *x)
617{
618 if (x != NULL && !really_exiting)
619 {
620#ifdef MEM_PROFILE
621 mem_pre_free(&x);
622#endif
623 free(x);
624 }
625}
626
627/************************************************************************
628 * Functions for handling growing arrays.
629 */
630
631/*
632 * Clear an allocated growing array.
633 */
634 void
635ga_clear(garray_T *gap)
636{
637 vim_free(gap->ga_data);
638 ga_init(gap);
639}
640
641/*
642 * Clear a growing array that contains a list of strings.
643 */
644 void
645ga_clear_strings(garray_T *gap)
646{
647 int i;
648
649 if (gap->ga_data != NULL)
650 for (i = 0; i < gap->ga_len; ++i)
651 vim_free(((char_u **)(gap->ga_data))[i]);
652 ga_clear(gap);
653}
654
Dominique Pelle748b3082022-01-08 12:41:16 +0000655#if defined(FEAT_EVAL) || defined(PROTO)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200656/*
657 * Copy a growing array that contains a list of strings.
658 */
659 int
660ga_copy_strings(garray_T *from, garray_T *to)
661{
662 int i;
663
664 ga_init2(to, sizeof(char_u *), 1);
665 if (ga_grow(to, from->ga_len) == FAIL)
666 return FAIL;
667
668 for (i = 0; i < from->ga_len; ++i)
669 {
670 char_u *orig = ((char_u **)from->ga_data)[i];
671 char_u *copy;
672
673 if (orig == NULL)
674 copy = NULL;
675 else
676 {
677 copy = vim_strsave(orig);
678 if (copy == NULL)
679 {
680 to->ga_len = i;
681 ga_clear_strings(to);
682 return FAIL;
683 }
684 }
685 ((char_u **)to->ga_data)[i] = copy;
686 }
687 to->ga_len = from->ga_len;
688 return OK;
689}
Dominique Pelle748b3082022-01-08 12:41:16 +0000690#endif
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200691
692/*
693 * Initialize a growing array. Don't forget to set ga_itemsize and
694 * ga_growsize! Or use ga_init2().
695 */
696 void
697ga_init(garray_T *gap)
698{
699 gap->ga_data = NULL;
700 gap->ga_maxlen = 0;
701 gap->ga_len = 0;
702}
703
704 void
Bram Moolenaar9f1a39a2022-01-08 15:39:39 +0000705ga_init2(garray_T *gap, size_t itemsize, int growsize)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200706{
707 ga_init(gap);
K.Takata1a804522022-01-26 16:45:20 +0000708 gap->ga_itemsize = (int)itemsize;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200709 gap->ga_growsize = growsize;
710}
711
712/*
713 * Make room in growing array "gap" for at least "n" items.
714 * Return FAIL for failure, OK otherwise.
715 */
716 int
717ga_grow(garray_T *gap, int n)
718{
719 if (gap->ga_maxlen - gap->ga_len < n)
720 return ga_grow_inner(gap, n);
721 return OK;
722}
723
Yegappan Lakshmanan7c7e19c2022-04-09 11:09:07 +0100724/*
725 * Same as ga_grow() but uses an allocation id for testing.
726 */
727 int
728ga_grow_id(garray_T *gap, int n, alloc_id_T id UNUSED)
729{
730#ifdef FEAT_EVAL
731 if (alloc_fail_id == id && alloc_does_fail(sizeof(list_T)))
732 return FAIL;
733#endif
734
735 return ga_grow(gap, n);
736}
737
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200738 int
739ga_grow_inner(garray_T *gap, int n)
740{
741 size_t old_len;
742 size_t new_len;
743 char_u *pp;
744
745 if (n < gap->ga_growsize)
746 n = gap->ga_growsize;
747
748 // A linear growth is very inefficient when the array grows big. This
749 // is a compromise between allocating memory that won't be used and too
750 // many copy operations. A factor of 1.5 seems reasonable.
751 if (n < gap->ga_len / 2)
752 n = gap->ga_len / 2;
753
=?UTF-8?q?Dundar=20G=C3=B6c?=d5cec1f2022-01-29 15:19:23 +0000754 new_len = (size_t)gap->ga_itemsize * (gap->ga_len + n);
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200755 pp = vim_realloc(gap->ga_data, new_len);
756 if (pp == NULL)
757 return FAIL;
=?UTF-8?q?Dundar=20G=C3=B6c?=d5cec1f2022-01-29 15:19:23 +0000758 old_len = (size_t)gap->ga_itemsize * gap->ga_maxlen;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200759 vim_memset(pp + old_len, 0, new_len - old_len);
760 gap->ga_maxlen = gap->ga_len + n;
761 gap->ga_data = pp;
762 return OK;
763}
764
765/*
766 * For a growing array that contains a list of strings: concatenate all the
767 * strings with a separating "sep".
768 * Returns NULL when out of memory.
769 */
770 char_u *
771ga_concat_strings(garray_T *gap, char *sep)
772{
773 int i;
774 int len = 0;
775 int sep_len = (int)STRLEN(sep);
776 char_u *s;
777 char_u *p;
778
779 for (i = 0; i < gap->ga_len; ++i)
780 len += (int)STRLEN(((char_u **)(gap->ga_data))[i]) + sep_len;
781
782 s = alloc(len + 1);
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100783 if (s == NULL)
784 return NULL;
785
786 *s = NUL;
787 p = s;
788 for (i = 0; i < gap->ga_len; ++i)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200789 {
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100790 if (p != s)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200791 {
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100792 STRCPY(p, sep);
793 p += sep_len;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200794 }
Yegappan Lakshmananb1f471e2022-09-05 14:33:47 +0100795 STRCPY(p, ((char_u **)(gap->ga_data))[i]);
796 p += STRLEN(p);
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200797 }
798 return s;
799}
800
801/*
802 * Make a copy of string "p" and add it to "gap".
803 * When out of memory nothing changes and FAIL is returned.
804 */
805 int
Bram Moolenaar9f1a39a2022-01-08 15:39:39 +0000806ga_copy_string(garray_T *gap, char_u *p)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200807{
808 char_u *cp = vim_strsave(p);
809
810 if (cp == NULL)
811 return FAIL;
812
813 if (ga_grow(gap, 1) == FAIL)
814 {
815 vim_free(cp);
816 return FAIL;
817 }
818 ((char_u **)(gap->ga_data))[gap->ga_len++] = cp;
819 return OK;
820}
821
822/*
Bram Moolenaar9f1a39a2022-01-08 15:39:39 +0000823 * Add string "p" to "gap".
824 * When out of memory "p" is freed and FAIL is returned.
825 */
826 int
827ga_add_string(garray_T *gap, char_u *p)
828{
829 if (ga_grow(gap, 1) == FAIL)
830 return FAIL;
831 ((char_u **)(gap->ga_data))[gap->ga_len++] = p;
832 return OK;
833}
834
835/*
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200836 * Concatenate a string to a growarray which contains bytes.
Bram Moolenaar0abc2872022-05-10 13:24:30 +0100837 * When "s" is NULL memory allocation fails does not do anything.
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200838 * Note: Does NOT copy the NUL at the end!
839 */
840 void
841ga_concat(garray_T *gap, char_u *s)
842{
843 int len;
844
845 if (s == NULL || *s == NUL)
846 return;
847 len = (int)STRLEN(s);
848 if (ga_grow(gap, len) == OK)
849 {
850 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
851 gap->ga_len += len;
852 }
853}
854
855/*
856 * Concatenate 'len' bytes from string 's' to a growarray.
857 * When "s" is NULL does not do anything.
858 */
859 void
860ga_concat_len(garray_T *gap, char_u *s, size_t len)
861{
Yegappan Lakshmanan36a5b682022-03-19 12:56:51 +0000862 if (s == NULL || *s == NUL || len == 0)
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200863 return;
864 if (ga_grow(gap, (int)len) == OK)
865 {
866 mch_memmove((char *)gap->ga_data + gap->ga_len, s, len);
867 gap->ga_len += (int)len;
868 }
869}
870
871/*
872 * Append one byte to a growarray which contains bytes.
873 */
Bram Moolenaar0abc2872022-05-10 13:24:30 +0100874 int
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200875ga_append(garray_T *gap, int c)
876{
Bram Moolenaar0abc2872022-05-10 13:24:30 +0100877 if (ga_grow(gap, 1) == FAIL)
878 return FAIL;
879 *((char *)gap->ga_data + gap->ga_len) = c;
880 ++gap->ga_len;
881 return OK;
Yegappan Lakshmanancbae5802021-08-06 21:51:55 +0200882}
883
884#if (defined(UNIX) && !defined(USE_SYSTEM)) || defined(MSWIN) \
885 || defined(PROTO)
886/*
887 * Append the text in "gap" below the cursor line and clear "gap".
888 */
889 void
890append_ga_line(garray_T *gap)
891{
892 // Remove trailing CR.
893 if (gap->ga_len > 0
894 && !curbuf->b_p_bin
895 && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
896 --gap->ga_len;
897 ga_append(gap, NUL);
898 ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
899 gap->ga_len = 0;
900}
901#endif
902