robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
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{ 69static bool trying_to_free = false; 70// avoid recursive calls 71if (trying_to_free ) { 72return ; 73 } 74trying_to_free = true; 75 76// free any scrollback text 77clear_sb_text (true); 78// Try to save all buffers and release as many blocks as possible 79mf_release_all (); 80 81arena_free_reuse_blks (); 82 83trying_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{ 90if (did_outofmem_msg ) { 91return ; 92 } 93 94// Don't hide this message 95emsg_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. 99did_outofmem_msg = true; 100 101semsg (_ ("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{ 114size_t allocated_size = size ?size :1 ; 115void * ret = malloc (allocated_size ); 116if (!ret ) { 117try_to_free_memory (); 118ret = malloc (allocated_size ); 119 } 120return 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{ 131void * ret = try_malloc (size ); 132if (!ret ) { 133do_outofmem_msg (size ); 134 } 135return 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 ) 147FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE (1 )FUNC_ATTR_NONNULL_RET 148{ 149void * ret = try_malloc (size ); 150if (!ret ) { 151preserve_exit (e_outofmem ); 152 } 153return 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{ 161free (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 ) 171FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE_PROD (1 ,2 )FUNC_ATTR_NONNULL_RET 172{ 173size_t allocated_count = count && size ?count :1 ; 174size_t allocated_size = count && size ?size :1 ; 175void * ret = calloc (allocated_count ,allocated_size ); 176if (!ret ) { 177try_to_free_memory (); 178ret = calloc (allocated_count ,allocated_size ); 179if (!ret ) { 180preserve_exit (e_outofmem ); 181 } 182 } 183return 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 ) 192FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALLOC_SIZE (2 )FUNC_ATTR_NONNULL_RET 193{ 194size_t allocated_size = size ?size :1 ; 195void * ret = realloc (ptr ,allocated_size ); 196if (!ret ) { 197try_to_free_memory (); 198ret = realloc (ptr ,allocated_size ); 199if (!ret ) { 200preserve_exit (e_outofmem ); 201 } 202 } 203return 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 ) 214FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT 215{ 216size_t total_size = size + 1 ; 217if (total_size < size ) { 218preserve_exit (_ ("Nvim: Data too large to fit into virtual memory space\n" )); 219 } 220 221void * ret = xmalloc (total_size ); 222 ((char * )ret )[size ]= NUL ; 223 224return 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 ) 236FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT 237FUNC_ATTR_NONNULL_ALL 238{ 239return 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 ) 249FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 250{ 251memcpy (dst ,src ,len ); 252 ((char * )dst )[len ]= NUL ; 253return dst ; 254} 255 256#ifndef HAVE_STRNLEN 257size_t xstrnlen (const char * s ,size_t n ) 258FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 259{ 260const char * end = memchr (s ,NUL ,n ); 261if (end == NULL ) { 262return n ; 263 } 264return (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 ) 276FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 277{ 278const char * p = strchr (str ,c ); 279return 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 ) 291FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 292{ 293const char * p = memchr (addr ,c ,size ); 294return 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 ) 305FUNC_ATTR_NONNULL_ALL 306{ 307assert (c != NUL ); 308while ((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 ) 320FUNC_ATTR_NONNULL_ALL 321{ 322char * p = data ; 323char * end = (char * )data + len ; 324while ((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 ) 337FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 338{ 339assert (c != 0 ); 340size_t cnt = 0 ; 341while ((str = strchr (str ,c ))) { 342cnt ++ ; 343str ++ ;// Skip the instance of c. 344 } 345return 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 ) 355FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 356{ 357size_t cnt = 0 ; 358const char * ptr = data ; 359const char * end = ptr + len ; 360while ((ptr = memchr (ptr ,c , (size_t )(end - ptr )))!= NULL ) { 361cnt ++ ; 362ptr ++ ;// Skip the instance of c. 363 } 364return 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 * restrictdst ,const char * restrictsrc ) 382FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 383{ 384const size_t len = strlen (src ); 385return (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 * restrictdst ,const char * restrictsrc ,size_t maxlen ) 405FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 406{ 407const char * p = memchr (src ,NUL ,maxlen ); 408if (p ) { 409size_t srclen = (size_t )(p - src ); 410memcpy (dst ,src ,srclen ); 411memset (dst + srclen ,0 ,maxlen - srclen ); 412return dst + srclen ; 413 }else { 414memcpy (dst ,src ,maxlen ); 415return 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 * restrictdst ,const char * restrictsrc ,size_t dsize ) 432FUNC_ATTR_NONNULL_ALL 433{ 434size_t slen = strlen (src ); 435 436if (dsize ) { 437size_t len = MIN (slen ,dsize - 1 ); 438memcpy (dst ,src ,len ); 439dst [len ]= NUL ; 440 } 441 442return 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 ) 460FUNC_ATTR_NONNULL_ALL 461{ 462assert (dsize > 0 ); 463const size_t dlen = strlen (dst ); 464assert (dlen < dsize ); 465const size_t slen = strlen (src ); 466 467if (slen > dsize - dlen - 1 ) { 468memmove (dst + dlen ,src ,dsize - dlen - 1 ); 469dst [dsize - 1 ]= NUL ; 470 }else { 471memmove (dst + dlen ,src ,slen + 1 ); 472 } 473 474return 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 ) 483FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET 484FUNC_ATTR_NONNULL_ALL 485{ 486return 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 ) 493FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET 494{ 495if (str == NULL ) { 496return xmallocz (0 ); 497 } 498return 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 ) 510FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 511{ 512while (len -- ) { 513if (((uint8_t * )src )[len ]== c ) { 514return (uint8_t * )src + len ; 515 } 516 } 517return 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 ) 526FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET 527FUNC_ATTR_NONNULL_ALL 528{ 529const char * p = memchr (str ,NUL ,len ); 530return 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 ) 540FUNC_ATTR_MALLOC FUNC_ATTR_ALLOC_SIZE (2 )FUNC_ATTR_NONNULL_RET 541FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 542{ 543return 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 ) 548FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 549{ 550return (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 ) 555FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 556{ 557return (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. 565for (size_t i = 7 ,bufi = 0 ;bufi < 8 ;i -- ,bufi ++ ) { 566buf [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 , 576MergeSortGetFunc get_prev ,MergeSortSetFunc set_prev , 577MergeSortCompareFunc compare ) 578{ 579if (!head || !get_next (head )) { 580return head ; 581 } 582 583// Count length 584int n = 0 ; 585void * curr = head ; 586while (curr ) { 587n ++ ; 588curr = get_next (curr ); 589 } 590 591for (int size = 1 ;size < n ;size *=2 ) { 592void * new_head = NULL ; 593void * tail = NULL ; 594curr = head ; 595 596while (curr ) { 597// Split two runs 598void * left = curr ; 599void * right = left ; 600for (int i = 0 ;i < size && right ;i ++ ) { 601right = get_next (right ); 602 } 603 604void * next = right ; 605for (int i = 0 ;i < size && next ;i ++ ) { 606next = get_next (next ); 607 } 608 609// Break links 610void * l_end = right ?get_prev (right ) :NULL ; 611if (l_end ) { 612set_next (l_end ,NULL ); 613 } 614if (right ) { 615set_prev (right ,NULL ); 616 } 617 618void * r_end = next ?get_prev (next ) :NULL ; 619if (r_end ) { 620set_next (r_end ,NULL ); 621 } 622if (next ) { 623set_prev (next ,NULL ); 624 } 625 626// Merge 627void * merged = NULL ; 628void * merged_tail = NULL ; 629 630while (left || right ) { 631void * chosen = NULL ; 632if (!left ) { 633chosen = right ; 634right = get_next (right ); 635 }else if (!right ) { 636chosen = left ; 637left = get_next (left ); 638 }else if (compare (left ,right ) <=0 ) { 639chosen = left ; 640left = get_next (left ); 641 }else { 642chosen = right ; 643right = get_next (right ); 644 } 645 646if (merged_tail ) { 647set_next (merged_tail ,chosen ); 648set_prev (chosen ,merged_tail ); 649merged_tail = chosen ; 650 }else { 651merged = merged_tail = chosen ; 652set_prev (chosen ,NULL ); 653 } 654 } 655 656// Connect to full list 657if (!new_head ) { 658new_head = merged ; 659 }else { 660set_next (tail ,merged ); 661set_prev (merged ,tail ); 662 } 663 664// Move tail to end 665while (get_next (merged_tail )) { 666merged_tail = get_next (merged_tail ); 667 } 668tail = merged_tail ; 669 670curr = next ; 671 } 672 673head = new_head ; 674 } 675 676return 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{ 686while (arena_reuse_blk_count > 0 ) { 687struct consumed_blk * blk = arena_reuse_blk ; 688arena_reuse_blk = arena_reuse_blk -> prev ; 689xfree (blk ); 690arena_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{ 702struct consumed_blk * res = (struct consumed_blk * )arena -> cur_blk ; 703* arena = (Arena )ARENA_EMPTY ; 704return res ; 705} 706 707/// allocate a block of ARENA_BLOCK_SIZE 708/// 709/// free it with free_block 710void * alloc_block (void ) 711{ 712if (arena_reuse_blk_count > 0 ) { 713void * retval = (char * )arena_reuse_blk ; 714arena_reuse_blk = arena_reuse_blk -> prev ; 715arena_reuse_blk_count -- ; 716return retval ; 717 }else { 718arena_alloc_count ++ ; 719return xmalloc (ARENA_BLOCK_SIZE ); 720 } 721} 722 723void arena_alloc_block (Arena * arena ) 724{ 725struct consumed_blk * prev_blk = (struct consumed_blk * )arena -> cur_blk ; 726arena -> cur_blk = alloc_block (); 727arena -> pos = 0 ; 728arena -> size = ARENA_BLOCK_SIZE ; 729struct consumed_blk * blk = arena_alloc (arena ,sizeof (struct consumed_blk ), true); 730blk -> prev = prev_blk ; 731} 732 733static size_t arena_align_offset (uint64_t off ) 734{ 735#define ARENA_ALIGN MAX(sizeof(void *), sizeof(double)) 736return ((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{ 744if (!arena ) { 745return xmalloc (size ); 746 } 747if (!arena -> cur_blk ) { 748arena_alloc_block (arena ); 749 } 750size_t alloc_pos = align ?arena_align_offset (arena -> pos ) :arena -> pos ; 751if (alloc_pos + size > arena -> size ) { 752if (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. 757arena_alloc_count ++ ; 758size_t hdr_size = sizeof (struct consumed_blk ); 759size_t aligned_hdr_size = (align ?arena_align_offset (hdr_size ) :hdr_size ); 760char * 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 764struct consumed_blk * cur_blk = (struct consumed_blk * )arena -> cur_blk ; 765struct consumed_blk * fix_blk = (struct consumed_blk * )alloc ; 766fix_blk -> prev = cur_blk -> prev ; 767cur_blk -> prev = fix_blk ; 768return alloc + aligned_hdr_size ; 769 }else { 770arena_alloc_block (arena );// resets arena->pos 771alloc_pos = align ?arena_align_offset (arena -> pos ) :arena -> pos ; 772 } 773 } 774 775char * mem = arena -> cur_blk + alloc_pos ; 776arena -> pos = alloc_pos + size ; 777return mem ; 778} 779 780void free_block (void * block ) 781{ 782if (arena_reuse_blk_count < REUSE_MAX ) { 783struct consumed_blk * reuse_blk = block ; 784reuse_blk -> prev = arena_reuse_blk ; 785arena_reuse_blk = reuse_blk ; 786arena_reuse_blk_count ++ ; 787 }else { 788xfree (block ); 789 } 790} 791 792void arena_mem_free (ArenaMem mem ) 793{ 794struct 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 797if (b != NULL ) { 798struct consumed_blk * reuse_blk = b ; 799b = b -> prev ; 800free_block (reuse_blk ); 801 } 802 803while (b ) { 804struct consumed_blk * prev = b -> prev ; 805xfree (b ); 806b = prev ; 807 } 808} 809 810char * arena_allocz (Arena * arena ,size_t size ) 811{ 812char * mem = arena_alloc (arena ,size + 1 , false); 813mem [size ]= NUL ; 814return mem ; 815} 816 817char * arena_memdupz (Arena * arena ,const char * buf ,size_t size ) 818FUNC_ATTR_NONNULL_ARG (2 ) 819{ 820char * mem = arena_allocz (arena ,size ); 821memcpy (mem ,buf ,size ); 822return mem ; 823} 824 825char * arena_strdup (Arena * arena ,const char * str ) 826FUNC_ATTR_NONNULL_ARG (2 ) 827{ 828return 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{ 862buf_T * buf ,* nextbuf ; 863 864// If a routine below recurses into free_all_mem, don't try freeing everything again. 865if (entered_free_all_mem ) { 866// Except the Lua state. #39675 867nlua_free_all_mem (); 868return ; 869 } 870entered_free_all_mem = true; 871// Don't want to trigger autocommands from here on. 872block_autocmds (); 873 874// Close all tabs and windows. Reset 'equalalways' to avoid redraws. 875p_ea = false; 876if (first_tabpage != NULL && first_tabpage -> tp_next != NULL ) { 877do_cmdline_cmd ("tabonly!" ); 878 } 879 880// Free all spell info. 881spell_free_all (); 882 883// Clear user commands (before deleting buffers). 884ex_comclear (NULL ); 885 886if (curbuf != NULL ) { 887// Clear menus. 888do_cmdline_cmd ("aunmenu *" ); 889do_cmdline_cmd ("tlunmenu *" ); 890do_cmdline_cmd ("menutranslate clear" ); 891 892// Clear mappings, abbreviations, breakpoints. 893// NB: curbuf not used with local=false arg 894map_clear_mode (curbuf ,MAP_ALL_MODES , false, false); 895map_clear_mode (curbuf ,MAP_ALL_MODES , false, true); 896do_cmdline_cmd ("breakdel *" ); 897do_cmdline_cmd ("profdel *" ); 898do_cmdline_cmd ("set keymap=" ); 899 } 900 901free_titles (); 902free_findfile (); 903 904// Obviously named calls. 905free_all_autocmds (); 906free_all_marks (); 907alist_clear (& global_alist ); 908free_homedir (); 909free_users (); 910free_search_patterns (); 911free_old_sub (); 912free_last_insert (); 913free_insexpand_stuff (); 914free_prev_shellcmd (); 915free_regexp_stuff (); 916free_tag_stuff (); 917free_cd_dir (); 918free_signs (); 919set_expr_line (NULL ); 920if (curtab != NULL ) { 921diff_clear (curtab ); 922 } 923clear_sb_text (true);// free any scrollback text 924 925// Free some global vars. 926xfree (last_cmdline ); 927xfree (new_last_cmdline ); 928set_keep_msg (NULL ,0 ); 929 930// Clear cmdline history. 931p_hi = 0 ; 932init_history (); 933 934free_quickfix (); 935 936// Close all script inputs. 937close_all_scripts (); 938 939if (curwin != NULL ) { 940// Destroy all windows. Must come before freeing buffers. 941win_free_all (); 942 } 943 944// Free all option values. Must come after closing windows. 945free_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. 951p_acd = false; 952for (buf = firstbuf ;buf != NULL ;) { 953bufref_T bufref ; 954set_bufref (& bufref ,buf ); 955nextbuf = buf -> b_next ; 956// All windows were freed. Reset b_nwindows so buffers can be wiped. 957buf -> 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. 961buf_free_callbacks (buf ); 962 963close_buffer (NULL ,buf ,DOBUF_WIPE , false, false, false); 964// Didn't work, try next one. 965buf = bufref_valid (& bufref ) ?nextbuf :firstbuf ; 966 } 967 968// Clear registers. 969clear_registers (); 970redo_free_all (); 971 972// highlight info 973free_highlight (); 974 975reset_last_sourcing (); 976 977if (first_tabpage != NULL ) { 978free_tabpage (first_tabpage ); 979first_tabpage = NULL ; 980 } 981 982// message history 983msg_hist_clear (0 ); 984 985channel_free_all_mem (); 986eval_clear (); 987api_extmark_free_all_mem (); 988atom_free_all (); 989mc_free_all (); 990 991map_destroy (int ,& buffer_handles ); 992map_destroy (int ,& window_handles ); 993map_destroy (int ,& tabpage_handles ); 994 995// free screenlines (can't display anything now!) 996grid_free_all_mem (); 997stl_clear_click_defs (tab_page_click_defs ,tab_page_click_defs_size ); 998xfree (tab_page_click_defs ); 999 1000clear_hl_tables (false); 1001 1002check_quickfix_busy (); 1003 1004decor_free_all_mem (); 1005drawline_free_all_mem (); 1006 1007if (ui_client_channel_id ) { 1008ui_client_free_all_mem (); 1009 } 1010 1011remote_ui_free_all_mem (); 1012ui_free_all_mem (); 1013ui_comp_free_all_mem (); 1014nlua_free_all_mem (); 1015rpc_free_all_mem (); 1016autocmd_free_all_mem (); 1017 1018// should be last, in case earlier free functions deallocates arenas 1019arena_free_reuse_blks (); 1020} 1021 1022#endif