robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 9a29622b3b00ddb601

master
27.2 KiB1022 linesraw
1// Various routines dealing with allocation and deallocation of memory.
2
3#include <assert.h>
4#include <inttypes.h>
5#include <stdbool.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9#include <time.h>
10
11#include "nvim/api/extmark.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/api/ui.h"
14#include "nvim/arglist.h"
15#include "nvim/ascii_defs.h"
16#include "nvim/buffer_defs.h"
17#include "nvim/buffer_updates.h"
18#include "nvim/channel.h"
19#include "nvim/decoration_provider.h"
20#include "nvim/drawline.h"
21#include "nvim/errors.h"
22#include "nvim/eval.h"
23#include "nvim/gettext_defs.h"
24#include "nvim/globals.h"
25#include "nvim/highlight.h"
26#include "nvim/highlight_group.h"
27#include "nvim/input_cmdatom.h"
28#include "nvim/insexpand.h"
29#include "nvim/lua/executor.h"
30#include "nvim/main.h"
31#include "nvim/map_defs.h"
32#include "nvim/mapping.h"
33#include "nvim/mcursor.h"
34#include "nvim/memfile.h"
35#include "nvim/memory.h"
36#include "nvim/message.h"
37#include "nvim/normal.h"
38#include "nvim/option_vars.h"
39#include "nvim/sign.h"
40#include "nvim/state_defs.h"
41#include "nvim/statusline.h"
42#include "nvim/types_defs.h"
43#include "nvim/ui.h"
44#include "nvim/ui_client.h"
45#include "nvim/ui_compositor.h"
46#include "nvim/usercmd.h"
47
48#ifdef UNIT_TESTING
49# define malloc(size) mem_malloc(size)
50# define calloc(count, size) mem_calloc(count, size)
51# define realloc(ptr, size) mem_realloc(ptr, size)
52# define free(ptr) mem_free(ptr)
53MemMalloc mem_malloc = &malloc;
54MemFree mem_free = &free;
55MemCalloc mem_calloc = &calloc;
56MemRealloc mem_realloc = &realloc;
57#endif
58
59#include "memory.c.generated.h"
60
61#ifdef EXITFREE
62bool entered_free_all_mem = false;
63#endif
64
65/// Try to free memory. Used when trying to recover from out of memory errors.
66/// @see {xmalloc}
67static void try_to_free_memory(void)
68{
69  static bool trying_to_free = false;
70  // avoid recursive calls
71  if (trying_to_free) {
72    return;
73  }
74  trying_to_free = true;
75
76  // free any scrollback text
77  clear_sb_text(true);
78  // Try to save all buffers and release as many blocks as possible
79  mf_release_all();
80
81  arena_free_reuse_blks();
82
83  trying_to_free = false;
84}
85
86/// Avoid repeating the error message many times (they take 1 second each).
87/// `did_outofmem_msg` is reset when a character is read.
88static void do_outofmem_msg(size_t size)
89{
90  if (did_outofmem_msg) {
91    return;
92  }
93
94  // Don't hide this message
95  emsg_silent = 0;
96
97  // Must come first to avoid coming back here when printing the error
98  // message fails, e.g. when setting v:errmsg.
99  did_outofmem_msg = true;
100
101  semsg(_("E342: Out of memory!  (allocating %" PRIu64 " bytes)"), (uint64_t)size);
102}
103
104/// malloc() wrapper
105///
106/// try_malloc() is a malloc() wrapper that tries to free some memory before
107/// trying again.
108///
109/// @see {try_to_free_memory}
110/// @param size
111/// @return pointer to allocated space. NULL if out of memory
112void *try_malloc(size_t size) FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE(1)
113{
114  size_t allocated_size = size ? size : 1;
115  void *ret = malloc(allocated_size);
116  if (!ret) {
117    try_to_free_memory();
118    ret = malloc(allocated_size);
119  }
120  return ret;
121}
122
123/// try_malloc() wrapper that shows an out-of-memory error message to the user
124/// before returning NULL
125///
126/// @see {try_malloc}
127/// @param size
128/// @return pointer to allocated space. NULL if out of memory
129void *verbose_try_malloc(size_t size) FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE(1)
130{
131  void *ret = try_malloc(size);
132  if (!ret) {
133    do_outofmem_msg(size);
134  }
135  return ret;
136}
137
138/// malloc() wrapper that never returns NULL
139///
140/// xmalloc() succeeds or gracefully aborts when out of memory.
141/// Before aborting try to free some memory and call malloc again.
142///
143/// @see {try_to_free_memory}
144/// @param size
145/// @return pointer to allocated space. Never NULL
146void *xmalloc(size_t size)
147  FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE(1) FUNC_ATTR_NONNULL_RET
148{
149  void *ret = try_malloc(size);
150  if (!ret) {
151    preserve_exit(e_outofmem);
152  }
153  return ret;
154}
155
156/// free() wrapper that delegates to the backing memory manager
157///
158/// @note Use XFREE_CLEAR() instead, if possible.
159void xfree(void *ptr)
160{
161  free(ptr);
162}
163
164/// calloc() wrapper
165///
166/// @see {xmalloc}
167/// @param count
168/// @param size
169/// @return pointer to allocated space. Never NULL
170void *xcalloc(size_t count, size_t size)
171  FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE_PROD(1, 2) FUNC_ATTR_NONNULL_RET
172{
173  size_t allocated_count = count && size ? count : 1;
174  size_t allocated_size = count && size ? size : 1;
175  void *ret = calloc(allocated_count, allocated_size);
176  if (!ret) {
177    try_to_free_memory();
178    ret = calloc(allocated_count, allocated_size);
179    if (!ret) {
180      preserve_exit(e_outofmem);
181    }
182  }
183  return ret;
184}
185
186/// realloc() wrapper
187///
188/// @see {xmalloc}
189/// @param size
190/// @return pointer to reallocated space. Never NULL
191void *xrealloc(void *ptr, size_t size)
192  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALLOC_SIZE(2) FUNC_ATTR_NONNULL_RET
193{
194  size_t allocated_size = size ? size : 1;
195  void *ret = realloc(ptr, allocated_size);
196  if (!ret) {
197    try_to_free_memory();
198    ret = realloc(ptr, allocated_size);
199    if (!ret) {
200      preserve_exit(e_outofmem);
201    }
202  }
203  return ret;
204}
205
206/// xmalloc() wrapper that allocates size + 1 bytes and zeroes the last byte
207///
208/// Commonly used to allocate strings, e.g. `char *s = xmallocz(len)`.
209///
210/// @see {xmalloc}
211/// @param size
212/// @return pointer to allocated space. Never NULL
213void *xmallocz(size_t size)
214  FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT
215{
216  size_t total_size = size + 1;
217  if (total_size < size) {
218    preserve_exit(_("Nvim: Data too large to fit into virtual memory space\n"));
219  }
220
221  void *ret = xmalloc(total_size);
222  ((char *)ret)[size] = NUL;
223
224  return ret;
225}
226
227/// Allocates (len + 1) bytes of memory, duplicates `len` bytes of
228/// `data` to the allocated memory, zero terminates the allocated memory,
229/// and returns a pointer to the allocated memory. If the allocation fails,
230/// the program dies.
231///
232/// @see {xmalloc}
233/// @param data Pointer to the data that will be copied
234/// @param len number of bytes that will be copied
235void *xmemdupz(const void *data, size_t len)
236  FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT
237  FUNC_ATTR_NONNULL_ALL
238{
239  return memcpy(xmallocz(len), data, len);
240}
241
242/// Copies `len` bytes of `src` to `dst` and zero terminates it.
243///
244/// @see {xstrlcpy}
245/// @param[out]  dst  Buffer to store the result.
246/// @param[in]  src  Buffer to be copied.
247/// @param[in]  len  Number of bytes to be copied.
248void *xmemcpyz(void *dst, const void *src, size_t len)
249  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
250{
251  memcpy(dst, src, len);
252  ((char *)dst)[len] = NUL;
253  return dst;
254}
255
256#ifndef HAVE_STRNLEN
257size_t xstrnlen(const char *s, size_t n)
258  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
259{
260  const char *end = memchr(s, NUL, n);
261  if (end == NULL) {
262    return n;
263  }
264  return (size_t)(end - s);
265}
266#endif
267
268/// A version of strchr() that returns a pointer to the terminating NUL if it
269/// doesn't find `c`.
270///
271/// @param str The string to search.
272/// @param c   The char to look for.
273/// @returns a pointer to the first instance of `c`, or to the NUL terminator
274///          if not found.
275char *xstrchrnul(const char *str, char c)
276  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
277{
278  const char *p = strchr(str, c);
279  return p ? (char *)p : (char *)(str + strlen(str));
280}
281
282/// A version of memchr() that returns a pointer one past the end
283/// if it doesn't find `c`.
284///
285/// @param addr The address of the memory object.
286/// @param c    The char to look for.
287/// @param size The size of the memory object.
288/// @returns a pointer to the first instance of `c`, or one past the end if not
289///          found.
290void *xmemscan(const void *addr, char c, size_t size)
291  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
292{
293  const char *p = memchr(addr, c, size);
294  return p ? (char *)p : (char *)addr + size;
295}
296
297/// Replaces every instance of `c` with `x`.
298///
299/// @warning Will read past `str + strlen(str)` if `c == NUL`.
300///
301/// @param str A NUL-terminated string.
302/// @param c   The unwanted byte.
303/// @param x   The replacement.
304void strchrsub(char *str, char c, char x)
305  FUNC_ATTR_NONNULL_ALL
306{
307  assert(c != NUL);
308  while ((str = strchr(str, c))) {
309    *str++ = x;
310  }
311}
312
313/// Replaces every instance of `c` with `x`.
314///
315/// @param data An object in memory. May contain NULs.
316/// @param c    The unwanted byte.
317/// @param x    The replacement.
318/// @param len  The length of data.
319void memchrsub(void *data, char c, char x, size_t len)
320  FUNC_ATTR_NONNULL_ALL
321{
322  char *p = data;
323  char *end = (char *)data + len;
324  while ((p = memchr(p, c, (size_t)(end - p)))) {
325    *p++ = x;
326  }
327}
328
329/// Counts the number of occurrences of `c` in `str`.
330///
331/// @warning Unsafe if `c == NUL`.
332///
333/// @param str Pointer to the string to search.
334/// @param c   The byte to search for.
335/// @returns the number of occurrences of `c` in `str`.
336size_t strcnt(const char *str, char c)
337  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
338{
339  assert(c != 0);
340  size_t cnt = 0;
341  while ((str = strchr(str, c))) {
342    cnt++;
343    str++;  // Skip the instance of c.
344  }
345  return cnt;
346}
347
348/// Counts the number of occurrences of byte `c` in `data[len]`.
349///
350/// @param data Pointer to the data to search.
351/// @param c    The byte to search for.
352/// @param len  The length of `data`.
353/// @returns the number of occurrences of `c` in `data[len]`.
354size_t memcnt(const void *data, char c, size_t len)
355  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
356{
357  size_t cnt = 0;
358  const char *ptr = data;
359  const char *end = ptr + len;
360  while ((ptr = memchr(ptr, c, (size_t)(end - ptr))) != NULL) {
361    cnt++;
362    ptr++;  // Skip the instance of c.
363  }
364  return cnt;
365}
366
367/// Copies the string pointed to by src (including the terminating NUL
368/// character) into the array pointed to by dst.
369///
370/// @returns pointer to the terminating NUL char copied into the dst buffer.
371///          This is the only difference with strcpy(), which returns dst.
372///
373/// WARNING: If copying takes place between objects that overlap, the behavior
374/// is undefined.
375///
376/// Nvim version of POSIX 2008 stpcpy(3). We do not require POSIX 2008, so
377/// implement our own version.
378///
379/// @param dst
380/// @param src
381char *xstpcpy(char *restrict dst, const char *restrict src)
382  FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
383{
384  const size_t len = strlen(src);
385  return (char *)memcpy(dst, src, len + 1) + len;
386}
387
388/// Copies not more than n bytes (bytes that follow a NUL character are not
389/// copied) from the array pointed to by src to the array pointed to by dst.
390///
391/// If a NUL character is written to the destination, xstpncpy() returns the
392/// address of the first such NUL character. Otherwise, it shall return
393/// &dst[maxlen].
394///
395/// WARNING: If copying takes place between objects that overlap, the behavior
396/// is undefined.
397///
398/// WARNING: xstpncpy will ALWAYS write maxlen bytes. If src is shorter than
399/// maxlen, zeroes will be written to the remaining bytes.
400///
401/// @param dst
402/// @param src
403/// @param maxlen
404char *xstpncpy(char *restrict dst, const char *restrict src, size_t maxlen)
405  FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
406{
407  const char *p = memchr(src, NUL, maxlen);
408  if (p) {
409    size_t srclen = (size_t)(p - src);
410    memcpy(dst, src, srclen);
411    memset(dst + srclen, 0, maxlen - srclen);
412    return dst + srclen;
413  } else {
414    memcpy(dst, src, maxlen);
415    return dst + maxlen;
416  }
417}
418
419/// xstrlcpy - Copy a NUL-terminated string into a sized buffer
420///
421/// Compatible with *BSD strlcpy: the result is always a valid NUL-terminated
422/// string that fits in the buffer (unless, of course, the buffer size is
423/// zero). It does not pad out the result like strncpy() does.
424///
425/// @param[out]  dst  Buffer to store the result.
426/// @param[in]  src  String to be copied.
427/// @param[in]  dsize  Size of `dst`.
428///
429/// @return Length of `src`. May be greater than `dsize - 1`, which would mean
430///         that string was truncated.
431size_t xstrlcpy(char *restrict dst, const char *restrict src, size_t dsize)
432  FUNC_ATTR_NONNULL_ALL
433{
434  size_t slen = strlen(src);
435
436  if (dsize) {
437    size_t len = MIN(slen, dsize - 1);
438    memcpy(dst, src, len);
439    dst[len] = NUL;
440  }
441
442  return slen;  // Does not include NUL.
443}
444
445/// Appends `src` to string `dst` of size `dsize` (unlike strncat, dsize is the
446/// full size of `dst`, not space left).  At most dsize-1 characters
447/// will be copied.  Always NUL terminates. `src` and `dst` may overlap.
448///
449/// @see vim_strcat from Vim.
450/// @see strlcat from OpenBSD.
451///
452/// @param[in,out]  dst  Buffer to be appended-to. Must have a NUL byte.
453/// @param[in]  src  String to put at the end of `dst`.
454/// @param[in]  dsize  Size of `dst` including NUL byte. Must be greater than 0.
455///
456/// @return Length of the resulting string as if destination size was #SIZE_MAX.
457///         May be greater than `dsize - 1`, which would mean that string was
458///         truncated.
459size_t xstrlcat(char *const dst, const char *const src, const size_t dsize)
460  FUNC_ATTR_NONNULL_ALL
461{
462  assert(dsize > 0);
463  const size_t dlen = strlen(dst);
464  assert(dlen < dsize);
465  const size_t slen = strlen(src);
466
467  if (slen > dsize - dlen - 1) {
468    memmove(dst + dlen, src, dsize - dlen - 1);
469    dst[dsize - 1] = NUL;
470  } else {
471    memmove(dst + dlen, src, slen + 1);
472  }
473
474  return slen + dlen;  // Does not include NUL.
475}
476
477/// strdup() wrapper
478///
479/// @see {xmalloc}
480/// @param str 0-terminated string that will be copied
481/// @return pointer to a copy of the string
482char *xstrdup(const char *str)
483  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET
484  FUNC_ATTR_NONNULL_ALL
485{
486  return xmemdupz(str, strlen(str));
487}
488
489/// strdup() wrapper
490///
491/// Unlike xstrdup() allocates a new empty string if it receives NULL.
492char *xstrdupnul(const char *const str)
493  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET
494{
495  if (str == NULL) {
496    return xmallocz(0);
497  }
498  return xstrdup(str);
499}
500
501/// A version of memchr that starts the search at `src + len`.
502///
503/// Based on glibc's memrchr.
504///
505/// @param src The source memory object.
506/// @param c   The byte to search for.
507/// @param len The length of the memory object.
508/// @returns a pointer to the found byte in src[len], or NULL.
509void *xmemrchr(const void *src, uint8_t c, size_t len)
510  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
511{
512  while (len--) {
513    if (((uint8_t *)src)[len] == c) {
514      return (uint8_t *)src + len;
515    }
516  }
517  return NULL;
518}
519
520/// strndup() wrapper
521///
522/// @see {xmalloc}
523/// @param str 0-terminated string that will be copied
524/// @return pointer to a copy of the string
525char *xstrndup(const char *str, size_t len)
526  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET
527  FUNC_ATTR_NONNULL_ALL
528{
529  const char *p = memchr(str, NUL, len);
530  return xmemdupz(str, p ? (size_t)(p - str) : len);
531}
532
533/// Duplicates a chunk of memory using xmalloc
534///
535/// @see {xmalloc}
536/// @param data pointer to the chunk
537/// @param len size of the chunk
538/// @return a pointer
539void *xmemdup(const void *data, size_t len)
540  FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE(2) FUNC_ATTR_NONNULL_RET
541  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
542{
543  return memcpy(xmalloc(len), data, len);
544}
545
546/// Returns true if strings `a` and `b` are equal. Arguments may be NULL.
547bool strequal(const char *a, const char *b)
548  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
549{
550  return (a == NULL && b == NULL) || (a && b && strcmp(a, b) == 0);
551}
552
553/// Returns true if first `n` characters of strings `a` and `b` are equal. Arguments may be NULL.
554bool strnequal(const char *a, const char *b, size_t n)
555  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
556{
557  return (a == NULL && b == NULL) || (a && b && strncmp(a, b, n) == 0);
558}
559
560/// Writes time_t to "buf[8]".
561void time_to_bytes(time_t time_, uint8_t buf[8])
562{
563  // time_t can be up to 8 bytes in size, more than uintmax_t in 32 bits
564  // systems, thus we can't use put_bytes() here.
565  for (size_t i = 7, bufi = 0; bufi < 8; i--, bufi++) {
566    buf[bufi] = (uint8_t)((uint64_t)time_ >> (i * 8));
567  }
568}
569
570/// Iterative merge sort for doubly linked list.
571/// O(NlogN) worst case, and stable.
572///  - The list is divided into blocks of increasing size (1, 2, 4, 8, ...).
573///  - Each pair of blocks is merged in sorted order.
574///  - Merged blocks are reconnected to build the sorted list.
575void *mergesort_list(void *head, MergeSortGetFunc get_next, MergeSortSetFunc set_next,
576                     MergeSortGetFunc get_prev, MergeSortSetFunc set_prev,
577                     MergeSortCompareFunc compare)
578{
579  if (!head || !get_next(head)) {
580    return head;
581  }
582
583  // Count length
584  int n = 0;
585  void *curr = head;
586  while (curr) {
587    n++;
588    curr = get_next(curr);
589  }
590
591  for (int size = 1; size < n; size *= 2) {
592    void *new_head = NULL;
593    void *tail = NULL;
594    curr = head;
595
596    while (curr) {
597      // Split two runs
598      void *left = curr;
599      void *right = left;
600      for (int i = 0; i < size && right; i++) {
601        right = get_next(right);
602      }
603
604      void *next = right;
605      for (int i = 0; i < size && next; i++) {
606        next = get_next(next);
607      }
608
609      // Break links
610      void *l_end = right ? get_prev(right) : NULL;
611      if (l_end) {
612        set_next(l_end, NULL);
613      }
614      if (right) {
615        set_prev(right, NULL);
616      }
617
618      void *r_end = next ? get_prev(next) : NULL;
619      if (r_end) {
620        set_next(r_end, NULL);
621      }
622      if (next) {
623        set_prev(next, NULL);
624      }
625
626      // Merge
627      void *merged = NULL;
628      void *merged_tail = NULL;
629
630      while (left || right) {
631        void *chosen = NULL;
632        if (!left) {
633          chosen = right;
634          right = get_next(right);
635        } else if (!right) {
636          chosen = left;
637          left = get_next(left);
638        } else if (compare(left, right) <= 0) {
639          chosen = left;
640          left = get_next(left);
641        } else {
642          chosen = right;
643          right = get_next(right);
644        }
645
646        if (merged_tail) {
647          set_next(merged_tail, chosen);
648          set_prev(chosen, merged_tail);
649          merged_tail = chosen;
650        } else {
651          merged = merged_tail = chosen;
652          set_prev(chosen, NULL);
653        }
654      }
655
656      // Connect to full list
657      if (!new_head) {
658        new_head = merged;
659      } else {
660        set_next(tail, merged);
661        set_prev(merged, tail);
662      }
663
664      // Move tail to end
665      while (get_next(merged_tail)) {
666        merged_tail = get_next(merged_tail);
667      }
668      tail = merged_tail;
669
670      curr = next;
671    }
672
673    head = new_head;
674  }
675
676  return head;
677}
678
679#define REUSE_MAX 4
680
681static struct consumed_blk *arena_reuse_blk;
682static size_t arena_reuse_blk_count = 0;
683
684static void arena_free_reuse_blks(void)
685{
686  while (arena_reuse_blk_count > 0) {
687    struct consumed_blk *blk = arena_reuse_blk;
688    arena_reuse_blk = arena_reuse_blk->prev;
689    xfree(blk);
690    arena_reuse_blk_count--;
691  }
692}
693
694/// Finish the allocations in an arena.
695///
696/// This does not immediately free the memory, but leaves existing allocated
697/// objects valid, and returns an opaque ArenaMem handle, which can be used to
698/// free the allocations using `arena_mem_free`, when the objects allocated
699/// from the arena are not needed anymore.
700ArenaMem arena_finish(Arena *arena)
701{
702  struct consumed_blk *res = (struct consumed_blk *)arena->cur_blk;
703  *arena = (Arena)ARENA_EMPTY;
704  return res;
705}
706
707/// allocate a block of ARENA_BLOCK_SIZE
708///
709/// free it with free_block
710void *alloc_block(void)
711{
712  if (arena_reuse_blk_count > 0) {
713    void *retval = (char *)arena_reuse_blk;
714    arena_reuse_blk = arena_reuse_blk->prev;
715    arena_reuse_blk_count--;
716    return retval;
717  } else {
718    arena_alloc_count++;
719    return xmalloc(ARENA_BLOCK_SIZE);
720  }
721}
722
723void arena_alloc_block(Arena *arena)
724{
725  struct consumed_blk *prev_blk = (struct consumed_blk *)arena->cur_blk;
726  arena->cur_blk = alloc_block();
727  arena->pos = 0;
728  arena->size = ARENA_BLOCK_SIZE;
729  struct consumed_blk *blk = arena_alloc(arena, sizeof(struct consumed_blk), true);
730  blk->prev = prev_blk;
731}
732
733static size_t arena_align_offset(uint64_t off)
734{
735#define ARENA_ALIGN MAX(sizeof(void *), sizeof(double))
736  return ((off + (ARENA_ALIGN - 1)) & ~(ARENA_ALIGN - 1));
737#undef ARENA_ALIGN
738}
739
740/// @param arena if NULL, do a global allocation. caller must then free the value!
741/// @param size if zero, will still return a non-null pointer, but not a usable or unique one
742void *arena_alloc(Arena *arena, size_t size, bool align)
743{
744  if (!arena) {
745    return xmalloc(size);
746  }
747  if (!arena->cur_blk) {
748    arena_alloc_block(arena);
749  }
750  size_t alloc_pos = align ? arena_align_offset(arena->pos) : arena->pos;
751  if (alloc_pos + size > arena->size) {
752    if (size > (ARENA_BLOCK_SIZE - sizeof(struct consumed_blk)) >> 1) {
753      // if allocation is too big, allocate a large block with the requested
754      // size, but still with block pointer head. We do this even for
755      // arena->size / 2, as there likely is space left for the next
756      // small allocation in the current block.
757      arena_alloc_count++;
758      size_t hdr_size = sizeof(struct consumed_blk);
759      size_t aligned_hdr_size = (align ? arena_align_offset(hdr_size) : hdr_size);
760      char *alloc = xmalloc(size + aligned_hdr_size);
761
762      // to simplify free-list management, arena->cur_blk must
763      // always be a normal, ARENA_BLOCK_SIZE sized, block
764      struct consumed_blk *cur_blk = (struct consumed_blk *)arena->cur_blk;
765      struct consumed_blk *fix_blk = (struct consumed_blk *)alloc;
766      fix_blk->prev = cur_blk->prev;
767      cur_blk->prev = fix_blk;
768      return alloc + aligned_hdr_size;
769    } else {
770      arena_alloc_block(arena);  // resets arena->pos
771      alloc_pos = align ? arena_align_offset(arena->pos) : arena->pos;
772    }
773  }
774
775  char *mem = arena->cur_blk + alloc_pos;
776  arena->pos = alloc_pos + size;
777  return mem;
778}
779
780void free_block(void *block)
781{
782  if (arena_reuse_blk_count < REUSE_MAX) {
783    struct consumed_blk *reuse_blk = block;
784    reuse_blk->prev = arena_reuse_blk;
785    arena_reuse_blk = reuse_blk;
786    arena_reuse_blk_count++;
787  } else {
788    xfree(block);
789  }
790}
791
792void arena_mem_free(ArenaMem mem)
793{
794  struct consumed_blk *b = mem;
795  // peel of the first block, as it is guaranteed to be ARENA_BLOCK_SIZE,
796  // not a custom fix_blk
797  if (b != NULL) {
798    struct consumed_blk *reuse_blk = b;
799    b = b->prev;
800    free_block(reuse_blk);
801  }
802
803  while (b) {
804    struct consumed_blk *prev = b->prev;
805    xfree(b);
806    b = prev;
807  }
808}
809
810char *arena_allocz(Arena *arena, size_t size)
811{
812  char *mem = arena_alloc(arena, size + 1, false);
813  mem[size] = NUL;
814  return mem;
815}
816
817char *arena_memdupz(Arena *arena, const char *buf, size_t size)
818  FUNC_ATTR_NONNULL_ARG(2)
819{
820  char *mem = arena_allocz(arena, size);
821  memcpy(mem, buf, size);
822  return mem;
823}
824
825char *arena_strdup(Arena *arena, const char *str)
826  FUNC_ATTR_NONNULL_ARG(2)
827{
828  return arena_memdupz(arena, str, strlen(str));
829}
830
831#ifdef EXITFREE
832
833# include "nvim/autocmd.h"
834# include "nvim/buffer.h"
835# include "nvim/cmdhist.h"
836# include "nvim/diff.h"
837# include "nvim/ex_cmds.h"
838# include "nvim/ex_docmd.h"
839# include "nvim/file_search.h"
840# include "nvim/grid.h"
841# include "nvim/input.h"
842# include "nvim/insert.h"
843# include "nvim/mark.h"
844# include "nvim/msgpack_rpc/channel.h"
845# include "nvim/option.h"
846# include "nvim/os/os.h"
847# include "nvim/quickfix.h"
848# include "nvim/regexp.h"
849# include "nvim/register.h"
850# include "nvim/search.h"
851# include "nvim/spell.h"
852# include "nvim/tag.h"
853# include "nvim/window.h"
854
855// Free everything that we allocated.
856// Can be used to detect memory leaks, e.g., with ccmalloc.
857// NOTE: This is tricky!  Things are freed that functions depend on.  Don't be
858// surprised if Vim crashes...
859// Some things can't be freed, esp. things local to a library function.
860void free_all_mem(void)
861{
862  buf_T *buf, *nextbuf;
863
864  // If a routine below recurses into free_all_mem, don't try freeing everything again.
865  if (entered_free_all_mem) {
866    // Except the Lua state. #39675
867    nlua_free_all_mem();
868    return;
869  }
870  entered_free_all_mem = true;
871  // Don't want to trigger autocommands from here on.
872  block_autocmds();
873
874  // Close all tabs and windows.  Reset 'equalalways' to avoid redraws.
875  p_ea = false;
876  if (first_tabpage != NULL && first_tabpage->tp_next != NULL) {
877    do_cmdline_cmd("tabonly!");
878  }
879
880  // Free all spell info.
881  spell_free_all();
882
883  // Clear user commands (before deleting buffers).
884  ex_comclear(NULL);
885
886  if (curbuf != NULL) {
887    // Clear menus.
888    do_cmdline_cmd("aunmenu *");
889    do_cmdline_cmd("tlunmenu *");
890    do_cmdline_cmd("menutranslate clear");
891
892    // Clear mappings, abbreviations, breakpoints.
893    // NB: curbuf not used with local=false arg
894    map_clear_mode(curbuf, MAP_ALL_MODES, false, false);
895    map_clear_mode(curbuf, MAP_ALL_MODES, false, true);
896    do_cmdline_cmd("breakdel *");
897    do_cmdline_cmd("profdel *");
898    do_cmdline_cmd("set keymap=");
899  }
900
901  free_titles();
902  free_findfile();
903
904  // Obviously named calls.
905  free_all_autocmds();
906  free_all_marks();
907  alist_clear(&global_alist);
908  free_homedir();
909  free_users();
910  free_search_patterns();
911  free_old_sub();
912  free_last_insert();
913  free_insexpand_stuff();
914  free_prev_shellcmd();
915  free_regexp_stuff();
916  free_tag_stuff();
917  free_cd_dir();
918  free_signs();
919  set_expr_line(NULL);
920  if (curtab != NULL) {
921    diff_clear(curtab);
922  }
923  clear_sb_text(true);            // free any scrollback text
924
925  // Free some global vars.
926  xfree(last_cmdline);
927  xfree(new_last_cmdline);
928  set_keep_msg(NULL, 0);
929
930  // Clear cmdline history.
931  p_hi = 0;
932  init_history();
933
934  free_quickfix();
935
936  // Close all script inputs.
937  close_all_scripts();
938
939  if (curwin != NULL) {
940    // Destroy all windows.  Must come before freeing buffers.
941    win_free_all();
942  }
943
944  // Free all option values.  Must come after closing windows.
945  free_all_options();
946
947  // Free all buffers.  Reset 'autochdir' to avoid accessing things that
948  // were freed already.
949  // Must be after eval_clear to avoid it trying to access b:changedtick after
950  // freeing it.
951  p_acd = false;
952  for (buf = firstbuf; buf != NULL;) {
953    bufref_T bufref;
954    set_bufref(&bufref, buf);
955    nextbuf = buf->b_next;
956    // All windows were freed.  Reset b_nwindows so buffers can be wiped.
957    buf->b_nwindows = 0;
958
959    // Since options (in addition to other stuff) have been freed above we need to ensure no
960    // callbacks are called, so free them before closing the buffer.
961    buf_free_callbacks(buf);
962
963    close_buffer(NULL, buf, DOBUF_WIPE, false, false, false);
964    // Didn't work, try next one.
965    buf = bufref_valid(&bufref) ? nextbuf : firstbuf;
966  }
967
968  // Clear registers.
969  clear_registers();
970  redo_free_all();
971
972  // highlight info
973  free_highlight();
974
975  reset_last_sourcing();
976
977  if (first_tabpage != NULL) {
978    free_tabpage(first_tabpage);
979    first_tabpage = NULL;
980  }
981
982  // message history
983  msg_hist_clear(0);
984
985  channel_free_all_mem();
986  eval_clear();
987  api_extmark_free_all_mem();
988  atom_free_all();
989  mc_free_all();
990
991  map_destroy(int, &buffer_handles);
992  map_destroy(int, &window_handles);
993  map_destroy(int, &tabpage_handles);
994
995  // free screenlines (can't display anything now!)
996  grid_free_all_mem();
997  stl_clear_click_defs(tab_page_click_defs, tab_page_click_defs_size);
998  xfree(tab_page_click_defs);
999
1000  clear_hl_tables(false);
1001
1002  check_quickfix_busy();
1003
1004  decor_free_all_mem();
1005  drawline_free_all_mem();
1006
1007  if (ui_client_channel_id) {
1008    ui_client_free_all_mem();
1009  }
1010
1011  remote_ui_free_all_mem();
1012  ui_free_all_mem();
1013  ui_comp_free_all_mem();
1014  nlua_free_all_mem();
1015  rpc_free_all_mem();
1016  autocmd_free_all_mem();
1017
1018  // should be last, in case earlier free functions deallocates arenas
1019  arena_free_reuse_blks();
1020}
1021
1022#endif