robin/laufey

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

robinmerge: 8c77b5be50c50ab119

master
129.5 KiB3774 linesraw
1#include <assert.h>
2#include <inttypes.h>
3#include <stdbool.h>
4#include <stddef.h>
5#include <stdlib.h>
6#include <string.h>
7#include <sys/stat.h>
8#include <uv.h>
9
10#include "auto/config.h"
11#include "klib/kvec.h"
12#include "mpack/mpack_core.h"
13#include "nvim/api/keysets_defs.h"
14#include "nvim/api/private/defs.h"
15#include "nvim/api/private/dispatch.h"
16#include "nvim/api/private/helpers.h"
17#include "nvim/ascii_defs.h"
18#include "nvim/buffer.h"
19#include "nvim/buffer_defs.h"
20#include "nvim/cmdhist.h"
21#include "nvim/eval.h"
22#include "nvim/eval/decode.h"
23#include "nvim/eval/encode.h"
24#include "nvim/eval/typval.h"
25#include "nvim/eval/typval_defs.h"
26#include "nvim/eval/vars.h"
27#include "nvim/ex_cmds.h"
28#include "nvim/ex_cmds_defs.h"
29#include "nvim/ex_docmd.h"
30#include "nvim/fileio.h"
31#include "nvim/gettext_defs.h"
32#include "nvim/globals.h"
33#include "nvim/hashtab.h"
34#include "nvim/hashtab_defs.h"
35#include "nvim/macros_defs.h"
36#include "nvim/map_defs.h"
37#include "nvim/mark.h"
38#include "nvim/mark_defs.h"
39#include "nvim/mbyte.h"
40#include "nvim/memory.h"
41#include "nvim/memory_defs.h"
42#include "nvim/message.h"
43#include "nvim/msgpack_rpc/packer.h"
44#include "nvim/msgpack_rpc/packer_defs.h"
45#include "nvim/msgpack_rpc/unpacker.h"
46#include "nvim/normal_defs.h"
47#include "nvim/option.h"
48#include "nvim/option_vars.h"
49#include "nvim/os/fileio.h"
50#include "nvim/os/fileio_defs.h"
51#include "nvim/os/fs.h"
52#include "nvim/os/fs_defs.h"
53#include "nvim/os/os.h"
54#include "nvim/os/os_defs.h"
55#include "nvim/os/time.h"
56#include "nvim/os/time_defs.h"
57#include "nvim/path.h"
58#include "nvim/pos_defs.h"
59#include "nvim/regexp.h"
60#include "nvim/register.h"
61#include "nvim/search.h"
62#include "nvim/shada.h"
63#include "nvim/strings.h"
64#include "nvim/types_defs.h"
65#include "nvim/version.h"
66#include "nvim/vim_defs.h"
67
68#ifdef HAVE_BE64TOH
69# define _BSD_SOURCE 1  // NOLINT(bugprone-reserved-identifier)
70# define _DEFAULT_SOURCE 1  // NOLINT(bugprone-reserved-identifier)
71# include ENDIAN_INCLUDE_FILE
72#endif
73
74#define SEARCH_KEY_MAGIC sm
75#define SEARCH_KEY_SMARTCASE sc
76#define SEARCH_KEY_HAS_LINE_OFFSET sl
77#define SEARCH_KEY_PLACE_CURSOR_AT_END se
78#define SEARCH_KEY_IS_LAST_USED su
79#define SEARCH_KEY_IS_SUBSTITUTE_PATTERN ss
80#define SEARCH_KEY_HIGHLIGHTED sh
81#define SEARCH_KEY_OFFSET so
82#define SEARCH_KEY_PAT sp
83#define SEARCH_KEY_BACKWARD sb
84
85#define REG_KEY_TYPE rt
86#define REG_KEY_WIDTH rw
87#define REG_KEY_CONTENTS rc
88#define REG_KEY_UNNAMED ru
89
90#define KEY_LNUM l
91#define KEY_COL c
92#define KEY_FILE f
93#define KEY_NAME_CHAR n
94
95// Error messages formerly used by viminfo code:
96//   E136: viminfo: Too many errors, skipping rest of file
97//   E137: Viminfo file is not writable: %s
98//   E138: Can't write viminfo file %s!
99//   E195: Cannot open ShaDa file for reading
100//   E574: Unknown register type %d
101//   E575: Illegal starting char
102//   E576: Missing '>'
103//   E577: Illegal register name
104//   E886: Can't rename viminfo file to %s!
105//   E929: Too many viminfo temp files, like %s!
106// Now only six of them are used:
107//   E137: ShaDa file is not writeable (for pre-open checks)
108//   E929: All %s.tmp.X files exist, cannot write ShaDa file!
109//   RCERR (E576) for critical read errors.
110//   RNERR (E136) for various errors when renaming.
111//   RERR (E575) for various errors inside read ShaDa file.
112//   SERR (E886) for various “system” errors (always contains output of
113//   strerror)
114//   WERR (E574) for various ignorable write errors
115
116/// Common prefix for all errors inside ShaDa file
117///
118/// I.e. errors occurred while parsing, but not system errors occurred while
119/// reading.
120#define RERR "E575: "
121
122/// Common prefix for critical read errors
123///
124/// I.e. errors that make shada_read_next_item return kSDReadStatusNotShaDa.
125#define RCERR "E576: "
126
127/// Common prefix for all “system” errors
128#define SERR "E886: "
129
130/// Common prefix for all “rename” errors
131#define RNERR "E136: "
132
133/// Common prefix for all ignorable “write” errors
134#define WERR "E574: "
135
136/// Callback function for add_search_pattern
137typedef void (*SearchPatternGetter)(SearchPattern *);
138
139/// Possible ShaDa entry types
140///
141/// @warning Enum values are part of the API and must not be altered.
142///
143/// All values that are not in enum are ignored.
144typedef enum {
145  kSDItemUnknown = -1,       ///< Unknown item.
146  kSDItemMissing = 0,        ///< Missing value. Should never appear in a file.
147  kSDItemHeader = 1,         ///< Header. Present for debugging purposes.
148  kSDItemSearchPattern = 2,  ///< Last search pattern (*not* history item).
149                             ///< Comes from user searches (e.g. when typing
150                             ///< "/pat") or :substitute command calls.
151  kSDItemSubString = 3,      ///< Last substitute replacement string.
152  kSDItemHistoryEntry = 4,   ///< History item.
153  kSDItemRegister = 5,       ///< Register.
154  kSDItemVariable = 6,       ///< Global variable.
155  kSDItemGlobalMark = 7,     ///< Global mark definition.
156  kSDItemJump = 8,           ///< Item from jump list.
157  kSDItemBufferList = 9,     ///< Buffer list.
158  kSDItemLocalMark = 10,     ///< Buffer-local mark.
159  kSDItemChange = 11,        ///< Item from buffer change list.
160} ShadaEntryType;
161#define SHADA_LAST_ENTRY ((uint64_t)kSDItemChange)
162
163/// Possible results when reading ShaDa file
164typedef enum {
165  kSDReadStatusSuccess,    ///< Reading was successful.
166  kSDReadStatusFinished,   ///< Nothing more to read.
167  kSDReadStatusReadError,  ///< Failed to read from file.
168  kSDReadStatusNotShaDa,   ///< Input is most likely not a ShaDa file.
169  kSDReadStatusMalformed,  ///< Error in the currently read item.
170} ShaDaReadResult;
171
172/// Possible results of shada_write function.
173typedef enum {
174  kSDWriteSuccessful,    ///< Writing was successful.
175  kSDWriteReadNotShada,  ///< Writing was successful, but when reading it
176                         ///< attempted to read file that did not look like
177                         ///< a ShaDa file.
178  kSDWriteFailed,        ///< Writing was not successful (e.g. because there
179                         ///< was no space left on device).
180  kSDWriteIgnError,      ///< Writing resulted in a error which can be ignored
181                         ///< (e.g. when trying to dump a function reference or
182                         ///< self-referencing container in a variable).
183} ShaDaWriteResult;
184
185/// Flags for shada_read_next_item
186enum SRNIFlags {
187  kSDReadHeader = (1 << kSDItemHeader),  ///< Determines whether header should
188                                         ///< be read (it is usually ignored).
189  kSDReadUndisableableData = (
190                              (1 << kSDItemSearchPattern)
191                              | (1 << kSDItemSubString)
192                              | (1 << kSDItemJump)),  ///< Data reading which cannot be disabled by
193                                                      ///< &shada or other options except for disabling
194                                                      ///< reading ShaDa as a whole.
195  kSDReadRegisters = (1 << kSDItemRegister),  ///< Determines whether registers
196                                              ///< should be read (may only be
197                                              ///< disabled when writing, but
198                                              ///< not when reading).
199  kSDReadHistory = (1 << kSDItemHistoryEntry),  ///< Determines whether history
200                                                ///< should be read (can only be
201                                                ///< disabled by &history).
202  kSDReadVariables = (1 << kSDItemVariable),  ///< Determines whether variables
203                                              ///< should be read (disabled by
204                                              ///< removing ! from &shada).
205  kSDReadBufferList = (1 << kSDItemBufferList),  ///< Determines whether buffer
206                                                 ///< list should be read
207                                                 ///< (disabled by removing
208                                                 ///< % entry from &shada).
209  kSDReadUnknown = (1 << (SHADA_LAST_ENTRY + 1)),  ///< Determines whether
210                                                   ///< unknown items should be
211                                                   ///< read (usually disabled).
212  kSDReadGlobalMarks = (1 << kSDItemGlobalMark),  ///< Determines whether global
213                                                  ///< marks should be read. Can
214                                                  ///< only be disabled by
215                                                  ///< having f0 in &shada when
216                                                  ///< writing.
217  kSDReadLocalMarks = (1 << kSDItemLocalMark),  ///< Determines whether local
218                                                ///< marks should be read. Can
219                                                ///< only be disabled by
220                                                ///< disabling &shada or putting
221                                                ///< '0 there. Is also used for
222                                                ///< v:oldfiles.
223  kSDReadChanges = (1 << kSDItemChange),  ///< Determines whether change list
224                                          ///< should be read. Can only be
225                                          ///< disabled by disabling &shada or
226                                          ///< putting '0 there.
227};
228// Note: SRNIFlags enum name was created only to make it possible to reference
229// it. This name is not actually used anywhere outside of the documentation.
230
231/// Structure defining a single ShaDa file entry
232typedef struct {
233  ShadaEntryType type;
234  // If the entry was read from file, string data will be allocated and needs to be freed.
235  // Entries can also be constructed from nvim internal data structures (like registers)
236  // and reference their allocated strings. then shada code must not attempt to free these.
237  bool can_free_entry;
238  Timestamp timestamp;
239  union {
240    Dict header;
241    struct shada_filemark {
242      char name;
243      pos_T mark;
244      char *fname;
245    } filemark;
246    Dict(_shada_search_pat) search_pattern;
247    struct history_item {
248      uint8_t histtype;
249      char *string;
250      char sep;
251    } history_item;
252    struct reg {  // yankreg_T
253      char name;
254      MotionType type;
255      String *contents;
256      bool is_unnamed;
257      size_t contents_size;
258      size_t width;
259    } reg;
260    struct global_var {
261      char *name;
262      typval_T value;
263    } global_var;
264    struct {
265      uint64_t type;
266      char *contents;
267      size_t size;
268    } unknown_item;
269    struct sub_string {
270      char *sub;
271    } sub_string;
272    struct buffer_list {
273      size_t size;
274      struct buffer_list_buffer {
275        pos_T pos;
276        char *fname;
277        AdditionalData *additional_data;
278      } *buffers;
279    } buffer_list;
280  } data;
281  AdditionalData *additional_data;
282} ShadaEntry;
283
284/// One entry in sized linked list
285typedef struct hm_llist_entry {
286  ShadaEntry data;              ///< Entry data.
287  struct hm_llist_entry *next;  ///< Pointer to next entry or NULL.
288  struct hm_llist_entry *prev;  ///< Pointer to previous entry or NULL.
289} HMLListEntry;
290
291/// Sized linked list structure for history merger
292typedef struct {
293  HMLListEntry *entries;  ///< Pointer to the start of the allocated array of
294                          ///< entries.
295  HMLListEntry *first;    ///< First entry in the list (is not necessary start
296                          ///< of the array) or NULL.
297  HMLListEntry *last;     ///< Last entry in the list or NULL.
298  HMLListEntry *free_entry;  ///< Last free entry removed by hmll_remove.
299  HMLListEntry *last_free_entry;  ///< Last unused element in entries array.
300  size_t size;            ///< Number of allocated entries.
301  size_t num_entries;     ///< Number of entries already used.
302  PMap(cstr_t) contained_entries;  ///< Map all history entry strings to
303                                   ///< corresponding entry pointers.
304} HMLList;
305
306typedef struct {
307  HMLList hmll;
308  bool do_merge;
309  bool reading;
310  const void *iter;
311  ShadaEntry last_hist_entry;
312  uint8_t history_type;
313} HistoryMergerState;
314
315/// Structure that holds one file marks.
316typedef struct {
317  ShadaEntry marks[NLOCALMARKS];  ///< All file marks.
318  ShadaEntry changes[JUMPLISTSIZE];  ///< All file changes.
319  size_t changes_size;  ///< Number of changes occupied.
320  ShadaEntry *additional_marks;  ///< All marks with unknown names.
321  size_t additional_marks_size;  ///< Size of the additional_marks array.
322  Timestamp greatest_timestamp;  ///< Greatest timestamp among marks.
323} FileMarks;
324
325/// State structure used by shada_write
326///
327/// Before actually writing most of the data is read to this structure.
328typedef struct {
329  HistoryMergerState hms[HIST_COUNT];  ///< Structures for history merging.
330  ShadaEntry global_marks[NMARKS];  ///< Named global marks.
331  ShadaEntry numbered_marks[EXTRA_MARKS];  ///< Numbered marks.
332  ShadaEntry registers[NUM_SAVED_REGISTERS];  ///< All registers.
333  ShadaEntry jumps[JUMPLISTSIZE];  ///< All dumped jumps.
334  size_t jumps_size;  ///< Number of jumps occupied.
335  ShadaEntry search_pattern;  ///< Last search pattern.
336  ShadaEntry sub_search_pattern;  ///< Last s/ search pattern.
337  ShadaEntry replacement;  ///< Last s// replacement string.
338  Set(cstr_t) dumped_variables;  ///< Names of already dumped variables.
339  PMap(cstr_t) file_marks;  ///< All file marks.
340} WriteMergerState;
341
342#include "shada.c.generated.h"
343
344#define DEF_SDE(name, attr, ...) \
345  [kSDItem##name] = { \
346    .timestamp = 0, \
347    .type = kSDItem##name, \
348    .additional_data = NULL, \
349    .data = { \
350      .attr = { __VA_ARGS__ } \
351    } \
352  }
353#define DEFAULT_POS { 1, 0, 0 }
354static const pos_T default_pos = DEFAULT_POS;
355static const ShadaEntry sd_default_values[] = {
356  [kSDItemMissing] = { .type = kSDItemMissing, .timestamp = 0 },
357  DEF_SDE(Header, header, .size = 0),
358  DEF_SDE(SearchPattern, search_pattern,
359          .magic = true,
360          .smartcase = false,
361          .has_line_offset = false,
362          .place_cursor_at_end = false,
363          .offset = 0,
364          .is_last_used = true,
365          .is_substitute_pattern = false,
366          .highlighted = false,
367          .search_backward = false,
368          .pat = STRING_INIT),
369  DEF_SDE(SubString, sub_string, .sub = NULL),
370  DEF_SDE(HistoryEntry, history_item,
371          .histtype = HIST_CMD,
372          .string = NULL,
373          .sep = NUL),
374  DEF_SDE(Register, reg,
375          .name = NUL,
376          .type = kMTCharWise,
377          .contents = NULL,
378          .contents_size = 0,
379          .is_unnamed = false,
380          .width = 0),
381  DEF_SDE(Variable, global_var,
382          .name = NULL,
383          .value = { .v_type = VAR_UNKNOWN, .vval = { .v_string = NULL } }),
384  DEF_SDE(GlobalMark, filemark,
385          .name = '"',
386          .mark = DEFAULT_POS,
387          .fname = NULL),
388  DEF_SDE(Jump, filemark,
389          .name = NUL,
390          .mark = DEFAULT_POS,
391          .fname = NULL),
392  DEF_SDE(BufferList, buffer_list,
393          .size = 0,
394          .buffers = NULL),
395  DEF_SDE(LocalMark, filemark,
396          .name = '"',
397          .mark = DEFAULT_POS,
398          .fname = NULL),
399  DEF_SDE(Change, filemark,
400          .name = NUL,
401          .mark = DEFAULT_POS,
402          .fname = NULL),
403};
404#undef DEFAULT_POS
405#undef DEF_SDE
406
407/// Initialize new linked list
408///
409/// @param[out]  hmll       List to initialize.
410/// @param[in]   size       Maximum size of the list.
411static inline void hmll_init(HMLList *const hmll, const size_t size)
412  FUNC_ATTR_NONNULL_ALL
413{
414  *hmll = (HMLList) {
415    .entries = xcalloc(size, sizeof(hmll->entries[0])),
416    .first = NULL,
417    .last = NULL,
418    .free_entry = NULL,
419    .size = size,
420    .num_entries = 0,
421    .contained_entries = MAP_INIT,
422  };
423  hmll->last_free_entry = hmll->entries;
424}
425
426/// Iterate over HMLList in forward direction
427///
428/// @param  hmll       Pointer to the list.
429/// @param  cur_entry  Name of the variable to iterate over.
430/// @param  code       Code to execute on each iteration.
431///
432/// @return `for` cycle header (use `HMLL_FORALL(hmll, cur_entry) {body}`).
433#define HMLL_FORALL(hmll, cur_entry, code) \
434  for (HMLListEntry *(cur_entry) = (hmll)->first; (cur_entry) != NULL; \
435       (cur_entry) = (cur_entry)->next) { \
436    code \
437  } \
438
439/// Remove entry from the linked list
440///
441/// @param  hmll        List to remove from.
442/// @param  hmll_entry  Entry to remove.
443static inline void hmll_remove(HMLList *const hmll, HMLListEntry *const hmll_entry)
444  FUNC_ATTR_NONNULL_ALL
445{
446  if (hmll_entry == hmll->last_free_entry - 1) {
447    hmll->last_free_entry--;
448  } else {
449    assert(hmll->free_entry == NULL);
450    hmll->free_entry = hmll_entry;
451  }
452  ptr_t val = pmap_del(cstr_t)(&hmll->contained_entries,
453                               hmll_entry->data.data.history_item.string, NULL);
454  assert(val);
455  (void)val;
456  if (hmll_entry->next == NULL) {
457    hmll->last = hmll_entry->prev;
458  } else {
459    hmll_entry->next->prev = hmll_entry->prev;
460  }
461  if (hmll_entry->prev == NULL) {
462    hmll->first = hmll_entry->next;
463  } else {
464    hmll_entry->prev->next = hmll_entry->next;
465  }
466  hmll->num_entries--;
467  shada_free_shada_entry(&hmll_entry->data);
468}
469
470/// Insert entry to the linked list
471///
472/// @param[out]  hmll            List to insert to.
473/// @param[in]   hmll_entry      Entry to insert after or NULL if it is needed
474///                              to insert at the first entry.
475/// @param[in]   data            Data to insert.
476static inline void hmll_insert(HMLList *const hmll, HMLListEntry *hmll_entry, const ShadaEntry data)
477  FUNC_ATTR_NONNULL_ARG(1)
478{
479  if (hmll->num_entries == hmll->size) {
480    if (hmll_entry == hmll->first) {
481      hmll_entry = NULL;
482    }
483    assert(hmll->first != NULL);
484    hmll_remove(hmll, hmll->first);
485  }
486  HMLListEntry *target_entry;
487  if (hmll->free_entry == NULL) {
488    assert((size_t)(hmll->last_free_entry - hmll->entries)
489           == hmll->num_entries);
490    target_entry = hmll->last_free_entry++;
491  } else {
492    assert((size_t)(hmll->last_free_entry - hmll->entries) - 1
493           == hmll->num_entries);
494    target_entry = hmll->free_entry;
495    hmll->free_entry = NULL;
496  }
497  target_entry->data = data;
498  bool new_item = false;
499  ptr_t *val = pmap_put_ref(cstr_t)(&hmll->contained_entries, data.data.history_item.string,
500                                    NULL, &new_item);
501  if (new_item) {
502    *val = target_entry;
503  }
504  hmll->num_entries++;
505  target_entry->prev = hmll_entry;
506  if (hmll_entry == NULL) {
507    target_entry->next = hmll->first;
508    hmll->first = target_entry;
509  } else {
510    target_entry->next = hmll_entry->next;
511    hmll_entry->next = target_entry;
512  }
513  if (target_entry->next == NULL) {
514    hmll->last = target_entry;
515  } else {
516    target_entry->next->prev = target_entry;
517  }
518}
519
520/// Free linked list
521///
522/// @param[in]  hmll  List to free.
523static inline void hmll_dealloc(HMLList *const hmll)
524  FUNC_ATTR_NONNULL_ALL
525{
526  map_destroy(cstr_t, &hmll->contained_entries);
527  xfree(hmll->entries);
528}
529
530/// Wrapper for read that can be used when lseek cannot be used
531///
532/// E.g. when trying to read from a pipe.
533///
534/// @param[in,out]  sd_reader  File read.
535/// @param[in]      offset     Amount of bytes to skip.
536///
537/// @return kSDReadStatusReadError, kSDReadStatusNotShaDa or
538///         kSDReadStatusSuccess.
539static ShaDaReadResult sd_reader_skip(FileDescriptor *const sd_reader, const size_t offset)
540  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
541{
542  const ptrdiff_t skip_bytes = file_skip(sd_reader, offset);
543  if (skip_bytes < 0) {
544    semsg(_(SERR "System error while skipping in ShaDa file: %s"), os_strerror((int)skip_bytes));
545    return kSDReadStatusReadError;
546  } else if (skip_bytes != (ptrdiff_t)offset) {
547    assert(skip_bytes < (ptrdiff_t)offset);
548    if (file_eof(sd_reader)) {
549      semsg(_(RCERR "Reading ShaDa file: last entry specified that it occupies %" PRIu64 " bytes, "
550              "but file ended earlier"),
551            (uint64_t)offset);
552    } else {
553      semsg(_(SERR "System error while skipping in ShaDa file: %s"), _("too few bytes read"));
554    }
555    return kSDReadStatusNotShaDa;
556  }
557  return kSDReadStatusSuccess;
558}
559
560/// Wrapper for closing file descriptors
561static void close_file(FileDescriptor *cookie)
562{
563  const int error = file_close(cookie, !!p_fs);
564  if (error != 0) {
565    semsg(_(SERR "System error while closing ShaDa file: %s"),
566          os_strerror(error));
567  }
568}
569
570/// Read ShaDa file
571///
572/// @param[in]  file   File to read or NULL to use default name.
573/// @param[in]  flags  Flags, see ShaDaReadFileFlags enum.
574///
575/// @return FAIL if reading failed for some reason and OK otherwise.
576static int shada_read_file(const char *const file, const int flags)
577  FUNC_ATTR_WARN_UNUSED_RESULT
578{
579  char *const fname = shada_filename(file);
580  if (fname == NULL) {
581    return FAIL;
582  }
583
584  FileDescriptor sd_reader;
585  int of_ret = file_open(&sd_reader, fname, kFileReadOnly, 0);
586
587  if (p_verbose > 1) {
588    verbose_enter();
589    smsg(0, _("Reading ShaDa file \"%s\"%s%s%s%s"),
590         fname,
591         (flags & kShaDaWantInfo) ? _(" info") : "",
592         (flags & kShaDaWantMarks) ? _(" marks") : "",
593         (flags & kShaDaGetOldfiles) ? _(" oldfiles") : "",
594         of_ret != 0 ? _(" FAILED") : "");
595    verbose_leave();
596  }
597
598  if (of_ret != 0) {
599    if (of_ret != UV_ENOENT || (flags & kShaDaMissingError)) {
600      semsg(_(SERR "System error while opening ShaDa file %s for reading: %s"),
601            fname, os_strerror(of_ret));
602    }
603    xfree(fname);
604    return FAIL;
605  }
606  xfree(fname);
607
608  shada_read(&sd_reader, flags);
609  close_file(&sd_reader);
610
611  return OK;
612}
613
614/// Wrapper for hist_iter() function which produces ShadaEntry values
615///
616/// @param[in]   iter          Current iteration state.
617/// @param[in]   history_type  Type of the history (HIST_*).
618/// @param[in]   zero          If true, then item is removed from instance
619///                            memory upon reading.
620/// @param[out]  hist          Location where iteration results should be saved.
621///
622/// @return Next iteration state.
623static const void *shada_hist_iter(const void *const iter, const uint8_t history_type,
624                                   const bool zero, ShadaEntry *const hist)
625  FUNC_ATTR_NONNULL_ARG(4) FUNC_ATTR_WARN_UNUSED_RESULT
626{
627  histentry_T hist_he;
628  const void *const ret = hist_iter(iter, history_type, zero, &hist_he);
629  if (hist_he.hisstr == NULL) {
630    *hist = (ShadaEntry) { .type = kSDItemMissing };
631  } else {
632    *hist = (ShadaEntry) {
633      .can_free_entry = zero,
634      .type = kSDItemHistoryEntry,
635      .timestamp = hist_he.timestamp,
636      .data = {
637        .history_item = {
638          .histtype = history_type,
639          .string = hist_he.hisstr,
640          .sep = (char)(history_type == HIST_SEARCH
641                        ? hist_he.hisstr[hist_he.hisstrlen + 1]
642                        : 0),
643        }
644      },
645      .additional_data = hist_he.additional_data,
646    };
647  }
648  return ret;
649}
650
651/// Insert history entry
652///
653/// Inserts history entry at the end of the ring buffer (may insert earlier
654/// according to the timestamp). If entry was already in the ring buffer
655/// existing entry will be removed unless it has greater timestamp.
656///
657/// Before the new entry entries from the current Neovim history will be
658/// inserted unless `do_iter` argument is false.
659///
660/// @param[in,out]  hms_p           Ring buffer and associated structures.
661/// @param[in]      entry           Inserted entry.
662/// @param[in]      do_iter         Determines whether Neovim own history should
663///                                 be used. Must be true only if inserting
664///                                 entry from current Neovim history.
665static void hms_insert(HistoryMergerState *const hms_p, const ShadaEntry entry, const bool do_iter)
666  FUNC_ATTR_NONNULL_ALL
667{
668  if (do_iter) {
669    while (hms_p->last_hist_entry.type != kSDItemMissing
670           && hms_p->last_hist_entry.timestamp < entry.timestamp) {
671      hms_insert(hms_p, hms_p->last_hist_entry, false);
672      if (hms_p->iter == NULL) {
673        hms_p->last_hist_entry.type = kSDItemMissing;
674        break;
675      }
676      hms_p->iter = shada_hist_iter(hms_p->iter, hms_p->history_type,
677                                    hms_p->reading, &hms_p->last_hist_entry);
678    }
679  }
680  HMLList *const hmll = &hms_p->hmll;
681  cstr_t *key_alloc = NULL;
682  ptr_t *val = pmap_ref(cstr_t)(&hms_p->hmll.contained_entries, entry.data.history_item.string,
683                                &key_alloc);
684  if (val) {
685    HMLListEntry *const existing_entry = *val;
686    if (entry.timestamp > existing_entry->data.timestamp) {
687      hmll_remove(hmll, existing_entry);
688    } else if (!do_iter && entry.timestamp == existing_entry->data.timestamp) {
689      // Prefer entry from the current Neovim instance.
690      shada_free_shada_entry(&existing_entry->data);
691      existing_entry->data = entry;
692      // Previous key was freed above, as part of freeing the ShaDa entry.
693      *key_alloc = entry.data.history_item.string;
694      return;
695    } else {
696      return;
697    }
698  }
699  HMLListEntry *insert_after;
700  // Iterate over HMLList in backward direction
701  for (insert_after = hmll->last; insert_after != NULL; insert_after = insert_after->prev) {
702    if (insert_after->data.timestamp <= entry.timestamp) {
703      break;
704    }
705  }
706  hmll_insert(hmll, insert_after, entry);
707}
708
709/// Initialize the history merger
710///
711/// @param[out]  hms_p         Structure to be initialized.
712/// @param[in]   history_type  History type (one of HIST_\* values).
713/// @param[in]   num_elements  Number of elements in the result.
714/// @param[in]   do_merge      Prepare structure for merging elements.
715/// @param[in]   reading       If true, then merger is reading history for use
716///                            in Neovim.
717static inline void hms_init(HistoryMergerState *const hms_p, const uint8_t history_type,
718                            const size_t num_elements, const bool do_merge, const bool reading)
719  FUNC_ATTR_NONNULL_ALL
720{
721  hmll_init(&hms_p->hmll, num_elements);
722  hms_p->do_merge = do_merge;
723  hms_p->reading = reading;
724  hms_p->iter = shada_hist_iter(NULL, history_type, hms_p->reading,
725                                &hms_p->last_hist_entry);
726  hms_p->history_type = history_type;
727}
728
729/// Merge in all remaining Neovim own history entries
730///
731/// @param[in,out]  hms_p  Merger structure into which history should be
732///                        inserted.
733static inline void hms_insert_whole_neovim_history(HistoryMergerState *const hms_p)
734  FUNC_ATTR_NONNULL_ALL
735{
736  while (hms_p->last_hist_entry.type != kSDItemMissing) {
737    hms_insert(hms_p, hms_p->last_hist_entry, false);
738    if (hms_p->iter == NULL) {
739      break;
740    }
741    hms_p->iter = shada_hist_iter(hms_p->iter, hms_p->history_type,
742                                  hms_p->reading, &hms_p->last_hist_entry);
743  }
744}
745
746/// Convert merger structure to Neovim internal structure for history
747///
748/// @param[in]   hms_p       Converted merger structure.
749/// @param[out]  hist_array  Array with the results.
750/// @param[out]  new_hisidx  New last history entry index.
751/// @param[out]  new_hisnum  Amount of history items in merger structure.
752static inline void hms_to_he_array(const HistoryMergerState *const hms_p,
753                                   histentry_T *const hist_array, int *const new_hisidx,
754                                   int *const new_hisnum)
755  FUNC_ATTR_NONNULL_ALL
756{
757  histentry_T *hist = hist_array;
758  HMLL_FORALL(&hms_p->hmll, cur_entry,  {
759    hist->timestamp = cur_entry->data.timestamp;
760    hist->hisnum = (int)(hist - hist_array) + 1;
761    hist->hisstr = cur_entry->data.data.history_item.string;
762    hist->hisstrlen = strlen(cur_entry->data.data.history_item.string);
763    hist->additional_data = cur_entry->data.additional_data;
764    hist++;
765  })
766  *new_hisnum = (int)(hist - hist_array);
767  *new_hisidx = *new_hisnum - 1;
768}
769
770/// Free history merger structure
771///
772/// @param[in]  hms_p  Structure to be freed.
773static inline void hms_dealloc(HistoryMergerState *const hms_p)
774  FUNC_ATTR_NONNULL_ALL
775{
776  hmll_dealloc(&hms_p->hmll);
777}
778
779/// Iterate over all history entries in history merger, in order
780///
781/// @param[in]   hms_p      Merger structure to iterate over.
782/// @param[out]  cur_entry  Name of the iterator variable.
783/// @param       code       Code to execute on each iteration.
784///
785/// @return for cycle header. Use `HMS_ITER(hms_p, cur_entry) {body}`.
786#define HMS_ITER(hms_p, cur_entry, code) \
787  HMLL_FORALL(&((hms_p)->hmll), cur_entry, code)
788
789/// Iterate over global variables
790///
791/// @warning No modifications to global variable Dict must be performed
792///          while iteration is in progress.
793///
794/// @param[in]   iter   Iterator. Pass NULL to start iteration.
795/// @param[out]  name   Variable name.
796/// @param[out]  rettv  Variable value.
797///
798/// @return Pointer that needs to be passed to next `var_shada_iter` invocation
799///         or NULL to indicate that iteration is over.
800static const void *var_shada_iter(const void *const iter, const char **const name, typval_T *rettv,
801                                  var_flavour_T flavour)
802  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(2, 3)
803{
804  const hashitem_T *hi;
805  hashtab_T *globvarht = get_globvar_ht();
806  const hashitem_T *hifirst = globvarht->ht_array;
807  const size_t hinum = (size_t)globvarht->ht_mask + 1;
808  *name = NULL;
809  if (iter == NULL) {
810    hi = globvarht->ht_array;
811    while ((size_t)(hi - hifirst) < hinum
812           && (HASHITEM_EMPTY(hi)
813               || !(var_flavour(hi->hi_key) & flavour))) {
814      hi++;
815    }
816    if ((size_t)(hi - hifirst) == hinum) {
817      return NULL;
818    }
819  } else {
820    hi = (const hashitem_T *)iter;
821  }
822  *name = TV_DICT_HI2DI(hi)->di_key;
823  tv_copy(&TV_DICT_HI2DI(hi)->di_tv, rettv);
824  while ((size_t)(++hi - hifirst) < hinum) {
825    if (!HASHITEM_EMPTY(hi) && (var_flavour(hi->hi_key) & flavour)) {
826      return hi;
827    }
828  }
829  return NULL;
830}
831
832/// Find buffer for given buffer name (cached)
833///
834/// @param[in,out]  fname_bufs  Cache containing fname to buffer mapping.
835/// @param[in]      fname       File name to find.
836///
837/// @return Pointer to the buffer or NULL.
838static buf_T *find_buffer(PMap(cstr_t) *const fname_bufs, const char *const fname)
839  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
840{
841  cstr_t *key_alloc = NULL;
842  bool new_item = false;
843  buf_T **ref = (buf_T **)pmap_put_ref(cstr_t)(fname_bufs, fname, &key_alloc, &new_item);
844  if (new_item) {
845    *key_alloc = xstrdup(fname);
846  } else {
847    return *ref;  // item already existed (can be a NULL value)
848  }
849
850  FOR_ALL_BUFFERS(buf) {
851    if (buf->b_ffname != NULL) {
852      if (path_equal(fname, buf->b_ffname, kPathCmpLiteral)) {
853        *ref = buf;
854        return buf;
855      }
856    }
857  }
858  *ref = NULL;
859  return NULL;
860}
861
862/// Compare two marks
863static inline bool marks_equal(const pos_T a, const pos_T b)
864{
865  return (a.lnum == b.lnum) && (a.col == b.col);
866}
867
868/// adjust "jumps_arr" to make space to insert an item just before the item at "i"
869/// (or after the last if i == jl_len)
870///
871/// Higher incidies indicate newer items. If the list is full, discard the oldest item
872/// (or don't insert the considered item if it is older)
873///
874/// @return the actual position a new item should be inserted or -1 if it shouldn't be inserted
875static int marklist_insert(void *jumps_arr, size_t jump_size, int jl_len, int i)
876{
877  char *jumps = (char *)jumps_arr;  // for pointer maffs
878  if (i > 0) {
879    if (jl_len == JUMPLISTSIZE) {
880      i--;
881      if (i > 0) {
882        // delete oldest item to make room for new element
883        memmove(jumps, jumps + jump_size, jump_size * (size_t)i);
884      }
885    } else if (i != jl_len) {
886      // insert at position i, move newer items out of the way
887      memmove(jumps + (size_t)(i + 1) * jump_size, jumps + (size_t)i * jump_size,
888              jump_size * (size_t)(jl_len - i));
889    }
890  } else if (i == 0) {
891    if (jl_len == JUMPLISTSIZE) {
892      return -1;  // don't insert, older than the entire list
893    } else if (jl_len > 0) {
894      // insert i as the oldest item
895      memmove(jumps + jump_size, jumps, jump_size * (size_t)jl_len);
896    }
897  }
898  return i;
899}
900
901/// Read data from ShaDa file
902///
903/// @param[in]  sd_reader  Structure containing file reader definition.
904/// @param[in]  flags      What to read, see ShaDaReadFileFlags enum.
905static void shada_read(FileDescriptor *const sd_reader, const int flags)
906  FUNC_ATTR_NONNULL_ALL
907{
908  list_T *oldfiles_list = get_vim_var_list(VV_OLDFILES);
909  const bool force = flags & kShaDaForceit;
910  const bool get_old_files = (flags & kShaDaGetOldfiles)
911                             && (force || tv_list_len(oldfiles_list) == 0);
912  const bool want_marks = flags & kShaDaWantMarks;
913  const bool no_opt = flags & kShaDaNoOpt;
914  const unsigned srni_flags =
915    (unsigned)(
916               (flags & kShaDaWantInfo
917                ? (kSDReadUndisableableData
918                   | kSDReadRegisters
919                   | kSDReadGlobalMarks
920                   | (p_hi && !(flags & kShaDaNoHistory) ? kSDReadHistory : 0)
921                   | (no_opt || find_shada_parameter('!') != NULL
922                      ? kSDReadVariables
923                      : 0)
924                   | ((no_opt || find_shada_parameter('%') != NULL)
925                      && ARGCOUNT == 0
926                      ? kSDReadBufferList
927                      : 0))
928                : 0)
929               | (want_marks && get_shada_parameter('\'') > 0
930                  ? kSDReadLocalMarks | kSDReadChanges
931                  : 0)
932               | (get_old_files
933                  ? kSDReadLocalMarks
934                  : 0));
935  if (srni_flags == 0) {
936    // Nothing to do.
937    return;
938  }
939  HistoryMergerState hms[HIST_COUNT];
940  if (srni_flags & kSDReadHistory) {
941    for (int i = 0; i < HIST_COUNT; i++) {
942      hms_init(&hms[i], (uint8_t)i, (size_t)p_hi, true, true);
943    }
944  }
945  ShadaEntry cur_entry;
946  Set(ptr_t) cl_bufs = SET_INIT;
947  PMap(cstr_t) fname_bufs = MAP_INIT;
948  Set(path_t) oldfiles_set = SET_INIT;
949  if (get_old_files && (oldfiles_list == NULL || force)) {
950    oldfiles_list = tv_list_alloc(kListLenUnknown);
951    set_vim_var_list(VV_OLDFILES, oldfiles_list);
952  }
953  ShaDaReadResult srni_ret;
954  while ((srni_ret = shada_read_next_item(sd_reader, &cur_entry, srni_flags, 0))
955         != kSDReadStatusFinished) {
956    switch (srni_ret) {
957    case kSDReadStatusSuccess:
958      break;
959    case kSDReadStatusFinished:
960      // Should be handled by the while condition.
961      abort();
962    case kSDReadStatusNotShaDa:
963    case kSDReadStatusReadError:
964      goto shada_read_main_cycle_end;
965    case kSDReadStatusMalformed:
966      continue;
967    }
968    switch (cur_entry.type) {
969    case kSDItemMissing:
970      abort();
971    case kSDItemUnknown:
972      break;
973    case kSDItemHeader:
974      shada_free_shada_entry(&cur_entry);
975      break;
976    case kSDItemSearchPattern:
977      if (!force) {
978        SearchPattern pat;
979        if (cur_entry.data.search_pattern.is_substitute_pattern) {
980          get_substitute_pattern(&pat);
981        } else {
982          get_search_pattern(&pat);
983        }
984        if (pat.pat != NULL && pat.timestamp >= cur_entry.timestamp) {
985          shada_free_shada_entry(&cur_entry);
986          break;
987        }
988      }
989
990      SearchPattern spat = (SearchPattern) {
991        .magic = cur_entry.data.search_pattern.magic,
992        .no_scs = !cur_entry.data.search_pattern.smartcase,
993        .off = {
994          .dir = cur_entry.data.search_pattern.search_backward ? '?' : '/',
995          .line = cur_entry.data.search_pattern.has_line_offset,
996          .end = cur_entry.data.search_pattern.place_cursor_at_end,
997          .off = cur_entry.data.search_pattern.offset,
998        },
999        .pat = cur_entry.data.search_pattern.pat.data,
1000        .patlen = cur_entry.data.search_pattern.pat.size,
1001        .additional_data = cur_entry.additional_data,
1002        .timestamp = cur_entry.timestamp,
1003      };
1004
1005      if (cur_entry.data.search_pattern.is_substitute_pattern) {
1006        set_substitute_pattern(spat);
1007      } else {
1008        set_search_pattern(spat);
1009      }
1010
1011      if (cur_entry.data.search_pattern.is_last_used) {
1012        set_last_used_pattern(cur_entry.data.search_pattern.is_substitute_pattern);
1013        set_no_hlsearch(!cur_entry.data.search_pattern.highlighted);
1014      }
1015      // Do not free shada entry: its allocated memory was saved above.
1016      break;
1017    case kSDItemSubString:
1018      if (!force) {
1019        SubReplacementString sub;
1020        sub_get_replacement(&sub);
1021        if (sub.sub != NULL && sub.timestamp >= cur_entry.timestamp) {
1022          shada_free_shada_entry(&cur_entry);
1023          break;
1024        }
1025      }
1026      sub_set_replacement((SubReplacementString) {
1027        .sub = cur_entry.data.sub_string.sub,
1028        .timestamp = cur_entry.timestamp,
1029        .additional_data = cur_entry.additional_data,
1030      });
1031      // Without using regtilde and without / &cpo flag previous substitute
1032      // string is close to useless: you can only use it with :& or :~ and
1033      // that’s all because s//~ is not available until the first call to
1034      // regtilde. Vim was not calling this for some reason.
1035      regtilde(cur_entry.data.sub_string.sub, p_magic, false);
1036      // Do not free shada entry: its allocated memory was saved above.
1037      break;
1038    case kSDItemHistoryEntry:
1039      if (cur_entry.data.history_item.histtype >= HIST_COUNT) {
1040        shada_free_shada_entry(&cur_entry);
1041        break;
1042      }
1043      hms_insert(hms + cur_entry.data.history_item.histtype, cur_entry, true);
1044      // Do not free shada entry: its allocated memory was saved above.
1045      break;
1046    case kSDItemRegister: {
1047      if (cur_entry.data.reg.type != kMTCharWise
1048          && cur_entry.data.reg.type != kMTLineWise
1049          && cur_entry.data.reg.type != kMTBlockWise) {
1050        shada_free_shada_entry(&cur_entry);
1051        break;
1052      }
1053      // reg are ns; shada stores seconds; Context/multicursor wants high-precision comparison.
1054      const Timestamp reg_ts = (flags & kShaDaNanos)
1055                               ? cur_entry.timestamp : cur_entry.timestamp * NS_PER_SEC;
1056      if (!force) {
1057        const yankreg_T *const reg = op_reg_get(cur_entry.data.reg.name);
1058        if (reg == NULL || reg->timestamp >= reg_ts) {
1059          shada_free_shada_entry(&cur_entry);
1060          break;
1061        }
1062      }
1063      if (!op_reg_set(cur_entry.data.reg.name, (yankreg_T) {
1064          .y_array = cur_entry.data.reg.contents,
1065          .y_size = cur_entry.data.reg.contents_size,
1066          .y_type = cur_entry.data.reg.type,
1067          .y_width = (colnr_T)cur_entry.data.reg.width,
1068          .timestamp = reg_ts,
1069          .additional_data = cur_entry.additional_data,
1070        }, cur_entry.data.reg.is_unnamed)) {
1071        shada_free_shada_entry(&cur_entry);
1072      }
1073      // Do not free shada entry: its allocated memory was saved above.
1074      break;
1075    }
1076    case kSDItemVariable:
1077      var_set_global(cur_entry.data.global_var.name,
1078                     cur_entry.data.global_var.value);
1079      cur_entry.data.global_var.value.v_type = VAR_UNKNOWN;
1080      shada_free_shada_entry(&cur_entry);
1081      break;
1082    case kSDItemJump:
1083    case kSDItemGlobalMark: {
1084      buf_T *buf = find_buffer(&fname_bufs, cur_entry.data.filemark.fname);
1085      if (buf != NULL) {
1086        XFREE_CLEAR(cur_entry.data.filemark.fname);
1087      }
1088      xfmark_T fm = (xfmark_T) {
1089        .fname = buf == NULL ? cur_entry.data.filemark.fname : NULL,
1090        .fmark = {
1091          .mark = cur_entry.data.filemark.mark,
1092          .fnum = (buf == NULL ? 0 : buf->b_fnum),
1093          .timestamp = cur_entry.timestamp,
1094          .view = INIT_FMARKV,
1095          .additional_data = cur_entry.additional_data,
1096        },
1097      };
1098      if (cur_entry.type == kSDItemGlobalMark) {
1099        if (!mark_set_global(cur_entry.data.filemark.name, fm, !force)) {
1100          shada_free_shada_entry(&cur_entry);
1101          break;
1102        }
1103      } else {
1104        int i;
1105        for (i = curwin->w_jumplistlen; i > 0; i--) {
1106          const xfmark_T jl_entry = curwin->w_jumplist[i - 1];
1107          if (jl_entry.fmark.timestamp <= cur_entry.timestamp) {
1108            if (marks_equal(jl_entry.fmark.mark, cur_entry.data.filemark.mark)
1109                && (buf == NULL
1110                    ? (jl_entry.fname != NULL && strcmp(fm.fname, jl_entry.fname) == 0)
1111                    : fm.fmark.fnum == jl_entry.fmark.fnum)) {
1112              i = -1;
1113            }
1114            break;
1115          }
1116        }
1117        if (i > 0 && curwin->w_jumplistlen == JUMPLISTSIZE) {
1118          free_xfmark(curwin->w_jumplist[0]);
1119        }
1120        i = marklist_insert(curwin->w_jumplist, sizeof(*curwin->w_jumplist),
1121                            curwin->w_jumplistlen, i);
1122
1123        if (i != -1) {
1124          curwin->w_jumplist[i] = fm;
1125          if (curwin->w_jumplistlen < JUMPLISTSIZE) {
1126            curwin->w_jumplistlen++;
1127          }
1128          if (curwin->w_jumplistidx >= i && curwin->w_jumplistidx + 1 <= curwin->w_jumplistlen) {
1129            curwin->w_jumplistidx++;
1130          }
1131        } else {
1132          shada_free_shada_entry(&cur_entry);
1133        }
1134      }
1135
1136      // Do not free shada entry: its allocated memory was saved above.
1137      break;
1138    }
1139    case kSDItemBufferList:
1140      for (size_t i = 0; i < cur_entry.data.buffer_list.size; i++) {
1141        char *const sfname =
1142          path_try_shorten_fname(cur_entry.data.buffer_list.buffers[i].fname);
1143        buf_T *const buf =
1144          buflist_new(cur_entry.data.buffer_list.buffers[i].fname, sfname, 0, BLN_LISTED);
1145        if (buf != NULL) {
1146          fmarkv_T view = INIT_FMARKV;
1147          RESET_FMARK(&buf->b_last_cursor,
1148                      cur_entry.data.buffer_list.buffers[i].pos, 0, view);
1149          buflist_setfpos(buf, curwin, buf->b_last_cursor.mark.lnum,
1150                          buf->b_last_cursor.mark.col, false);
1151
1152          xfree(buf->additional_data);
1153          buf->additional_data = cur_entry.data.buffer_list.buffers[i].additional_data;
1154          cur_entry.data.buffer_list.buffers[i].additional_data = NULL;
1155        }
1156      }
1157      shada_free_shada_entry(&cur_entry);
1158      break;
1159    case kSDItemChange:
1160    case kSDItemLocalMark: {
1161      if (get_old_files && !set_has(path_t, &oldfiles_set, cur_entry.data.filemark.fname)) {
1162        char *fname = cur_entry.data.filemark.fname;
1163        if (want_marks) {
1164          // Do not bother with allocating memory for the string if already
1165          // allocated string from cur_entry can be used. It cannot be used if
1166          // want_marks is set because this way it may be used for a mark.
1167          fname = xstrdup(fname);
1168        }
1169        set_put(path_t, &oldfiles_set, fname);
1170        tv_list_append_allocated_string(oldfiles_list, fname);
1171        if (!want_marks) {
1172          // Avoid free because this string was already used.
1173          cur_entry.data.filemark.fname = NULL;
1174        }
1175      }
1176      if (!want_marks) {
1177        shada_free_shada_entry(&cur_entry);
1178        break;
1179      }
1180      buf_T *buf = find_buffer(&fname_bufs, cur_entry.data.filemark.fname);
1181      if (buf == NULL) {
1182        shada_free_shada_entry(&cur_entry);
1183        break;
1184      }
1185      const fmark_T fm = (fmark_T) {
1186        .mark = cur_entry.data.filemark.mark,
1187        .fnum = buf->b_fnum,
1188        .timestamp = cur_entry.timestamp,
1189        .view = INIT_FMARKV,
1190        .additional_data = cur_entry.additional_data,
1191      };
1192      if (cur_entry.type == kSDItemLocalMark) {
1193        if (!mark_set_local(cur_entry.data.filemark.name, buf, fm, !force)) {
1194          shada_free_shada_entry(&cur_entry);
1195          break;
1196        }
1197      } else {
1198        set_put(ptr_t, &cl_bufs, buf);
1199        int i;
1200        for (i = buf->b_changelistlen; i > 0; i--) {
1201          const fmark_T jl_entry = buf->b_changelist[i - 1];
1202          if (jl_entry.timestamp <= cur_entry.timestamp) {
1203            if (marks_equal(jl_entry.mark, cur_entry.data.filemark.mark)) {
1204              i = -1;
1205            }
1206            break;
1207          }
1208        }
1209        if (i > 0 && buf->b_changelistlen == JUMPLISTSIZE) {
1210          free_fmark(buf->b_changelist[0]);
1211        }
1212        i = marklist_insert(buf->b_changelist, sizeof(*buf->b_changelist), buf->b_changelistlen, i);
1213        if (i != -1) {
1214          buf->b_changelist[i] = fm;
1215          if (buf->b_changelistlen < JUMPLISTSIZE) {
1216            buf->b_changelistlen++;
1217          }
1218        } else {
1219          xfree(fm.additional_data);
1220        }
1221      }
1222      // only free fname part of shada entry, as additional_data was saved or freed above.
1223      xfree(cur_entry.data.filemark.fname);
1224      break;
1225    }
1226    }
1227  }
1228shada_read_main_cycle_end:
1229  // Warning: shada_hist_iter returns ShadaEntry elements which use strings from
1230  //          original history list. This means that once such entry is removed
1231  //          from the history Neovim array will no longer be valid. To reduce
1232  //          amount of memory allocations ShaDa file reader allocates enough
1233  //          memory for the history string itself and separator character which
1234  //          may be assigned right away.
1235  if (srni_flags & kSDReadHistory) {
1236    for (int i = 0; i < HIST_COUNT; i++) {
1237      hms_insert_whole_neovim_history(&hms[i]);
1238      clr_history(i);
1239      int *new_hisidx;
1240      int *new_hisnum;
1241      histentry_T *hist = hist_get_array((uint8_t)i, &new_hisidx, &new_hisnum);
1242      if (hist != NULL) {
1243        hms_to_he_array(&hms[i], hist, new_hisidx, new_hisnum);
1244      }
1245      hms_dealloc(&hms[i]);
1246    }
1247  }
1248  if (cl_bufs.h.n_occupied) {
1249    FOR_ALL_TAB_WINDOWS(tp, wp) {
1250      (void)tp;
1251      if (set_has(ptr_t, &cl_bufs, wp->w_buffer)) {
1252        wp->w_changelistidx = wp->w_buffer->b_changelistlen;
1253      }
1254    }
1255  }
1256  set_destroy(ptr_t, &cl_bufs);
1257  const char *key;
1258  map_foreach_key(&fname_bufs, key, {
1259    xfree((char *)key);
1260  })
1261  map_destroy(cstr_t, &fname_bufs);
1262  set_destroy(path_t, &oldfiles_set);
1263}
1264
1265/// Default shada file location: cached path
1266static char *default_shada_file = NULL;
1267
1268/// Get the default ShaDa file
1269static const char *shada_get_default_file(void)
1270  FUNC_ATTR_WARN_UNUSED_RESULT
1271{
1272  if (default_shada_file == NULL) {
1273    char *shada_dir = stdpaths_user_state_subpath("shada", 0, false);
1274    default_shada_file = concat_fnames_realloc(shada_dir, "main.shada", true);
1275  }
1276  return default_shada_file;
1277}
1278
1279/// Get the ShaDa file name to use
1280///
1281/// If "file" is given and not empty, use it (has already been expanded by
1282/// cmdline functions). Otherwise use "-i file_name", value from 'shada' or the
1283/// default, and expand environment variables.
1284///
1285/// @param[in]  file  Forced file name or NULL.
1286///
1287/// @return  An allocated string containing shada file name,
1288///          or NULL if shada file should not be used.
1289static char *shada_filename(const char *file)
1290  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT
1291{
1292  if (file == NULL || *file == NUL) {
1293    if (p_shadafile != NULL && *p_shadafile != NUL) {
1294      // Check if writing to ShaDa file was disabled ("-i NONE" or "--clean").
1295      if (!strequal(p_shadafile, "NONE")) {
1296        file = p_shadafile;
1297      } else {
1298        return NULL;
1299      }
1300    } else {
1301      if ((file = find_shada_parameter('n')) == NULL || *file == NUL) {
1302        file = shada_get_default_file();
1303      }
1304      // XXX It used to be one level lower, so that whatever is in
1305      //     `p_shadafile` was expanded. I intentionally moved it here
1306      //     because various expansions must have already be done by the shell.
1307      //     If shell is not performing them then they should be done in main.c
1308      //     where arguments are parsed, *not here*.
1309      size_t len = expand_env((char *)file, &(NameBuff[0]), MAXPATHL);
1310      file = &(NameBuff[0]);
1311      return xmemdupz(file, len);
1312    }
1313  }
1314  return xstrdup(file);
1315}
1316
1317#define KEY_NAME_(s) #s
1318#define PACK_KEY(s) mpack_str(STATIC_CSTR_AS_STRING(KEY_NAME_(s)), &sbuf);
1319#define KEY_NAME(s) KEY_NAME_(s)
1320
1321#define SHADA_MPACK_FREE_SPACE (4 * MPACK_ITEM_SIZE)
1322
1323static void shada_check_buffer(PackerBuffer *packer)
1324{
1325  if (mpack_remaining(packer) < SHADA_MPACK_FREE_SPACE) {
1326    packer->packer_flush(packer);
1327  }
1328}
1329
1330static uint32_t additional_data_len(AdditionalData *src)
1331{
1332  return src ? src->nitems : 0;
1333}
1334
1335static void dump_additional_data(AdditionalData *src, PackerBuffer *sbuf)
1336{
1337  if (src != NULL) {
1338    mpack_raw(src->data, src->nbytes, sbuf);
1339  }
1340}
1341
1342/// Write single ShaDa entry
1343///
1344/// @param[in]  packer     Packer used to write entry.
1345/// @param[in]  entry      Entry written.
1346/// @param[in]  max_kbyte  Maximum size of an item in KiB. Zero means no
1347///                        restrictions.
1348///
1349/// @return kSDWriteSuccessful, kSDWriteFailed or kSDWriteIgnError.
1350static ShaDaWriteResult shada_pack_entry(PackerBuffer *const packer, ShadaEntry entry,
1351                                         const size_t max_kbyte)
1352  FUNC_ATTR_NONNULL_ALL
1353{
1354  ShaDaWriteResult ret = kSDWriteFailed;
1355  PackerBuffer sbuf = packer_string_buffer();
1356
1357#define CHECK_DEFAULT(entry, attr) \
1358  (sd_default_values[(entry).type].data.attr == (entry).data.attr)
1359#define ONE_IF_NOT_DEFAULT(entry, attr) \
1360  ((uint32_t)(!CHECK_DEFAULT(entry, attr)))
1361
1362#define PACK_BOOL(entry, name, attr) \
1363  do { \
1364    if (!CHECK_DEFAULT(entry, search_pattern.attr)) { \
1365      PACK_KEY(name); \
1366      mpack_bool(&sbuf.ptr, !sd_default_values[(entry).type].data.search_pattern.attr); \
1367    } \
1368  } while (0)
1369
1370  shada_check_buffer(&sbuf);
1371  switch (entry.type) {
1372  case kSDItemMissing:
1373    abort();
1374  case kSDItemUnknown:
1375    mpack_raw(entry.data.unknown_item.contents, entry.data.unknown_item.size, &sbuf);
1376    break;
1377  case kSDItemHistoryEntry: {
1378    const bool is_hist_search =
1379      entry.data.history_item.histtype == HIST_SEARCH;
1380    uint32_t arr_size = (2 + (uint32_t)is_hist_search
1381                         + additional_data_len(entry.additional_data));
1382    mpack_array(&sbuf.ptr, arr_size);
1383    mpack_uint(&sbuf.ptr, entry.data.history_item.histtype);
1384    mpack_bin(cstr_as_string(entry.data.history_item.string), &sbuf);
1385    if (is_hist_search) {
1386      mpack_uint(&sbuf.ptr, (uint8_t)entry.data.history_item.sep);
1387    }
1388    dump_additional_data(entry.additional_data, &sbuf);
1389    break;
1390  }
1391  case kSDItemVariable: {
1392    bool is_blob = (entry.data.global_var.value.v_type == VAR_BLOB);
1393    uint32_t arr_size = 2 + (is_blob ? 1 : 0) + additional_data_len(entry.additional_data);
1394    mpack_array(&sbuf.ptr, arr_size);
1395    const String varname = cstr_as_string(entry.data.global_var.name);
1396    mpack_bin(varname, &sbuf);
1397    char vardesc[256] = "variable g:";
1398    memcpy(&vardesc[sizeof("variable g:") - 1], varname.data,
1399           varname.size + 1);
1400    if (encode_vim_to_msgpack(&sbuf, &entry.data.global_var.value, vardesc)
1401        == FAIL) {
1402      ret = kSDWriteIgnError;
1403      semsg(_(WERR "Failed to write variable %s"),
1404            entry.data.global_var.name);
1405      goto shada_pack_entry_error;
1406    }
1407    if (is_blob) {
1408      mpack_check_buffer(&sbuf);
1409      mpack_integer(&sbuf.ptr, VAR_TYPE_BLOB);
1410    }
1411    dump_additional_data(entry.additional_data, &sbuf);
1412    break;
1413  }
1414  case kSDItemSubString: {
1415    uint32_t arr_size = 1 + additional_data_len(entry.additional_data);
1416    mpack_array(&sbuf.ptr, arr_size);
1417    mpack_bin(cstr_as_string(entry.data.sub_string.sub), &sbuf);
1418    dump_additional_data(entry.additional_data, &sbuf);
1419    break;
1420  }
1421  case kSDItemSearchPattern: {
1422    uint32_t entry_map_size = (1  // Search pattern is always present
1423                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.magic)
1424                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.is_last_used)
1425                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.smartcase)
1426                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.has_line_offset)
1427                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.place_cursor_at_end)
1428                               + ONE_IF_NOT_DEFAULT(entry,
1429                                                    search_pattern.is_substitute_pattern)
1430                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.highlighted)
1431                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.offset)
1432                               + ONE_IF_NOT_DEFAULT(entry, search_pattern.search_backward)
1433                               + additional_data_len(entry.additional_data));
1434    mpack_map(&sbuf.ptr, entry_map_size);
1435    PACK_KEY(SEARCH_KEY_PAT);
1436    mpack_bin(entry.data.search_pattern.pat, &sbuf);
1437    PACK_BOOL(entry, SEARCH_KEY_MAGIC, magic);
1438    PACK_BOOL(entry, SEARCH_KEY_IS_LAST_USED, is_last_used);
1439    PACK_BOOL(entry, SEARCH_KEY_SMARTCASE, smartcase);
1440    PACK_BOOL(entry, SEARCH_KEY_HAS_LINE_OFFSET, has_line_offset);
1441    PACK_BOOL(entry, SEARCH_KEY_PLACE_CURSOR_AT_END, place_cursor_at_end);
1442    PACK_BOOL(entry, SEARCH_KEY_IS_SUBSTITUTE_PATTERN, is_substitute_pattern);
1443    PACK_BOOL(entry, SEARCH_KEY_HIGHLIGHTED, highlighted);
1444    PACK_BOOL(entry, SEARCH_KEY_BACKWARD, search_backward);
1445    if (!CHECK_DEFAULT(entry, search_pattern.offset)) {
1446      PACK_KEY(SEARCH_KEY_OFFSET);
1447      mpack_integer(&sbuf.ptr, entry.data.search_pattern.offset);
1448    }
1449#undef PACK_BOOL
1450    dump_additional_data(entry.additional_data, &sbuf);
1451    break;
1452  }
1453  case kSDItemChange:
1454  case kSDItemGlobalMark:
1455  case kSDItemLocalMark:
1456  case kSDItemJump: {
1457    size_t entry_map_size = (1  // File name
1458                             + ONE_IF_NOT_DEFAULT(entry, filemark.mark.lnum)
1459                             + ONE_IF_NOT_DEFAULT(entry, filemark.mark.col)
1460                             + ONE_IF_NOT_DEFAULT(entry, filemark.name)
1461                             + additional_data_len(entry.additional_data));
1462    mpack_map(&sbuf.ptr, (uint32_t)entry_map_size);
1463    PACK_KEY(KEY_FILE);
1464    mpack_bin(cstr_as_string(entry.data.filemark.fname), &sbuf);
1465    if (!CHECK_DEFAULT(entry, filemark.mark.lnum)) {
1466      PACK_KEY(KEY_LNUM);
1467      mpack_integer(&sbuf.ptr, entry.data.filemark.mark.lnum);
1468    }
1469    if (!CHECK_DEFAULT(entry, filemark.mark.col)) {
1470      PACK_KEY(KEY_COL);
1471      mpack_integer(&sbuf.ptr, entry.data.filemark.mark.col);
1472    }
1473    assert(entry.type == kSDItemJump || entry.type == kSDItemChange
1474           ? CHECK_DEFAULT(entry, filemark.name)
1475           : true);
1476    if (!CHECK_DEFAULT(entry, filemark.name)) {
1477      PACK_KEY(KEY_NAME_CHAR);
1478      mpack_uint(&sbuf.ptr, (uint8_t)entry.data.filemark.name);
1479    }
1480    dump_additional_data(entry.additional_data, &sbuf);
1481    break;
1482  }
1483  case kSDItemRegister: {
1484    uint32_t entry_map_size = (2  // Register contents and name
1485                               + ONE_IF_NOT_DEFAULT(entry, reg.type)
1486                               + ONE_IF_NOT_DEFAULT(entry, reg.width)
1487                               + ONE_IF_NOT_DEFAULT(entry, reg.is_unnamed)
1488                               + additional_data_len(entry.additional_data));
1489
1490    mpack_map(&sbuf.ptr, entry_map_size);
1491    PACK_KEY(REG_KEY_CONTENTS);
1492    mpack_array(&sbuf.ptr, (uint32_t)entry.data.reg.contents_size);
1493    for (size_t i = 0; i < entry.data.reg.contents_size; i++) {
1494      mpack_bin(entry.data.reg.contents[i], &sbuf);
1495    }
1496    PACK_KEY(KEY_NAME_CHAR);
1497    mpack_uint(&sbuf.ptr, (uint8_t)entry.data.reg.name);
1498    if (!CHECK_DEFAULT(entry, reg.type)) {
1499      PACK_KEY(REG_KEY_TYPE);
1500      mpack_uint(&sbuf.ptr, (uint8_t)entry.data.reg.type);
1501    }
1502    if (!CHECK_DEFAULT(entry, reg.width)) {
1503      PACK_KEY(REG_KEY_WIDTH);
1504      mpack_uint64(&sbuf.ptr, (uint64_t)entry.data.reg.width);
1505    }
1506    if (!CHECK_DEFAULT(entry, reg.is_unnamed)) {
1507      PACK_KEY(REG_KEY_UNNAMED);
1508      mpack_bool(&sbuf.ptr, entry.data.reg.is_unnamed);
1509    }
1510    dump_additional_data(entry.additional_data, &sbuf);
1511    break;
1512  }
1513  case kSDItemBufferList:
1514    mpack_array(&sbuf.ptr, (uint32_t)entry.data.buffer_list.size);
1515    for (size_t i = 0; i < entry.data.buffer_list.size; i++) {
1516      size_t entry_map_size = (1  // Buffer name
1517                               + (size_t)(entry.data.buffer_list.buffers[i].pos.lnum
1518                                          != default_pos.lnum)
1519                               + (size_t)(entry.data.buffer_list.buffers[i].pos.col
1520                                          != default_pos.col)
1521                               + additional_data_len(entry.data.buffer_list.buffers[i].
1522                                                     additional_data));
1523      mpack_map(&sbuf.ptr, (uint32_t)entry_map_size);
1524      PACK_KEY(KEY_FILE);
1525      mpack_bin(cstr_as_string(entry.data.buffer_list.buffers[i].fname), &sbuf);
1526      if (entry.data.buffer_list.buffers[i].pos.lnum != 1) {
1527        PACK_KEY(KEY_LNUM);
1528        mpack_uint64(&sbuf.ptr, (uint64_t)entry.data.buffer_list.buffers[i].pos.lnum);
1529      }
1530      if (entry.data.buffer_list.buffers[i].pos.col != 0) {
1531        PACK_KEY(KEY_COL);
1532        mpack_uint64(&sbuf.ptr, (uint64_t)entry.data.buffer_list.buffers[i].pos.col);
1533      }
1534      dump_additional_data(entry.data.buffer_list.buffers[i].additional_data, &sbuf);
1535    }
1536    break;
1537  case kSDItemHeader:
1538    mpack_map(&sbuf.ptr, (uint32_t)entry.data.header.size);
1539    for (size_t i = 0; i < entry.data.header.size; i++) {
1540      mpack_str(entry.data.header.items[i].key, &sbuf);
1541      const Object obj = entry.data.header.items[i].value;
1542      switch (obj.type) {
1543      case kObjectTypeString:
1544        mpack_bin(obj.data.string, &sbuf);
1545        break;
1546      case kObjectTypeInteger:
1547        mpack_integer(&sbuf.ptr, obj.data.integer);
1548        break;
1549      default:
1550        abort();
1551      }
1552    }
1553    break;
1554  }
1555#undef CHECK_DEFAULT
1556#undef ONE_IF_NOT_DEFAULT
1557  String packed = packer_take_string(&sbuf);
1558  if (!max_kbyte || packed.size <= max_kbyte * 1024) {
1559    shada_check_buffer(packer);
1560
1561    if (entry.type == kSDItemUnknown) {
1562      mpack_uint64(&packer->ptr, entry.data.unknown_item.type);
1563    } else {
1564      mpack_uint64(&packer->ptr, (uint64_t)entry.type);
1565    }
1566    mpack_uint64(&packer->ptr, (uint64_t)entry.timestamp);
1567    if (packed.size > 0) {
1568      mpack_uint64(&packer->ptr, (uint64_t)packed.size);
1569      mpack_raw(packed.data, packed.size, packer);
1570    }
1571
1572    if (packer->anyint != 0) {  // error code
1573      goto shada_pack_entry_error;
1574    }
1575  }
1576  ret = kSDWriteSuccessful;
1577shada_pack_entry_error:
1578  xfree(sbuf.startptr);
1579  return ret;
1580}
1581
1582/// Write single ShaDa entry and free it afterwards
1583///
1584/// Will not free if entry could not be freed.
1585///
1586/// @param[in]  packer     Packer used to write entry.
1587/// @param[in]  entry      Entry written.
1588/// @param[in]  max_kbyte  Maximum size of an item in KiB. Zero means no
1589///                        restrictions.
1590static inline ShaDaWriteResult shada_pack_pfreed_entry(PackerBuffer *const packer, ShadaEntry entry,
1591                                                       const size_t max_kbyte)
1592  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
1593{
1594  ShaDaWriteResult ret = shada_pack_entry(packer, entry, max_kbyte);
1595  shada_free_shada_entry(&entry);
1596  return ret;
1597}
1598
1599/// Compare two FileMarks structure to order them by greatest_timestamp
1600///
1601/// Order is reversed: structure with greatest greatest_timestamp comes first.
1602/// Function signature is compatible with qsort.
1603static int compare_file_marks(const void *a, const void *b)
1604  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
1605{
1606  const FileMarks *const *const a_fms = a;
1607  const FileMarks *const *const b_fms = b;
1608  return ((*a_fms)->greatest_timestamp == (*b_fms)->greatest_timestamp
1609          ? 0
1610          : ((*a_fms)->greatest_timestamp > (*b_fms)->greatest_timestamp ? -1 : 1));
1611}
1612
1613/// Check the result of parsing one msgpack object from the ShaDa file.
1614///
1615/// @param[in]  initial_fpos  File position where the object started (for error messages).
1616/// @param[in]  status        mpack parser status (MPACK_OK, MPACK_EOF, …).
1617/// @param[in]  remaining     Unparsed bytes left over (must be 0 for a well-formed object).
1618///
1619/// @return kSDReadStatusSuccess, or kSDReadStatusNotShaDa on a parse error.
1620static ShaDaReadResult shada_check_status(uintmax_t initial_fpos, int status, size_t remaining)
1621  FUNC_ATTR_WARN_UNUSED_RESULT
1622{
1623  switch (status) {
1624  case MPACK_OK:
1625    if (remaining) {
1626      semsg(_(RCERR "Failed to parse ShaDa file: extra bytes in msgpack string "
1627              "at position %" PRIu64),
1628            (uint64_t)initial_fpos);
1629      return kSDReadStatusNotShaDa;
1630    }
1631    return kSDReadStatusSuccess;
1632  case MPACK_EOF:
1633    semsg(_(RCERR "Failed to parse ShaDa file: incomplete msgpack string "
1634            "at position %" PRIu64),
1635          (uint64_t)initial_fpos);
1636    return kSDReadStatusNotShaDa;
1637  default:
1638    semsg(_(RCERR "Failed to parse ShaDa file due to a msgpack parser error "
1639            "at position %" PRIu64),
1640          (uint64_t)initial_fpos);
1641    return kSDReadStatusNotShaDa;
1642  }
1643}
1644
1645/// Format shada entry for debugging purposes
1646///
1647/// @param[in]  entry  ShaDa entry to format.
1648///
1649/// @return string representing ShaDa entry in a static buffer.
1650static const char *shada_format_entry(const ShadaEntry entry)
1651  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_UNUSED FUNC_ATTR_NONNULL_RET
1652{
1653  static char ret[1024];
1654  ret[0] = 0;
1655  vim_snprintf(S_LEN(ret), "%s", "[ ] ts=%" PRIu64 " ");
1656  //                         ^ Space for `can_free_entry`
1657#define FORMAT_MARK_ENTRY(entry_name, name_fmt, name_fmt_arg) \
1658  do { \
1659    vim_snprintf_add(S_LEN(ret), \
1660                     entry_name " {" name_fmt " file=[%zu]\"%.512s\", " \
1661                     "pos={l=%" PRIdLINENR ",c=%" PRIdCOLNR ",a=%" PRIdCOLNR "}, " \
1662                     "}", \
1663                     name_fmt_arg, \
1664                     strlen(entry.data.filemark.fname), \
1665                     entry.data.filemark.fname, \
1666                     entry.data.filemark.mark.lnum, \
1667                     entry.data.filemark.mark.col, \
1668                     entry.data.filemark.mark.coladd); \
1669  } while (0)
1670  switch (entry.type) {
1671  case kSDItemMissing:
1672    vim_snprintf_add(S_LEN(ret), "Missing");
1673    break;
1674  case kSDItemHeader:
1675    vim_snprintf_add(S_LEN(ret), "Header { TODO }");
1676    break;
1677  case kSDItemBufferList:
1678    vim_snprintf_add(S_LEN(ret), "BufferList { TODO }");
1679    break;
1680  case kSDItemUnknown:
1681    vim_snprintf_add(S_LEN(ret), "Unknown { TODO }");
1682    break;
1683  case kSDItemSearchPattern:
1684    vim_snprintf_add(S_LEN(ret), "SearchPattern { TODO }");
1685    break;
1686  case kSDItemSubString:
1687    vim_snprintf_add(S_LEN(ret), "SubString { TODO }");
1688    break;
1689  case kSDItemHistoryEntry:
1690    vim_snprintf_add(S_LEN(ret), "HistoryEntry { TODO }");
1691    break;
1692  case kSDItemRegister:
1693    vim_snprintf_add(S_LEN(ret), "Register { TODO }");
1694    break;
1695  case kSDItemVariable:
1696    vim_snprintf_add(S_LEN(ret), "Variable { TODO }");
1697    break;
1698  case kSDItemGlobalMark:
1699    FORMAT_MARK_ENTRY("GlobalMark", " name='%c',", entry.data.filemark.name);
1700    break;
1701  case kSDItemChange:
1702    FORMAT_MARK_ENTRY("Change", "%s", "");
1703    break;
1704  case kSDItemLocalMark:
1705    FORMAT_MARK_ENTRY("LocalMark", " name='%c',", entry.data.filemark.name);
1706    break;
1707  case kSDItemJump:
1708    FORMAT_MARK_ENTRY("Jump", "%s", "");
1709    break;
1710#undef FORMAT_MARK_ENTRY
1711  }
1712  ret[1] = (entry.can_free_entry ? 'T' : 'F');
1713  return ret;
1714}
1715
1716/// Read and merge in ShaDa file, used when writing
1717///
1718/// @param[in]      sd_reader   Structure containing file reader definition.
1719/// @param[in]      srni_flags  Flags determining what to read.
1720/// @param[in]      max_kbyte   Maximum size of one element.
1721/// @param[in,out]  wms         Location where results are saved.
1722/// @param[out]     packer      MessagePack packer for entries which are not
1723///                             merged.
1724static inline ShaDaWriteResult shada_read_when_writing(FileDescriptor *const sd_reader,
1725                                                       const unsigned srni_flags,
1726                                                       const size_t max_kbyte,
1727                                                       WriteMergerState *const wms,
1728                                                       PackerBuffer *const packer)
1729  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1730{
1731  ShaDaWriteResult ret = kSDWriteSuccessful;
1732  ShadaEntry entry;
1733  ShaDaReadResult srni_ret;
1734
1735#define COMPARE_WITH_ENTRY(wms_entry_, entry) \
1736  do { \
1737    ShadaEntry *const wms_entry = (wms_entry_); \
1738    if (wms_entry->type != kSDItemMissing) { \
1739      if (wms_entry->timestamp >= (entry).timestamp) { \
1740        shada_free_shada_entry(&entry); \
1741        break; \
1742      } \
1743      shada_free_shada_entry(wms_entry); \
1744    } \
1745    *wms_entry = entry; \
1746  } while (0)
1747
1748  while ((srni_ret = shada_read_next_item(sd_reader, &entry, srni_flags,
1749                                          max_kbyte))
1750         != kSDReadStatusFinished) {
1751    switch (srni_ret) {
1752    case kSDReadStatusSuccess:
1753      break;
1754    case kSDReadStatusFinished:
1755      // Should be handled by the while condition.
1756      abort();
1757    case kSDReadStatusNotShaDa:
1758      ret = kSDWriteReadNotShada;
1759      FALLTHROUGH;
1760    case kSDReadStatusReadError:
1761      return ret;
1762    case kSDReadStatusMalformed:
1763      continue;
1764    }
1765    switch (entry.type) {
1766    case kSDItemMissing:
1767      break;
1768    case kSDItemHeader:
1769    case kSDItemBufferList:
1770      abort();
1771    case kSDItemUnknown:
1772      ret = shada_pack_entry(packer, entry, 0);
1773      shada_free_shada_entry(&entry);
1774      break;
1775    case kSDItemSearchPattern: {
1776      const bool is_sub = entry.data.search_pattern.is_substitute_pattern;
1777      ShadaEntry *const wms_pat = is_sub ? &wms->sub_search_pattern : &wms->search_pattern;
1778      if (wms_pat->type == kSDItemMissing
1779          && search_pattern_cleared(is_sub)
1780          && get_search_pattern_timestamp(is_sub) >= entry.timestamp) {
1781        shada_free_shada_entry(&entry);
1782        break;
1783      }
1784      COMPARE_WITH_ENTRY(wms_pat, entry);
1785      break;
1786    }
1787    case kSDItemSubString:
1788      COMPARE_WITH_ENTRY(&wms->replacement, entry);
1789      break;
1790    case kSDItemHistoryEntry:
1791      if (entry.data.history_item.histtype >= HIST_COUNT) {
1792        ret = shada_pack_entry(packer, entry, 0);
1793        shada_free_shada_entry(&entry);
1794        break;
1795      }
1796      if (wms->hms[entry.data.history_item.histtype].hmll.size != 0) {
1797        hms_insert(&wms->hms[entry.data.history_item.histtype], entry, true);
1798      } else {
1799        shada_free_shada_entry(&entry);
1800      }
1801      break;
1802    case kSDItemRegister: {
1803      const int idx = op_reg_index(entry.data.reg.name);
1804      if (idx < 0) {
1805        ret = shada_pack_entry(packer, entry, 0);
1806        shada_free_shada_entry(&entry);
1807        break;
1808      }
1809      if (wms->registers[idx].type == kSDItemMissing) {
1810        const yankreg_T *const reg = op_reg_get(entry.data.reg.name);
1811        if (reg != NULL && reg_empty(reg) && reg->timestamp / NS_PER_SEC >= entry.timestamp) {
1812          shada_free_shada_entry(&entry);
1813          break;
1814        }
1815      }
1816      COMPARE_WITH_ENTRY(&wms->registers[idx], entry);
1817      break;
1818    }
1819    case kSDItemVariable:
1820      if (!set_has(cstr_t, &wms->dumped_variables, entry.data.global_var.name)) {
1821        ret = shada_pack_entry(packer, entry, 0);
1822      }
1823      shada_free_shada_entry(&entry);
1824      break;
1825    case kSDItemGlobalMark:
1826      if (ascii_isdigit(entry.data.filemark.name)) {
1827        bool processed_mark = false;
1828        // Completely ignore numbered mark names, make a list sorted by
1829        // timestamp.
1830        for (size_t i = ARRAY_SIZE(wms->numbered_marks); i > 0; i--) {
1831          ShadaEntry wms_entry = wms->numbered_marks[i - 1];
1832          if (wms_entry.type != kSDItemGlobalMark) {
1833            continue;
1834          }
1835          // Ignore duplicates.
1836          if (wms_entry.timestamp == entry.timestamp
1837              && (wms_entry.additional_data == NULL
1838                  && entry.additional_data == NULL)
1839              && marks_equal(wms_entry.data.filemark.mark,
1840                             entry.data.filemark.mark)
1841              && strcmp(wms_entry.data.filemark.fname,
1842                        entry.data.filemark.fname) == 0) {
1843            shada_free_shada_entry(&entry);
1844            processed_mark = true;
1845            break;
1846          }
1847          if (wms_entry.timestamp >= entry.timestamp) {
1848            processed_mark = true;
1849            if (i < ARRAY_SIZE(wms->numbered_marks)) {
1850              replace_numbered_mark(wms, i, entry);
1851            } else {
1852              shada_free_shada_entry(&entry);
1853            }
1854            break;
1855          }
1856        }
1857        if (!processed_mark) {
1858          replace_numbered_mark(wms, 0, entry);
1859        }
1860      } else {
1861        const int idx = mark_global_index(entry.data.filemark.name);
1862        if (idx < 0) {
1863          ret = shada_pack_entry(packer, entry, 0);
1864          shada_free_shada_entry(&entry);
1865          break;
1866        }
1867
1868        // Global or numbered mark.
1869        ShadaEntry *mark = idx < 26 ? &wms->global_marks[idx] : &wms->numbered_marks[idx - 26];
1870
1871        if (mark->type == kSDItemMissing) {
1872          if (namedfm[idx].fmark.timestamp >= entry.timestamp) {
1873            shada_free_shada_entry(&entry);
1874            break;
1875          }
1876        }
1877        COMPARE_WITH_ENTRY(mark, entry);
1878      }
1879      break;
1880    case kSDItemChange:
1881    case kSDItemLocalMark: {
1882      if (shada_removable(entry.data.filemark.fname)) {
1883        shada_free_shada_entry(&entry);
1884        break;
1885      }
1886      const char *const fname = entry.data.filemark.fname;
1887      cstr_t *key = NULL;
1888      bool new_item = false;
1889      ptr_t *val = pmap_put_ref(cstr_t)(&wms->file_marks, fname, &key, &new_item);
1890      if (new_item) {
1891        *key = xstrdup(fname);
1892      }
1893      if (*val == NULL) {
1894        *val = xcalloc(1, sizeof(FileMarks));
1895      }
1896      FileMarks *const filemarks = *val;
1897      if (entry.timestamp > filemarks->greatest_timestamp) {
1898        filemarks->greatest_timestamp = entry.timestamp;
1899      }
1900      if (entry.type == kSDItemLocalMark) {
1901        const int idx = mark_local_index(entry.data.filemark.name);
1902        if (idx < 0) {
1903          filemarks->additional_marks = xrealloc(filemarks->additional_marks,
1904                                                 (++filemarks->additional_marks_size
1905                                                  * sizeof(filemarks->additional_marks[0])));
1906          filemarks->additional_marks[filemarks->additional_marks_size - 1] =
1907            entry;
1908        } else {
1909          ShadaEntry *const wms_entry = &filemarks->marks[idx];
1910          bool set_wms = true;
1911          if (wms_entry->type != kSDItemMissing) {
1912            if (wms_entry->timestamp >= entry.timestamp) {
1913              shada_free_shada_entry(&entry);
1914              break;
1915            }
1916            if (wms_entry->can_free_entry) {
1917              if (*key == wms_entry->data.filemark.fname) {
1918                *key = entry.data.filemark.fname;
1919              }
1920              shada_free_shada_entry(wms_entry);
1921            }
1922          } else {
1923            FOR_ALL_BUFFERS(buf) {
1924              if (buf->b_ffname != NULL
1925                  && path_equal(entry.data.filemark.fname, buf->b_ffname, kPathCmpLiteral)) {
1926                fmark_T fm;
1927                mark_get(buf, curwin, &fm, kMarkBufLocal, (int)entry.data.filemark.name);
1928                if (fm.timestamp >= entry.timestamp) {
1929                  set_wms = false;
1930                  shada_free_shada_entry(&entry);
1931                  break;
1932                }
1933              }
1934            }
1935          }
1936          if (set_wms) {
1937            *wms_entry = entry;
1938          }
1939        }
1940      } else {
1941        int i;
1942        for (i = (int)filemarks->changes_size; i > 0; i--) {
1943          const ShadaEntry jl_entry = filemarks->changes[i - 1];
1944          if (jl_entry.timestamp <= (entry).timestamp) {
1945            if (marks_equal(jl_entry.data.filemark.mark, entry.data.filemark.mark)) {
1946              i = -1;
1947            }
1948            break;
1949          }
1950        }
1951        if (i > 0 && filemarks->changes_size == JUMPLISTSIZE) {
1952          shada_free_shada_entry(&filemarks->changes[0]);
1953        }
1954        i = marklist_insert(filemarks->changes, sizeof(*filemarks->changes),
1955                            (int)filemarks->changes_size, i);
1956        if (i != -1) {
1957          filemarks->changes[i] = entry;
1958          if (filemarks->changes_size < JUMPLISTSIZE) {
1959            filemarks->changes_size++;
1960          }
1961        } else {
1962          shada_free_shada_entry(&(entry));
1963        }
1964      }
1965      break;
1966    }
1967    case kSDItemJump:
1968      ;
1969      int i;
1970      for (i = (int)wms->jumps_size; i > 0; i--) {
1971        const ShadaEntry jl_entry = wms->jumps[i - 1];
1972        if (jl_entry.timestamp <= entry.timestamp) {
1973          if (marks_equal(jl_entry.data.filemark.mark, entry.data.filemark.mark)
1974              && strcmp(jl_entry.data.filemark.fname, entry.data.filemark.fname) == 0) {
1975            i = -1;
1976          }
1977          break;
1978        }
1979      }
1980      if (i > 0 && wms->jumps_size == JUMPLISTSIZE) {
1981        shada_free_shada_entry(&wms->jumps[0]);
1982      }
1983      i = marklist_insert(wms->jumps, sizeof(*wms->jumps), (int)wms->jumps_size, i);
1984      if (i != -1) {
1985        wms->jumps[i] = entry;
1986        if (wms->jumps_size < JUMPLISTSIZE) {
1987          wms->jumps_size++;
1988        }
1989      } else {
1990        shada_free_shada_entry(&entry);
1991      }
1992      break;
1993    }
1994  }
1995#undef COMPARE_WITH_ENTRY
1996  return ret;
1997}
1998
1999/// Check whether buffer should be ignored
2000///
2001/// @param[in]  buf  buf_T* to check.
2002/// @param[in]  removable_bufs  Cache of buffers ignored due to their location.
2003///
2004/// @return true or false.
2005static inline bool ignore_buf(const buf_T *const buf, Set(ptr_t) *const removable_bufs)
2006  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE
2007{
2008  return (buf == NULL || buf->b_ffname == NULL || (!buf->b_p_bl && buf->b_p_initialized)
2009          || bt_quickfix(buf) || bt_terminal(buf) || set_has(ptr_t, removable_bufs, (ptr_t)buf));
2010}
2011
2012/// Get list of buffers to write to the shada file
2013///
2014/// @param[in]  removable_bufs  Buffers which are ignored
2015///
2016/// @return  ShadaEntry  List of buffers to save, kSDItemBufferList entry.
2017static inline ShadaEntry shada_get_buflist(Set(ptr_t) *const removable_bufs)
2018  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE
2019{
2020  int max_bufs = get_shada_parameter('%');
2021  size_t buf_count = 0;
2022  FOR_ALL_BUFFERS(buf) {
2023    if (!ignore_buf(buf, removable_bufs) && buf->b_p_bl
2024        && (max_bufs < 0 || buf_count < (size_t)max_bufs)) {
2025      buf_count++;
2026    }
2027  }
2028
2029  ShadaEntry buflist_entry = (ShadaEntry) {
2030    .type = kSDItemBufferList,
2031    .timestamp = os_time(),
2032    .data = {
2033      .buffer_list = {
2034        .size = buf_count,
2035        .buffers = xmalloc(buf_count
2036                           * sizeof(*buflist_entry.data.buffer_list.buffers)),
2037      },
2038    },
2039  };
2040  size_t i = 0;
2041  FOR_ALL_BUFFERS(buf) {
2042    if (ignore_buf(buf, removable_bufs) || !buf->b_p_bl) {
2043      continue;
2044    }
2045    if (i >= buf_count) {
2046      break;
2047    }
2048    buflist_entry.data.buffer_list.buffers[i] = (struct buffer_list_buffer) {
2049      .pos = buf->b_last_cursor.mark,
2050      .fname = buf->b_ffname,
2051      .additional_data = buf->additional_data,
2052    };
2053    i++;
2054  }
2055
2056  return buflist_entry;
2057}
2058
2059/// Save search pattern to ShadaEntry
2060///
2061/// @param[out]  ret_pse  Location where result will be saved.
2062/// @param[in]  get_pattern  Function used to get pattern.
2063/// @param[in]  is_substitute_pattern  True if pattern in question is substitute
2064///                                    pattern. Also controls whether some
2065///                                    fields should be initialized to default
2066///                                    or values from get_pattern.
2067/// @param[in]  search_last_used  Result of search_was_last_used().
2068/// @param[in]  search_highlighted  True if search pattern was highlighted by
2069///                                 &hlsearch and this information should be
2070///                                 saved.
2071static inline void add_search_pattern(ShadaEntry *const ret_pse,
2072                                      const SearchPatternGetter get_pattern,
2073                                      const bool is_substitute_pattern, const bool search_last_used,
2074                                      const bool search_highlighted)
2075  FUNC_ATTR_ALWAYS_INLINE
2076{
2077  const ShadaEntry defaults = sd_default_values[kSDItemSearchPattern];
2078  SearchPattern pat;
2079  get_pattern(&pat);
2080  if (pat.pat != NULL) {
2081    *ret_pse = (ShadaEntry) {
2082      .can_free_entry = false,
2083      .type = kSDItemSearchPattern,
2084      .timestamp = pat.timestamp,
2085      .data = {
2086        .search_pattern = {
2087          .magic = pat.magic,
2088          .smartcase = !pat.no_scs,
2089          .has_line_offset = (is_substitute_pattern
2090                              ? defaults.data.search_pattern.has_line_offset
2091                              : pat.off.line),
2092          .place_cursor_at_end = (
2093                                  is_substitute_pattern
2094                                  ? defaults.data.search_pattern.place_cursor_at_end
2095                                  : pat.off.end),
2096          .offset = (is_substitute_pattern
2097                     ? defaults.data.search_pattern.offset
2098                     : pat.off.off),
2099          .is_last_used = (is_substitute_pattern ^ search_last_used),
2100          .is_substitute_pattern = is_substitute_pattern,
2101          .highlighted = ((is_substitute_pattern ^ search_last_used)
2102                          && search_highlighted),
2103          .pat = cstr_as_string(pat.pat),
2104          .search_backward = (!is_substitute_pattern && pat.off.dir == '?'),
2105        }
2106      },
2107      .additional_data = pat.additional_data,
2108    };
2109  }
2110}
2111
2112/// Initialize registers for writing to the ShaDa file
2113///
2114/// @param[in]  wms  The WriteMergerState used when writing.
2115/// @param[in]  max_reg_lines  The maximum number of register lines.
2116/// @param scale_ts  Downscale the timestamp to seconds (shada legacy).
2117static inline void shada_initialize_registers(WriteMergerState *const wms, int max_reg_lines,
2118                                              bool scale_ts)
2119  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
2120{
2121  const void *reg_iter = NULL;
2122  const bool limit_reg_lines = max_reg_lines >= 0;
2123  do {
2124    yankreg_T reg;
2125    char name = NUL;
2126    bool is_unnamed = false;
2127    reg_iter = op_global_reg_iter(reg_iter, &name, &reg, &is_unnamed);
2128    if (name == NUL) {
2129      break;
2130    }
2131    if (limit_reg_lines && reg.y_size > (size_t)max_reg_lines) {
2132      continue;
2133    }
2134    wms->registers[op_reg_index(name)] = (ShadaEntry) {
2135      .can_free_entry = false,
2136      .type = kSDItemRegister,
2137      .timestamp = scale_ts ? reg.timestamp / NS_PER_SEC : reg.timestamp,
2138      .data = {
2139        .reg = {
2140          .contents = reg.y_array,
2141          .contents_size = reg.y_size,
2142          .type = reg.y_type,
2143          .width = (size_t)(reg.y_type == kMTBlockWise ? reg.y_width : 0),
2144          .name = name,
2145          .is_unnamed = is_unnamed,
2146        }
2147      },
2148      .additional_data = reg.additional_data,
2149    };
2150  } while (reg_iter != NULL);
2151}
2152
2153/// Replace numbered mark in WriteMergerState
2154///
2155/// Frees the last mark, moves (including adjusting mark names) marks from idx
2156/// to the last-but-one one and saves the new mark at given index.
2157///
2158/// @param[out]  wms  Merger state to adjust.
2159/// @param[in]  idx  Index at which new mark should be placed.
2160/// @param[in]  entry  New mark.
2161static inline void replace_numbered_mark(WriteMergerState *const wms, const size_t idx,
2162                                         const ShadaEntry entry)
2163  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
2164{
2165  shada_free_shada_entry(&ARRAY_LAST_ENTRY(wms->numbered_marks));
2166  for (size_t i = idx; i < ARRAY_SIZE(wms->numbered_marks) - 1; i++) {
2167    if (wms->numbered_marks[i].type == kSDItemGlobalMark) {
2168      wms->numbered_marks[i].data.filemark.name = (char)('0' + (int)i + 1);
2169    }
2170  }
2171  memmove(wms->numbered_marks + idx + 1, wms->numbered_marks + idx,
2172          sizeof(wms->numbered_marks[0])
2173          * (ARRAY_SIZE(wms->numbered_marks) - 1 - idx));
2174  wms->numbered_marks[idx] = entry;
2175  wms->numbered_marks[idx].data.filemark.name = (char)('0' + (int)idx);
2176}
2177
2178/// Find buffers ignored due to their location.
2179///
2180/// @param[out]  removable_bufs  Cache of buffers ignored due to their location.
2181static inline void find_removable_bufs(Set(ptr_t) *removable_bufs)
2182{
2183  FOR_ALL_BUFFERS(buf) {
2184    if (buf->b_ffname != NULL && shada_removable(buf->b_ffname)) {
2185      set_put(ptr_t, removable_bufs, (ptr_t)buf);
2186    }
2187  }
2188}
2189
2190/// Translate a history type number to the associated character
2191static int hist_type2char(const int type)
2192  FUNC_ATTR_CONST
2193{
2194  switch (type) {
2195  case HIST_CMD:
2196    return ':';
2197  case HIST_SEARCH:
2198    return '/';
2199  case HIST_EXPR:
2200    return '=';
2201  case HIST_INPUT:
2202    return '@';
2203  case HIST_DEBUG:
2204    return '>';
2205  default:
2206    abort();
2207  }
2208  return NUL;
2209}
2210
2211static PackerBuffer packer_buffer_for_file(FileDescriptor *file)
2212{
2213  if (file_space(file) < SHADA_MPACK_FREE_SPACE) {
2214    file_flush(file);
2215  }
2216  return (PackerBuffer) {
2217    .startptr = file->buffer,
2218    .ptr = file->write_pos,
2219    .endptr = file->buffer + ARENA_BLOCK_SIZE,
2220    .anydata = file,
2221    .anyint = 0,  // set to nonzero if error
2222    .packer_flush = flush_file_buffer,
2223  };
2224}
2225
2226static void flush_file_buffer(PackerBuffer *buffer)
2227{
2228  FileDescriptor *fd = buffer->anydata;
2229  fd->write_pos = buffer->ptr;
2230  buffer->anyint = file_flush(fd);
2231  buffer->ptr = fd->write_pos;
2232}
2233
2234/// Write ShaDa file
2235///
2236/// @param[in]  sd_writer  Structure containing file writer definition.
2237/// @param[in]  sd_reader  Structure containing file reader definition. If it is
2238///                        not NULL then contents of this file will be merged
2239///                        with current Neovim runtime.
2240static ShaDaWriteResult shada_write(FileDescriptor *const sd_writer,
2241                                    FileDescriptor *const sd_reader)
2242  FUNC_ATTR_NONNULL_ARG(1)
2243{
2244  ShaDaWriteResult ret = kSDWriteSuccessful;
2245  int max_kbyte_i = get_shada_parameter('s');
2246  if (max_kbyte_i < 0) {
2247    max_kbyte_i = 10;
2248  }
2249  if (max_kbyte_i == 0) {
2250    return ret;
2251  }
2252
2253  WriteMergerState *const wms = xcalloc(1, sizeof(*wms));
2254  bool dump_one_history[HIST_COUNT];
2255  const bool dump_global_vars = (find_shada_parameter('!') != NULL);
2256  int max_reg_lines = get_shada_parameter('<');
2257  if (max_reg_lines < 0) {
2258    max_reg_lines = get_shada_parameter('"');
2259  }
2260  const bool dump_registers = (max_reg_lines != 0);
2261  Set(ptr_t) removable_bufs = SET_INIT;
2262  const size_t max_kbyte = (size_t)max_kbyte_i;
2263  const size_t num_marked_files = (size_t)get_shada_parameter('\'');
2264  const bool dump_global_marks = get_shada_parameter('f') != 0;
2265  bool dump_history = false;
2266
2267  // Initialize history merger
2268  for (int i = 0; i < HIST_COUNT; i++) {
2269    int num_saved = get_shada_parameter(hist_type2char(i));
2270    if (num_saved == -1) {
2271      num_saved = (int)p_hi;
2272    }
2273    if (num_saved > 0) {
2274      dump_history = true;
2275      dump_one_history[i] = true;
2276      hms_init(&wms->hms[i], (uint8_t)i, (size_t)num_saved, sd_reader != NULL, false);
2277    } else {
2278      dump_one_history[i] = false;
2279    }
2280  }
2281
2282  const unsigned srni_flags = (unsigned)(kSDReadUndisableableData
2283                                         | kSDReadUnknown
2284                                         | (dump_history ? kSDReadHistory : 0)
2285                                         | (dump_registers ? kSDReadRegisters : 0)
2286                                         | (dump_global_vars ? kSDReadVariables : 0)
2287                                         | (dump_global_marks ? kSDReadGlobalMarks : 0)
2288                                         | (num_marked_files ? kSDReadLocalMarks |
2289                                            kSDReadChanges : 0));
2290
2291  PackerBuffer packer = packer_buffer_for_file(sd_writer);
2292
2293  // Set b_last_cursor for all the buffers that have a window.
2294  //
2295  // It is needed to correctly save '"' mark on exit. Has a side effect of
2296  // setting '"' mark in all windows on :wshada to the current cursor
2297  // position (basically what :wviminfo used to do).
2298  FOR_ALL_TAB_WINDOWS(tp, wp) {
2299    set_last_cursor(wp);
2300  }
2301
2302  find_removable_bufs(&removable_bufs);
2303
2304  // Write header
2305  if (shada_pack_entry(&packer, (ShadaEntry) {
2306    .type = kSDItemHeader,
2307    .timestamp = os_time(),
2308    .data = {
2309      .header = {
2310        .size = 5,
2311        .capacity = 5,
2312        .items = ((KeyValuePair[]) {
2313          { STATIC_CSTR_AS_STRING("generator"),
2314            STATIC_CSTR_AS_OBJ("nvim") },
2315          { STATIC_CSTR_AS_STRING("version"),
2316            CSTR_AS_OBJ(longVersion) },
2317          { STATIC_CSTR_AS_STRING("max_kbyte"),
2318            INTEGER_OBJ((Integer)max_kbyte) },
2319          { STATIC_CSTR_AS_STRING("pid"),
2320            INTEGER_OBJ((Integer)os_get_pid()) },
2321          { STATIC_CSTR_AS_STRING("encoding"),
2322            CSTR_AS_OBJ(p_enc) },
2323        }),
2324      }
2325    }
2326  }, 0) == kSDWriteFailed) {
2327    ret = kSDWriteFailed;
2328    goto shada_write_exit;
2329  }
2330
2331  // Write buffer list
2332  if (find_shada_parameter('%') != NULL) {
2333    ShadaEntry buflist_entry = shada_get_buflist(&removable_bufs);
2334    if (shada_pack_entry(&packer, buflist_entry, 0) == kSDWriteFailed) {
2335      xfree(buflist_entry.data.buffer_list.buffers);
2336      ret = kSDWriteFailed;
2337      goto shada_write_exit;
2338    }
2339    xfree(buflist_entry.data.buffer_list.buffers);
2340  }
2341
2342  // Write some of the variables
2343  if (dump_global_vars) {
2344    const void *var_iter = NULL;
2345    const Timestamp cur_timestamp = os_time();
2346    do {
2347      typval_T vartv;
2348      const char *name = NULL;
2349      var_iter = var_shada_iter(var_iter, &name, &vartv, VAR_FLAVOUR_SHADA);
2350      if (name == NULL) {
2351        break;
2352      }
2353      switch (vartv.v_type) {
2354      case VAR_FUNC:
2355      case VAR_PARTIAL:
2356        tv_clear(&vartv);
2357        continue;
2358      case VAR_DICT: {
2359        dict_T *di = vartv.vval.v_dict;
2360        int copyID = get_copyID();
2361        if (!set_ref_in_ht(&di->dv_hashtab, copyID, NULL)
2362            && copyID == di->dv_copyID) {
2363          tv_clear(&vartv);
2364          continue;
2365        }
2366        break;
2367      }
2368      case VAR_LIST: {
2369        list_T *l = vartv.vval.v_list;
2370        int copyID = get_copyID();
2371        if (!set_ref_in_list_items(l, copyID, NULL)
2372            && copyID == l->lv_copyID) {
2373          tv_clear(&vartv);
2374          continue;
2375        }
2376        break;
2377      }
2378      default:
2379        break;
2380      }
2381      typval_T tgttv;
2382      tv_copy(&vartv, &tgttv);
2383      ShaDaWriteResult spe_ret;
2384      if ((spe_ret = shada_pack_entry(&packer, (ShadaEntry) {
2385        .type = kSDItemVariable,
2386        .timestamp = cur_timestamp,
2387        .data = {
2388          .global_var = {
2389            .name = (char *)name,
2390            .value = tgttv,
2391          }
2392        },
2393        .additional_data = NULL,
2394      }, max_kbyte)) == kSDWriteFailed) {
2395        tv_clear(&vartv);
2396        tv_clear(&tgttv);
2397        ret = kSDWriteFailed;
2398        goto shada_write_exit;
2399      }
2400      tv_clear(&vartv);
2401      tv_clear(&tgttv);
2402      if (spe_ret == kSDWriteSuccessful) {
2403        set_put(cstr_t, &wms->dumped_variables, name);
2404      }
2405    } while (var_iter != NULL);
2406  }
2407
2408  if (num_marked_files > 0) {  // Skip if '0 in 'shada'
2409    // Initialize jump list
2410    wms->jumps_size = shada_init_jumps(wms->jumps, &removable_bufs);
2411  }
2412
2413  if (dump_one_history[HIST_SEARCH] > 0) {  // Skip if /0 in 'shada'
2414    const bool search_highlighted = !(Search.no_hlsearch
2415                                      || find_shada_parameter('h') != NULL);
2416    const bool search_last_used = search_was_last_used();
2417
2418    // Initialize search pattern
2419    add_search_pattern(&wms->search_pattern, &get_search_pattern, false,
2420                       search_last_used, search_highlighted);
2421
2422    // Initialize substitute search pattern
2423    add_search_pattern(&wms->sub_search_pattern, &get_substitute_pattern, true,
2424                       search_last_used, search_highlighted);
2425
2426    // Initialize substitute replacement string
2427    SubReplacementString sub;
2428    sub_get_replacement(&sub);
2429    if (sub.sub != NULL) {  // Don't store empty replacement string
2430      wms->replacement = (ShadaEntry) {
2431        .can_free_entry = false,
2432        .type = kSDItemSubString,
2433        .timestamp = sub.timestamp,
2434        .data = {
2435          .sub_string = {
2436            .sub = sub.sub,
2437          }
2438        },
2439        .additional_data = sub.additional_data,
2440      };
2441    }
2442  }
2443
2444  // Initialize global marks
2445  if (dump_global_marks) {
2446    const void *global_mark_iter = NULL;
2447    size_t digit_mark_idx = 0;
2448    do {
2449      char name = NUL;
2450      xfmark_T fm;
2451      global_mark_iter = mark_global_iter(global_mark_iter, &name, &fm);
2452      if (name == NUL) {
2453        break;
2454      }
2455      const char *fname;
2456      if (fm.fmark.fnum == 0) {
2457        assert(fm.fname != NULL);
2458        if (shada_removable(fm.fname)) {
2459          continue;
2460        }
2461        fname = fm.fname;
2462      } else {
2463        const buf_T *const buf = buflist_findnr(fm.fmark.fnum);
2464        if (buf == NULL || buf->b_ffname == NULL
2465            || set_has(ptr_t, &removable_bufs, (ptr_t)buf)) {
2466          continue;
2467        }
2468        fname = buf->b_ffname;
2469      }
2470      const ShadaEntry entry = {
2471        .can_free_entry = false,
2472        .type = kSDItemGlobalMark,
2473        .timestamp = fm.fmark.timestamp,
2474        .data = {
2475          .filemark = {
2476            .mark = fm.fmark.mark,
2477            .name = name,
2478            .fname = (char *)fname,
2479          }
2480        },
2481        .additional_data = fm.fmark.additional_data,
2482      };
2483      if (ascii_isdigit(name)) {
2484        replace_numbered_mark(wms, digit_mark_idx++, entry);
2485      } else {
2486        wms->global_marks[mark_global_index(name)] = entry;
2487      }
2488    } while (global_mark_iter != NULL);
2489  }
2490
2491  // Initialize registers
2492  if (dump_registers) {
2493    shada_initialize_registers(wms, max_reg_lines, true);
2494  }
2495
2496  // Initialize buffers
2497  if (num_marked_files > 0) {
2498    FOR_ALL_BUFFERS(buf) {
2499      if (ignore_buf(buf, &removable_bufs)) {
2500        continue;
2501      }
2502      const void *local_marks_iter = NULL;
2503      const char *const fname = buf->b_ffname;
2504      cstr_t *map_key = NULL;
2505      bool new_item = false;
2506      ptr_t *val = pmap_put_ref(cstr_t)(&wms->file_marks, fname, &map_key, &new_item);
2507      if (new_item) {
2508        *map_key = xstrdup(fname);
2509      }
2510      if (*val == NULL) {
2511        *val = xcalloc(1, sizeof(FileMarks));
2512      }
2513      FileMarks *const filemarks = *val;
2514      do {
2515        fmark_T fm;
2516        char name = NUL;
2517        local_marks_iter = mark_buffer_iter(local_marks_iter, buf, &name, &fm);
2518        if (name == NUL) {
2519          break;
2520        }
2521        filemarks->marks[mark_local_index(name)] = (ShadaEntry) {
2522          .can_free_entry = false,
2523          .type = kSDItemLocalMark,
2524          .timestamp = fm.timestamp,
2525          .data = {
2526            .filemark = {
2527              .mark = fm.mark,
2528              .name = name,
2529              .fname = (char *)fname,
2530            }
2531          },
2532          .additional_data = fm.additional_data,
2533        };
2534        if (fm.timestamp > filemarks->greatest_timestamp) {
2535          filemarks->greatest_timestamp = fm.timestamp;
2536        }
2537      } while (local_marks_iter != NULL);
2538      for (int i = 0; i < buf->b_changelistlen; i++) {
2539        const fmark_T fm = buf->b_changelist[i];
2540        filemarks->changes[i] = (ShadaEntry) {
2541          .can_free_entry = false,
2542          .type = kSDItemChange,
2543          .timestamp = fm.timestamp,
2544          .data = {
2545            .filemark = {
2546              .mark = fm.mark,
2547              .fname = (char *)fname,
2548            }
2549          },
2550          .additional_data = fm.additional_data,
2551        };
2552        if (fm.timestamp > filemarks->greatest_timestamp) {
2553          filemarks->greatest_timestamp = fm.timestamp;
2554        }
2555      }
2556      filemarks->changes_size = (size_t)buf->b_changelistlen;
2557    }
2558  }
2559
2560  if (sd_reader != NULL) {
2561    const ShaDaWriteResult srww_ret = shada_read_when_writing(sd_reader, srni_flags, max_kbyte, wms,
2562                                                              &packer);
2563    if (srww_ret != kSDWriteSuccessful) {
2564      ret = srww_ret;
2565    }
2566  }
2567
2568  // Update numbered marks: replace '0 mark with the current position,
2569  // remove '9 and shift all other marks. Skip if f0 in 'shada'.
2570  if (dump_global_marks && !ignore_buf(curbuf, &removable_bufs) && curwin->w_cursor.lnum != 0) {
2571    replace_numbered_mark(wms, 0, (ShadaEntry) {
2572      .can_free_entry = false,
2573      .type = kSDItemGlobalMark,
2574      .timestamp = os_time(),
2575      .data = {
2576        .filemark = {
2577          .mark = curwin->w_cursor,
2578          .name = '0',
2579          .fname = curbuf->b_ffname,
2580        }
2581      },
2582      .additional_data = NULL,
2583    });
2584  }
2585
2586  // Write the rest
2587#define PACK_WMS_ARRAY(wms_array) \
2588  do { \
2589    for (size_t i_ = 0; i_ < ARRAY_SIZE(wms_array); i_++) { \
2590      if ((wms_array)[i_].type != kSDItemMissing) { \
2591        if (shada_pack_pfreed_entry(&packer, (wms_array)[i_], max_kbyte) \
2592            == kSDWriteFailed) { \
2593          ret = kSDWriteFailed; \
2594          goto shada_write_exit; \
2595        } \
2596      } \
2597    } \
2598  } while (0)
2599  PACK_WMS_ARRAY(wms->global_marks);
2600  PACK_WMS_ARRAY(wms->numbered_marks);
2601  PACK_WMS_ARRAY(wms->registers);
2602  for (size_t i = 0; i < wms->jumps_size; i++) {
2603    if (shada_pack_pfreed_entry(&packer, wms->jumps[i], max_kbyte)
2604        == kSDWriteFailed) {
2605      ret = kSDWriteFailed;
2606      goto shada_write_exit;
2607    }
2608  }
2609#define PACK_WMS_ENTRY(wms_entry) \
2610  do { \
2611    if ((wms_entry).type != kSDItemMissing) { \
2612      if (shada_pack_pfreed_entry(&packer, wms_entry, max_kbyte) \
2613          == kSDWriteFailed) { \
2614        ret = kSDWriteFailed; \
2615        goto shada_write_exit; \
2616      } \
2617    } \
2618  } while (0)
2619  PACK_WMS_ENTRY(wms->search_pattern);
2620  PACK_WMS_ENTRY(wms->sub_search_pattern);
2621  PACK_WMS_ENTRY(wms->replacement);
2622#undef PACK_WMS_ENTRY
2623
2624  const size_t file_markss_size = map_size(&wms->file_marks);
2625  FileMarks **const all_file_markss =
2626    xmalloc(file_markss_size * sizeof(*all_file_markss));
2627  FileMarks **cur_file_marks = all_file_markss;
2628  ptr_t val;
2629  map_foreach_value(&wms->file_marks, val, {
2630    *cur_file_marks++ = val;
2631  })
2632  qsort((void *)all_file_markss, file_markss_size, sizeof(*all_file_markss),
2633        &compare_file_marks);
2634  const size_t file_markss_to_dump = MIN(num_marked_files, file_markss_size);
2635  for (size_t i = 0; i < file_markss_to_dump; i++) {
2636    PACK_WMS_ARRAY(all_file_markss[i]->marks);
2637    for (size_t j = 0; j < all_file_markss[i]->changes_size; j++) {
2638      if (shada_pack_pfreed_entry(&packer, all_file_markss[i]->changes[j],
2639                                  max_kbyte) == kSDWriteFailed) {
2640        ret = kSDWriteFailed;
2641        goto shada_write_exit;
2642      }
2643    }
2644    for (size_t j = 0; j < all_file_markss[i]->additional_marks_size; j++) {
2645      if (shada_pack_entry(&packer, all_file_markss[i]->additional_marks[j],
2646                           0) == kSDWriteFailed) {
2647        shada_free_shada_entry(&all_file_markss[i]->additional_marks[j]);
2648        ret = kSDWriteFailed;
2649        goto shada_write_exit;
2650      }
2651      shada_free_shada_entry(&all_file_markss[i]->additional_marks[j]);
2652    }
2653    xfree(all_file_markss[i]->additional_marks);
2654  }
2655  xfree(all_file_markss);
2656#undef PACK_WMS_ARRAY
2657
2658  if (dump_history) {
2659    for (int i = 0; i < HIST_COUNT; i++) {
2660      if (dump_one_history[i]) {
2661        hms_insert_whole_neovim_history(&wms->hms[i]);
2662        HMS_ITER(&wms->hms[i], cur_entry, {
2663          if (shada_pack_pfreed_entry(&packer, cur_entry->data, max_kbyte) == kSDWriteFailed) {
2664            ret = kSDWriteFailed;
2665            break;
2666          }
2667        })
2668        if (ret == kSDWriteFailed) {
2669          goto shada_write_exit;
2670        }
2671      }
2672    }
2673  }
2674
2675shada_write_exit:
2676  for (int i = 0; i < HIST_COUNT; i++) {
2677    if (dump_one_history[i]) {
2678      hms_dealloc(&wms->hms[i]);
2679    }
2680  }
2681  const char *stored_key = NULL;
2682  map_foreach(&wms->file_marks, stored_key, val, {
2683    xfree((char *)stored_key);
2684    xfree(val);
2685  })
2686  map_destroy(cstr_t, &wms->file_marks);
2687  set_destroy(ptr_t, &removable_bufs);
2688  packer.packer_flush(&packer);
2689  set_destroy(cstr_t, &wms->dumped_variables);
2690  xfree(wms);
2691  return ret;
2692}
2693
2694#undef PACK_KEY
2695
2696/// Write ShaDa file to a given location
2697///
2698/// @param[in]  file     File to write to. If it is NULL or empty then default
2699///                      location is used.
2700/// @param[in]  nomerge  If true then old file is ignored.
2701///
2702/// @return OK if writing was successful, FAIL otherwise.
2703int shada_write_file(const char *const file, bool nomerge)
2704{
2705  char *const fname = shada_filename(file);
2706  if (fname == NULL) {
2707    return FAIL;
2708  }
2709
2710  char *tempname = NULL;
2711  FileDescriptor sd_writer;
2712  FileDescriptor sd_reader;
2713  bool did_open_writer = false;
2714  bool did_open_reader = false;
2715
2716  if (!nomerge) {
2717    int error;
2718    if ((error = file_open(&sd_reader, fname, kFileReadOnly, 0)) != 0) {
2719      if (error != UV_ENOENT) {
2720        semsg(_(SERR "System error while opening ShaDa file %s for reading "
2721                "to merge before writing it: %s"),
2722              fname, os_strerror(error));
2723        // Try writing the file even if opening it emerged any issues besides
2724        // file not existing: maybe writing will succeed nevertheless.
2725      }
2726      nomerge = true;
2727      goto shada_write_file_nomerge;
2728    } else {
2729      did_open_reader = true;
2730    }
2731    tempname = modname(fname, ".tmp.a", false);
2732    if (tempname == NULL) {
2733      nomerge = true;
2734      goto shada_write_file_nomerge;
2735    }
2736
2737    // Save permissions from the original file, with modifications:
2738    int perm = (int)os_getperm(fname);
2739    perm = (perm >= 0) ? ((perm & 0777) | 0600) : 0600;
2740    //                 ^3         ^1       ^2      ^2,3
2741    // 1: Strip SUID bit if any.
2742    // 2: Make sure that user can always read and write the result.
2743    // 3: If somebody happened to delete the file after it was opened for
2744    //    reading use u=rw permissions.
2745shada_write_file_open: {}
2746    error = file_open(&sd_writer, tempname, kFileCreateOnly|kFileNoSymlink, perm);
2747    if (error) {
2748      if (error == UV_EEXIST || error == UV_ELOOP) {
2749        // File already exists, try another name
2750        char *const wp = tempname + strlen(tempname) - 1;
2751        if (*wp == 'z') {
2752          // Tried names from .tmp.a to .tmp.z, all failed. Something must be
2753          // wrong then.
2754          semsg(_("E138: All %s.tmp.X files exist, cannot write ShaDa file!"),
2755                fname);
2756          xfree(fname);
2757          xfree(tempname);
2758          if (did_open_reader) {
2759            close_file(&sd_reader);
2760          }
2761          return FAIL;
2762        }
2763        (*wp)++;
2764        goto shada_write_file_open;
2765      } else {
2766        semsg(_(SERR "System error while opening temporary ShaDa file %s "
2767                "for writing: %s"), tempname, os_strerror(error));
2768      }
2769    } else {
2770      did_open_writer = true;
2771    }
2772  }
2773  if (nomerge) {
2774shada_write_file_nomerge: {}
2775    char *const tail = path_tail_with_sep(fname);
2776    if (tail != fname) {
2777      const char tail_save = *tail;
2778      *tail = NUL;
2779      if (!os_isdir(fname)) {
2780        int ret;
2781        char *failed_dir;
2782        if ((ret = os_mkdir_recurse(fname, 0700, &failed_dir, NULL)) != 0) {
2783          semsg(_(SERR "Failed to create directory %s "
2784                  "for writing ShaDa file: %s"),
2785                failed_dir, os_strerror(ret));
2786          xfree(fname);
2787          xfree(failed_dir);
2788          return FAIL;
2789        }
2790      }
2791      *tail = tail_save;
2792    }
2793    int error = file_open(&sd_writer, fname, kFileCreate|kFileTruncate, 0600);
2794    if (error) {
2795      semsg(_(SERR "System error while opening ShaDa file %s for writing: %s"),
2796            fname, os_strerror(error));
2797    } else {
2798      did_open_writer = true;
2799    }
2800  }
2801
2802  if (!did_open_writer) {
2803    xfree(fname);
2804    xfree(tempname);
2805    if (did_open_reader) {
2806      close_file(&sd_reader);
2807    }
2808    return FAIL;
2809  }
2810
2811  if (p_verbose > 1) {
2812    verbose_enter();
2813    smsg(0, _("Writing ShaDa file \"%s\""), fname);
2814    verbose_leave();
2815  }
2816
2817  const ShaDaWriteResult sw_ret = shada_write(&sd_writer, (nomerge ? NULL : &sd_reader));
2818  assert(sw_ret != kSDWriteIgnError);
2819  if (!nomerge) {
2820    if (did_open_reader) {
2821      close_file(&sd_reader);
2822    }
2823    bool did_remove = false;
2824    if (sw_ret == kSDWriteSuccessful) {
2825      FileInfo old_info;
2826      if (!os_fileinfo(fname, &old_info)
2827          || S_ISDIR(old_info.stat.st_mode)
2828#ifdef UNIX
2829          // For Unix we check the owner of the file.  It's not very nice
2830          // to overwrite a user's viminfo file after a "su root", with a
2831          // viminfo file that the user can't read.
2832          || (getuid() != ROOT_UID
2833              && !(old_info.stat.st_uid == getuid()
2834                   ? (old_info.stat.st_mode & 0200)
2835                   : (old_info.stat.st_gid == getgid()
2836                      ? (old_info.stat.st_mode & 0020)
2837                      : (old_info.stat.st_mode & 0002))))
2838#endif
2839          ) {
2840        semsg(_("E137: ShaDa file is not writable: %s"), fname);
2841        goto shada_write_file_did_not_remove;
2842      }
2843#ifdef UNIX
2844      if (getuid() == ROOT_UID) {
2845        if (old_info.stat.st_uid != ROOT_UID
2846            || old_info.stat.st_gid != getgid()) {
2847          const uv_uid_t old_uid = (uv_uid_t)old_info.stat.st_uid;
2848          const uv_gid_t old_gid = (uv_gid_t)old_info.stat.st_gid;
2849          const int fchown_ret = os_fchown(file_fd(&sd_writer),
2850                                           old_uid, old_gid);
2851          if (fchown_ret != 0) {
2852            semsg(_(RNERR "Failed setting uid and gid for file %s: %s"),
2853                  tempname, os_strerror(fchown_ret));
2854            goto shada_write_file_did_not_remove;
2855          }
2856        }
2857      }
2858#endif
2859      if (vim_rename(tempname, fname) == -1) {
2860        semsg(_(RNERR "Can't rename ShaDa file from %s to %s!"),
2861              tempname, fname);
2862      } else {
2863        did_remove = true;
2864        os_remove(tempname);
2865      }
2866    } else {
2867      if (sw_ret == kSDWriteReadNotShada) {
2868        semsg(_(RNERR "Did not rename %s because %s "
2869                "does not look like a ShaDa file"), tempname, fname);
2870      } else {
2871        semsg(_(RNERR "Did not rename %s to %s because there were errors "
2872                "during writing it"), tempname, fname);
2873      }
2874    }
2875    if (!did_remove) {
2876shada_write_file_did_not_remove:
2877      semsg(_(RNERR "Do not forget to remove %s or rename it manually to %s."),
2878            tempname, fname);
2879    }
2880    xfree(tempname);
2881  }
2882  close_file(&sd_writer);
2883
2884  xfree(fname);
2885  return OK;
2886}
2887
2888/// Read marks information from ShaDa file
2889///
2890/// @return OK in case of success, FAIL otherwise.
2891int shada_read_marks(void)
2892{
2893  return shada_read_file(NULL, kShaDaWantMarks);
2894}
2895
2896/// Read all information from ShaDa file
2897///
2898/// @param[in]  fname    File to write to. If it is NULL or empty then default
2899/// @param[in]  forceit  If true, use forced reading (prioritize file contents
2900///                      over current Neovim state).
2901/// @param[in]  missing_ok  If true, do not error out when file is missing.
2902///
2903/// @return OK in case of success, FAIL otherwise.
2904int shada_read_everything(const char *const fname, const bool forceit, const bool missing_ok)
2905{
2906  return shada_read_file(fname,
2907                         kShaDaWantInfo|kShaDaWantMarks|kShaDaGetOldfiles
2908                         |(forceit ? kShaDaForceit : 0)
2909                         |(missing_ok ? 0 : kShaDaMissingError));
2910}
2911
2912static void shada_free_shada_entry(ShadaEntry *const entry)
2913{
2914  if (entry == NULL || !entry->can_free_entry) {
2915    return;
2916  }
2917  switch (entry->type) {
2918  case kSDItemMissing:
2919    break;
2920  case kSDItemUnknown:
2921    xfree(entry->data.unknown_item.contents);
2922    break;
2923  case kSDItemHeader:
2924    api_free_dict(entry->data.header);
2925    break;
2926  case kSDItemChange:
2927  case kSDItemJump:
2928  case kSDItemGlobalMark:
2929  case kSDItemLocalMark:
2930    xfree(entry->data.filemark.fname);
2931    break;
2932  case kSDItemSearchPattern:
2933    api_free_string(entry->data.search_pattern.pat);
2934    break;
2935  case kSDItemRegister:
2936    for (size_t i = 0; i < entry->data.reg.contents_size; i++) {
2937      api_free_string(entry->data.reg.contents[i]);
2938    }
2939    xfree(entry->data.reg.contents);
2940    break;
2941  case kSDItemHistoryEntry:
2942    xfree(entry->data.history_item.string);
2943    break;
2944  case kSDItemVariable:
2945    xfree(entry->data.global_var.name);
2946    tv_clear(&entry->data.global_var.value);
2947    break;
2948  case kSDItemSubString:
2949    xfree(entry->data.sub_string.sub);
2950    break;
2951  case kSDItemBufferList:
2952    for (size_t i = 0; i < entry->data.buffer_list.size; i++) {
2953      xfree(entry->data.buffer_list.buffers[i].fname);
2954      xfree(entry->data.buffer_list.buffers[i].additional_data);
2955    }
2956    xfree(entry->data.buffer_list.buffers);
2957    break;
2958  }
2959  XFREE_CLEAR(entry->additional_data);
2960}
2961
2962#ifndef HAVE_BE64TOH
2963static inline uint64_t vim_be64toh(uint64_t big_endian_64_bits)
2964{
2965# ifdef ORDER_BIG_ENDIAN
2966  return big_endian_64_bits;
2967# else
2968  // It may appear that when !defined(ORDER_BIG_ENDIAN) actual order is big
2969  // endian. This variant is suboptimal, but it works regardless of actual
2970  // order.
2971  uint8_t *buf = (uint8_t *)&big_endian_64_bits;
2972  uint64_t ret = 0;
2973  for (size_t i = 8; i; i--) {
2974    ret |= ((uint64_t)buf[i - 1]) << ((8 - i) * 8);
2975  }
2976  return ret;
2977# endif
2978}
2979# define be64toh vim_be64toh
2980#endif
2981
2982/// Read given number of bytes into given buffer, display error if needed
2983///
2984/// @param[in]   sd_reader  Structure containing file reader definition.
2985/// @param[out]  buffer     Where to save the results.
2986/// @param[in]   length     How many bytes should be read.
2987///
2988/// @return kSDReadStatusSuccess if everything was OK, kSDReadStatusNotShaDa if
2989///         there were not enough bytes to read or kSDReadStatusReadError if
2990///         there was some error while reading.
2991static ShaDaReadResult fread_len(FileDescriptor *const sd_reader, char *const buffer,
2992                                 const size_t length)
2993  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
2994{
2995  const ptrdiff_t read_bytes = file_read(sd_reader, buffer, length);
2996  if (read_bytes < 0) {
2997    semsg(_(SERR "System error while reading ShaDa file: %s"),
2998          os_strerror((int)read_bytes));
2999    return kSDReadStatusReadError;
3000  }
3001
3002  if (read_bytes != (ptrdiff_t)length) {
3003    semsg(_(RCERR "Error while reading ShaDa file: "
3004            "last entry specified that it occupies %" PRIu64 " bytes, "
3005            "but file ended earlier"),
3006          (uint64_t)length);
3007    return kSDReadStatusNotShaDa;
3008  }
3009  return kSDReadStatusSuccess;
3010}
3011
3012/// Read next unsigned integer from file
3013///
3014/// Errors out if the result is not an unsigned integer.
3015///
3016/// Unlike msgpack own function this one works with `FILE *` and reads *exactly*
3017/// as much bytes as needed, making it possible to avoid both maintaining own
3018/// buffer and calling `fseek`.
3019///
3020/// One byte from file stream is always consumed, even if it is not correct.
3021///
3022/// @param[in]   sd_reader  Structure containing file reader definition.
3023/// @param[out]  result     Location where result is saved.
3024///
3025/// @return kSDReadStatusSuccess if reading was successful,
3026///         kSDReadStatusNotShaDa if there were not enough bytes to read or
3027///         kSDReadStatusReadError if reading failed for whatever reason.
3028///         kSDReadStatusFinished if eof and that was allowed
3029static ShaDaReadResult msgpack_read_uint64(FileDescriptor *const sd_reader, bool allow_eof,
3030                                           uint64_t *const result)
3031  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
3032{
3033  const uintmax_t fpos = sd_reader->bytes_read;
3034
3035  uint8_t ret;
3036  ptrdiff_t read_bytes = file_read(sd_reader, (char *)&ret, 1);
3037
3038  if (read_bytes < 0) {
3039    semsg(_(SERR "System error while reading integer from ShaDa file: %s"),
3040          os_strerror((int)read_bytes));
3041    return kSDReadStatusReadError;
3042  } else if (read_bytes == 0) {
3043    if (allow_eof && file_eof(sd_reader)) {
3044      return kSDReadStatusFinished;
3045    }
3046    semsg(_(RCERR "Error while reading ShaDa file: "
3047            "expected positive integer at position %" PRIu64
3048            ", but got nothing"),
3049          (uint64_t)fpos);
3050    return kSDReadStatusNotShaDa;
3051  }
3052
3053  int first_char = (int)ret;
3054  if (~first_char & 0x80) {
3055    // Positive fixnum
3056    *result = (uint64_t)((uint8_t)first_char);
3057  } else {
3058    size_t length = 0;
3059    switch (first_char) {
3060    case 0xCC:    // uint8
3061      length = 1;
3062      break;
3063    case 0xCD:    // uint16
3064      length = 2;
3065      break;
3066    case 0xCE:    // uint32
3067      length = 4;
3068      break;
3069    case 0xCF:    // uint64
3070      length = 8;
3071      break;
3072    default:
3073      semsg(_(RCERR "Error while reading ShaDa file: "
3074              "expected positive integer at position %" PRIu64),
3075            (uint64_t)fpos);
3076      return kSDReadStatusNotShaDa;
3077    }
3078    uint64_t buf = 0;
3079    char *buf_u8 = (char *)&buf;
3080    ShaDaReadResult fl_ret;
3081    if ((fl_ret = fread_len(sd_reader, &(buf_u8[sizeof(buf) - length]), length))
3082        != kSDReadStatusSuccess) {
3083      return fl_ret;
3084    }
3085    *result = be64toh(buf);
3086  }
3087  return kSDReadStatusSuccess;
3088}
3089
3090#define READERR(entry_name, error_desc) \
3091  RERR "Error while reading ShaDa file: " \
3092  entry_name " entry at position %" PRIu64 " " \
3093  error_desc
3094
3095/// Iterate over shada file contents
3096///
3097/// @param[in]   sd_reader  Structure containing file reader definition.
3098/// @param[out]  entry      Address where next entry contents will be saved.
3099/// @param[in]   flags      Flags, determining whether and which items should be
3100///                         skipped (see SRNIFlags enum).
3101/// @param[in]   max_kbyte  If non-zero, skip reading entries which have length
3102///                         greater then given.
3103///
3104/// @return Any value from ShaDaReadResult enum.
3105static ShaDaReadResult shada_read_next_item(FileDescriptor *const sd_reader,
3106                                            ShadaEntry *const entry, const unsigned flags,
3107                                            const size_t max_kbyte)
3108  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
3109{
3110  ShaDaReadResult ret = kSDReadStatusMalformed;
3111shada_read_next_item_start:
3112  // Set entry type to kSDItemMissing and also make sure that all pointers in
3113  // data union are NULL so they are safe to xfree(). This is needed in case
3114  // somebody calls goto shada_read_next_item_error before anything is set in
3115  // the switch.
3116  CLEAR_POINTER(entry);
3117  if (file_eof(sd_reader)) {
3118    return kSDReadStatusFinished;
3119  }
3120
3121  bool verify_but_ignore = false;
3122
3123  // First: manually unpack type, timestamp and length.
3124  // This is needed to avoid both seeking and having to maintain a buffer.
3125  uint64_t type_u64 = (uint64_t)kSDItemMissing;
3126  uint64_t timestamp_u64;
3127  uint64_t length_u64;
3128
3129  const uint64_t initial_fpos = sd_reader->bytes_read;
3130  AdditionalDataBuilder ad = KV_INITIAL_VALUE;
3131  uint32_t read_additional_array_elements = 0;
3132  char *error_alloc = NULL;
3133
3134  ShaDaReadResult mru_ret;
3135  if (((mru_ret = msgpack_read_uint64(sd_reader, true, &type_u64))
3136       != kSDReadStatusSuccess)
3137      || ((mru_ret = msgpack_read_uint64(sd_reader, false,
3138                                         &timestamp_u64))
3139          != kSDReadStatusSuccess)
3140      || ((mru_ret = msgpack_read_uint64(sd_reader, false,
3141                                         &length_u64))
3142          != kSDReadStatusSuccess)) {
3143    return mru_ret;
3144  }
3145
3146  if (length_u64 > PTRDIFF_MAX) {
3147    semsg(_(RCERR "Error while reading ShaDa file: "
3148            "there is an item at position %" PRIu64 " "
3149            "that is stated to be too long"),
3150          initial_fpos);
3151    return kSDReadStatusNotShaDa;
3152  }
3153
3154  const size_t length = (size_t)length_u64;
3155  entry->timestamp = (Timestamp)timestamp_u64;
3156  entry->can_free_entry = true;  // all allocations are owned by the entry
3157
3158  if (type_u64 == 0) {
3159    // kSDItemUnknown cannot possibly pass that far because it is -1 and that
3160    // will fail in msgpack_read_uint64. But kSDItemMissing may and it will
3161    // otherwise be skipped because (1 << 0) will never appear in flags.
3162    semsg(_(RCERR "Error while reading ShaDa file: "
3163            "there is an item at position %" PRIu64 " "
3164            "that must not be there: Missing items are "
3165            "for internal uses only"),
3166          initial_fpos);
3167    return kSDReadStatusNotShaDa;
3168  }
3169
3170  if ((type_u64 > SHADA_LAST_ENTRY
3171       ? !(flags & kSDReadUnknown)
3172       : !((unsigned)(1 << type_u64) & flags))
3173      || (max_kbyte && length > max_kbyte * 1024)) {
3174    // First entry is unknown or equal to "\n" (10)? Most likely this means that
3175    // current file is not a ShaDa file because first item should normally be
3176    // a header (excluding tests where first item is tested item). Check this by
3177    // parsing entry contents: in non-ShaDa files this will most likely result
3178    // in incomplete MessagePack string.
3179    if (initial_fpos == 0
3180        && (type_u64 == '\n' || type_u64 > SHADA_LAST_ENTRY)) {
3181      verify_but_ignore = true;
3182    } else {
3183      const ShaDaReadResult srs_ret = sd_reader_skip(sd_reader, length);
3184      if (srs_ret != kSDReadStatusSuccess) {
3185        return srs_ret;
3186      }
3187      goto shada_read_next_item_start;
3188    }
3189  }
3190
3191  const uint64_t parse_pos = sd_reader->bytes_read;
3192  bool buf_allocated = false;
3193  // try to avoid allocation for small items which fits entirely
3194  // in the internal buffer of sd_reader
3195  char *buf = file_try_read_buffered(sd_reader, length);
3196  if (!buf) {
3197    buf_allocated = true;
3198    buf = xmalloc(length);
3199    const ShaDaReadResult fl_ret = fread_len(sd_reader, buf, length);
3200    if (fl_ret != kSDReadStatusSuccess) {
3201      ret = fl_ret;
3202      goto shada_read_next_item_error;
3203    }
3204  }
3205
3206  const char *read_ptr = buf;
3207  size_t read_size = length;
3208
3209  if (verify_but_ignore) {
3210    int status = unpack_skip(&read_ptr, &read_size);
3211    ShaDaReadResult spm_ret = shada_check_status(parse_pos, status, read_size);
3212    if (buf_allocated) {
3213      xfree(buf);
3214    }
3215    if (spm_ret != kSDReadStatusSuccess) {
3216      return spm_ret;
3217    }
3218    goto shada_read_next_item_start;
3219  }
3220
3221  if (type_u64 > SHADA_LAST_ENTRY) {
3222    entry->type = kSDItemUnknown;
3223    entry->data.unknown_item.size = length;
3224    entry->data.unknown_item.type = type_u64;
3225    if (initial_fpos == 0) {
3226      int status = unpack_skip(&read_ptr, &read_size);
3227      ShaDaReadResult spm_ret = shada_check_status(parse_pos, status, read_size);
3228      if (spm_ret != kSDReadStatusSuccess) {
3229        if (buf_allocated) {
3230          xfree(buf);
3231        }
3232        entry->type = kSDItemMissing;
3233        return spm_ret;
3234      }
3235    }
3236    entry->data.unknown_item.contents = buf_allocated ? buf : xmemdup(buf, length);
3237    return kSDReadStatusSuccess;
3238  }
3239
3240  entry->data = sd_default_values[type_u64].data;
3241  switch ((ShadaEntryType)type_u64) {
3242  case kSDItemHeader:
3243    // TODO(bfredl): header is written to file and provides useful debugging
3244    // info. It is never read by nvim (earlier we parsed it back to a
3245    // Dict, but that value was never used)
3246    break;
3247  case kSDItemSearchPattern: {
3248    Dict(_shada_search_pat) *it = &entry->data.search_pattern;
3249    if (!unpack_keydict(it, DictHash(_shada_search_pat), &ad, &read_ptr, &read_size,
3250                        &error_alloc)) {
3251      semsg(_(READERR("search pattern", "%s")), initial_fpos, error_alloc);
3252      it->pat = NULL_STRING;
3253      goto shada_read_next_item_error;
3254    }
3255
3256    if (!HAS_KEY(it, _shada_search_pat, sp)) {  // SEARCH_KEY_PAT
3257      semsg(_(READERR("search pattern", "has no pattern")), initial_fpos);
3258      goto shada_read_next_item_error;
3259    }
3260    entry->data.search_pattern.pat = copy_string(entry->data.search_pattern.pat, NULL);
3261
3262    break;
3263  }
3264  case kSDItemChange:
3265  case kSDItemJump:
3266  case kSDItemGlobalMark:
3267  case kSDItemLocalMark: {
3268    Dict(_shada_mark) it = { 0 };
3269    if (!unpack_keydict(&it, DictHash(_shada_mark), &ad, &read_ptr, &read_size, &error_alloc)) {
3270      semsg(_(READERR("mark", "%s")), initial_fpos, error_alloc);
3271      goto shada_read_next_item_error;
3272    }
3273
3274    if (HAS_KEY(&it, _shada_mark, n)) {
3275      if (type_u64 == kSDItemJump || type_u64 == kSDItemChange) {
3276        semsg(_(READERR("mark", "has n key which is only valid for "
3277                        "local and global mark entries")), initial_fpos);
3278        goto shada_read_next_item_error;
3279      }
3280      entry->data.filemark.name = (char)it.n;
3281    }
3282
3283    if (HAS_KEY(&it, _shada_mark, l)) {
3284      entry->data.filemark.mark.lnum = (linenr_T)it.l;
3285    }
3286    if (HAS_KEY(&it, _shada_mark, c)) {
3287      entry->data.filemark.mark.col = (colnr_T)it.c;
3288    }
3289    if (HAS_KEY(&it, _shada_mark, f)) {
3290      entry->data.filemark.fname = xmemdupz(it.f.data, it.f.size);
3291      TO_SLASH(entry->data.filemark.fname);
3292    }
3293
3294    if (entry->data.filemark.fname == NULL) {
3295      semsg(_(READERR("mark", "is missing file name")), initial_fpos);
3296      goto shada_read_next_item_error;
3297    }
3298    if (entry->data.filemark.mark.lnum <= 0) {
3299      semsg(_(READERR("mark", "has invalid line number")), initial_fpos);
3300      goto shada_read_next_item_error;
3301    }
3302    if (entry->data.filemark.mark.col < 0) {
3303      semsg(_(READERR("mark", "has invalid column number")), initial_fpos);
3304      goto shada_read_next_item_error;
3305    }
3306    break;
3307  }
3308  case kSDItemRegister: {
3309    Dict(_shada_register) it = { 0 };
3310    if (!unpack_keydict(&it, DictHash(_shada_register), &ad, &read_ptr, &read_size, &error_alloc)) {
3311      semsg(_(READERR("register", "%s")), initial_fpos, error_alloc);
3312      kv_destroy(it.rc);
3313      goto shada_read_next_item_error;
3314    }
3315    if (it.rc.size == 0) {
3316      semsg(_(READERR("register",
3317                      "has " KEY_NAME(REG_KEY_CONTENTS) " key with missing or empty array")),
3318            initial_fpos);
3319      goto shada_read_next_item_error;
3320    }
3321    entry->data.reg.contents_size = it.rc.size;
3322    entry->data.reg.contents = xmalloc(it.rc.size * sizeof(String));
3323    for (size_t j = 0; j < it.rc.size; j++) {
3324      entry->data.reg.contents[j] = copy_string(it.rc.items[j], NULL);
3325    }
3326    kv_destroy(it.rc);
3327
3328#define REGISTER_VAL(name, loc, type) \
3329  if (HAS_KEY(&it, _shada_register, name)) { \
3330    loc = (type)it.name; \
3331  }
3332    REGISTER_VAL(REG_KEY_UNNAMED, entry->data.reg.is_unnamed, bool)
3333    REGISTER_VAL(REG_KEY_TYPE, entry->data.reg.type, uint8_t)
3334    REGISTER_VAL(KEY_NAME_CHAR, entry->data.reg.name, char)
3335    REGISTER_VAL(REG_KEY_WIDTH, entry->data.reg.width, size_t)
3336    break;
3337  }
3338  case kSDItemHistoryEntry: {
3339    ssize_t len = unpack_array(&read_ptr, &read_size);
3340
3341    if (len < 2) {
3342      semsg(_(READERR("history", "is not an array with enough elements")), initial_fpos);
3343      goto shada_read_next_item_error;
3344    }
3345    Integer hist_type;
3346    if (!unpack_integer(&read_ptr, &read_size, &hist_type)) {
3347      semsg(_(READERR("history", "has wrong history type type")), initial_fpos);
3348      goto shada_read_next_item_error;
3349    }
3350    const String item = unpack_string(&read_ptr, &read_size);
3351    if (!item.data) {
3352      semsg(_(READERR("history", "has wrong history string type")), initial_fpos);
3353      goto shada_read_next_item_error;
3354    }
3355    if (memchr(item.data, 0, item.size) != NULL) {
3356      semsg(_(READERR("history", "contains string with zero byte inside")), initial_fpos);
3357      goto shada_read_next_item_error;
3358    }
3359    entry->data.history_item.histtype = (uint8_t)hist_type;
3360    const bool is_hist_search = entry->data.history_item.histtype == HIST_SEARCH;
3361    if (is_hist_search) {
3362      if (len < 3) {
3363        semsg(_(READERR("search history",
3364                        "does not have separator character")), initial_fpos);
3365        goto shada_read_next_item_error;
3366      }
3367      Integer sep_type;
3368      if (!unpack_integer(&read_ptr, &read_size, &sep_type)) {
3369        semsg(_(READERR("search history", "has wrong history separator type")), initial_fpos);
3370        goto shada_read_next_item_error;
3371      }
3372      entry->data.history_item.sep = (char)sep_type;
3373    }
3374    size_t strsize = (item.size
3375                      + 1  // Zero byte
3376                      + 1);  // Separator character
3377    entry->data.history_item.string = xmalloc(strsize);
3378    memcpy(entry->data.history_item.string, item.data, item.size);
3379    entry->data.history_item.string[strsize - 2] = 0;
3380    entry->data.history_item.string[strsize - 1] = entry->data.history_item.sep;
3381    read_additional_array_elements = (uint32_t)(len - (2 + is_hist_search));
3382    break;
3383  }
3384  case kSDItemVariable: {
3385    ssize_t len = unpack_array(&read_ptr, &read_size);
3386
3387    if (len < 2) {
3388      semsg(_(READERR("variable", "is not an array with enough elements")), initial_fpos);
3389      goto shada_read_next_item_error;
3390    }
3391
3392    String name = unpack_string(&read_ptr, &read_size);
3393
3394    if (!name.data) {
3395      semsg(_(READERR("variable", "has wrong variable name type")), initial_fpos);
3396      goto shada_read_next_item_error;
3397    }
3398    entry->data.global_var.name = xmemdupz(name.data, name.size);
3399
3400    String binval = unpack_string(&read_ptr, &read_size);
3401
3402    bool is_blob = false;
3403    if (binval.data) {
3404      if (len > 2) {
3405        // A msgpack BIN could be a String or Blob; an additional VAR_TYPE_BLOB
3406        // element is stored with Blobs which can be used to differentiate them
3407        Integer type;
3408        if (!unpack_integer(&read_ptr, &read_size, &type) || type != VAR_TYPE_BLOB) {
3409          semsg(_(READERR("variable", "has wrong variable type")),
3410                initial_fpos);
3411          goto shada_read_next_item_error;
3412        }
3413        is_blob = true;
3414      }
3415      entry->data.global_var.value = decode_string(binval.data, binval.size, is_blob, false);
3416    } else {
3417      int status = unpack_typval(&read_ptr, &read_size, &entry->data.global_var.value);
3418      if (status != MPACK_OK) {
3419        semsg(_(READERR("variable", "has value that cannot "
3420                        "be converted to the Vimscript value")), initial_fpos);
3421        goto shada_read_next_item_error;
3422      }
3423    }
3424    read_additional_array_elements = (uint32_t)(len - 2 - (is_blob ? 1 : 0));
3425    break;
3426  }
3427  case kSDItemSubString: {
3428    ssize_t len = unpack_array(&read_ptr, &read_size);
3429
3430    if (len < 1) {
3431      semsg(_(READERR("sub string", "is not an array with enough elements")), initial_fpos);
3432      goto shada_read_next_item_error;
3433    }
3434
3435    String sub = unpack_string(&read_ptr, &read_size);
3436    if (!sub.data) {
3437      semsg(_(READERR("sub string", "has wrong sub string type")), initial_fpos);
3438      goto shada_read_next_item_error;
3439    }
3440    entry->data.sub_string.sub = xmemdupz(sub.data, sub.size);
3441    read_additional_array_elements = (uint32_t)(len - 1);
3442    break;
3443  }
3444  case kSDItemBufferList: {
3445    ssize_t len = unpack_array(&read_ptr, &read_size);
3446    if (len < 0) {
3447      semsg(_(READERR("buffer list", "is not an array")), initial_fpos);
3448      goto shada_read_next_item_error;
3449    }
3450    if (len == 0) {
3451      break;
3452    }
3453    entry->data.buffer_list.buffers = xcalloc((size_t)len,
3454                                              sizeof(*entry->data.buffer_list.buffers));
3455    for (size_t i = 0; i < (size_t)len; i++) {
3456      entry->data.buffer_list.size++;
3457      Dict(_shada_buflist_item) it = { 0 };
3458      AdditionalDataBuilder it_ad = KV_INITIAL_VALUE;
3459      if (!unpack_keydict(&it, DictHash(_shada_buflist_item), &it_ad, &read_ptr, &read_size,
3460                          &error_alloc)) {
3461        semsg(_(RERR "Error while reading ShaDa file: "
3462                "buffer list at position %" PRIu64 " contains entry that %s"),
3463              initial_fpos, error_alloc);
3464        kv_destroy(it_ad);
3465        goto shada_read_next_item_error;
3466      }
3467      struct buffer_list_buffer *e = &entry->data.buffer_list.buffers[i];
3468      e->additional_data = (AdditionalData *)it_ad.items;
3469      e->pos = default_pos;
3470      if (HAS_KEY(&it, _shada_buflist_item, l)) {
3471        e->pos.lnum = (linenr_T)it.l;
3472      }
3473      if (HAS_KEY(&it, _shada_buflist_item, c)) {
3474        e->pos.col = (colnr_T)it.c;
3475      }
3476      if (HAS_KEY(&it, _shada_buflist_item, f)) {
3477        e->fname = xmemdupz(it.f.data, it.f.size);
3478        TO_SLASH(e->fname);
3479      }
3480
3481      if (e->pos.lnum <= 0) {
3482        semsg(_(RERR "Error while reading ShaDa file: "
3483                "buffer list at position %" PRIu64 " "
3484                "contains entry with invalid line number"),
3485              initial_fpos);
3486        goto shada_read_next_item_error;
3487      }
3488      if (e->pos.col < 0) {
3489        semsg(_(RERR "Error while reading ShaDa file: "
3490                "buffer list at position %" PRIu64 " "
3491                "contains entry with invalid column number"),
3492              initial_fpos);
3493        goto shada_read_next_item_error;
3494      }
3495      if (e->fname == NULL) {
3496        semsg(_(RERR "Error while reading ShaDa file: "
3497                "buffer list at position %" PRIu64 " "
3498                "contains entry that does not have a file name"),
3499              initial_fpos);
3500        goto shada_read_next_item_error;
3501      }
3502    }
3503    break;
3504  }
3505  case kSDItemMissing:
3506  case kSDItemUnknown:
3507    abort();
3508  }
3509
3510  for (uint32_t i = 0; i < read_additional_array_elements; i++) {
3511    const char *item_start = read_ptr;
3512    int status = unpack_skip(&read_ptr, &read_size);
3513    if (status) {
3514      goto shada_read_next_item_error;
3515    }
3516
3517    push_additional_data(&ad, item_start, (size_t)(read_ptr - item_start));
3518  }
3519
3520  if (read_size) {
3521    semsg(_(READERR("item", "additional bytes")), initial_fpos);
3522    goto shada_read_next_item_error;
3523  }
3524
3525  entry->type = (ShadaEntryType)type_u64;
3526  entry->additional_data = (AdditionalData *)ad.items;
3527  ret = kSDReadStatusSuccess;
3528shada_read_next_item_end:
3529  if (buf_allocated) {
3530    xfree(buf);
3531  }
3532  return ret;
3533shada_read_next_item_error:
3534  entry->type = (ShadaEntryType)type_u64;
3535  shada_free_shada_entry(entry);
3536  entry->type = kSDItemMissing;
3537  xfree(error_alloc);
3538  kv_destroy(ad);
3539  goto shada_read_next_item_end;
3540}
3541
3542/// Check whether "name" is on removable media (according to 'shada')
3543///
3544/// @param[in]  name  Checked name.
3545///
3546/// @return True if it is, false otherwise.
3547static bool shada_removable(const char *name)
3548  FUNC_ATTR_WARN_UNUSED_RESULT
3549{
3550  char part[MAXPATHL + 1];
3551  bool retval = false;
3552
3553  char *new_name = home_replace_save(NULL, name);
3554  for (char *p = p_shada; *p;) {
3555    copy_option_part(&p, part, ARRAY_SIZE(part), ", ");
3556    if (part[0] == 'r') {
3557      size_t n = home_replace(NULL, part + 1, NameBuff, MAXPATHL, true);
3558      if (mb_strnicmp(NameBuff, new_name, n) == 0) {
3559        retval = true;
3560        break;
3561      }
3562    }
3563  }
3564  xfree(new_name);
3565  return retval;
3566}
3567
3568/// Initialize ShaDa jumplist entries.
3569///
3570/// @param[in,out]  jumps           Array of ShaDa entries to set.
3571/// @param[in]      removable_bufs  Cache of buffers ignored due to their
3572///                                 location.
3573///
3574/// @return number of jumplist entries
3575static inline size_t shada_init_jumps(ShadaEntry *jumps, Set(ptr_t) *const removable_bufs)
3576{
3577  // Initialize jump list
3578  size_t jumps_size = 0;
3579  const void *jump_iter = NULL;
3580  setpcmark();
3581  cleanup_jumplist(curwin, false);
3582  do {
3583    xfmark_T fm;
3584    jump_iter = mark_jumplist_iter(jump_iter, curwin, &fm);
3585
3586    if (fm.fmark.mark.lnum == 0) {
3587      siemsg("ShaDa: mark lnum zero (ji:%p, js:%p, len:%i)",
3588             (void *)jump_iter, (void *)&curwin->w_jumplist[0],
3589             curwin->w_jumplistlen);
3590      continue;
3591    }
3592    const buf_T *const buf = (fm.fmark.fnum == 0 ? NULL : buflist_findnr(fm.fmark.fnum));
3593    if (buf != NULL ? ignore_buf(buf, removable_bufs) : fm.fmark.fnum != 0) {
3594      continue;
3595    }
3596    const char *const fname =
3597      (fm.fmark.fnum == 0 ? (fm.fname == NULL ? NULL : fm.fname) : buf ? buf->b_ffname : NULL);
3598    if (fname == NULL) {
3599      continue;
3600    }
3601    jumps[jumps_size++] = (ShadaEntry) {
3602      .can_free_entry = false,
3603      .type = kSDItemJump,
3604      .timestamp = fm.fmark.timestamp,
3605      .data = {
3606        .filemark = {
3607          .name = NUL,
3608          .mark = fm.fmark.mark,
3609          .fname = (char *)fname,
3610        }
3611      },
3612      .additional_data = fm.fmark.additional_data,
3613    };
3614  } while (jump_iter != NULL);
3615  return jumps_size;
3616}
3617
3618/// Gets registers as a msgpack-encoded string, in shada format.
3619///
3620/// @param scale_ts  Downscale the timestamp to seconds (shada legacy).
3621/// @param since     Only registers modified => this time (0: all). Nanoseconds, unless `scale_ts`.
3622String shada_encode_regs(bool scale_ts, Timestamp since)
3623  FUNC_ATTR_NONNULL_ALL
3624{
3625  WriteMergerState *const wms = xcalloc(1, sizeof(*wms));
3626  shada_initialize_registers(wms, -1, scale_ts);
3627  PackerBuffer packer = packer_string_buffer();
3628  for (size_t i = 0; i < ARRAY_SIZE(wms->registers); i++) {
3629    if (wms->registers[i].type == kSDItemRegister && wms->registers[i].timestamp >= since) {
3630      if (kSDWriteFailed
3631          == shada_pack_pfreed_entry(&packer, wms->registers[i], 0)) {
3632        abort();
3633      }
3634    }
3635  }
3636  xfree(wms);
3637  return packer_take_string(&packer);
3638}
3639
3640/// Gets the jumplist as a msgpack-encoded string, in shada format.
3641String shada_encode_jumps(void)
3642  FUNC_ATTR_NONNULL_ALL
3643{
3644  Set(ptr_t) removable_bufs = SET_INIT;
3645  find_removable_bufs(&removable_bufs);
3646  ShadaEntry jumps[JUMPLISTSIZE];
3647  size_t jumps_size = shada_init_jumps(jumps, &removable_bufs);
3648  PackerBuffer packer = packer_string_buffer();
3649  for (size_t i = 0; i < jumps_size; i++) {
3650    if (kSDWriteFailed == shada_pack_pfreed_entry(&packer, jumps[i], 0)) {
3651      abort();
3652    }
3653  }
3654  return packer_take_string(&packer);
3655}
3656
3657/// Gets the buffer-list as a msgpack-encoded string, in shada format.
3658String shada_encode_buflist(void)
3659  FUNC_ATTR_NONNULL_ALL
3660{
3661  Set(ptr_t) removable_bufs = SET_INIT;
3662  find_removable_bufs(&removable_bufs);
3663  ShadaEntry buflist_entry = shada_get_buflist(&removable_bufs);
3664
3665  PackerBuffer packer = packer_string_buffer();
3666  if (kSDWriteFailed == shada_pack_entry(&packer, buflist_entry, 0)) {
3667    abort();
3668  }
3669  xfree(buflist_entry.data.buffer_list.buffers);
3670  return packer_take_string(&packer);
3671}
3672
3673/// Gets global Vimscript variables as a msgpack-encoded string, in shada format.
3674String shada_encode_gvars(void)
3675  FUNC_ATTR_NONNULL_ALL
3676{
3677  PackerBuffer packer = packer_string_buffer();
3678  const void *var_iter = NULL;
3679  const Timestamp cur_timestamp = os_time();
3680  do {
3681    typval_T vartv;
3682    const char *name = NULL;
3683    var_iter = var_shada_iter(var_iter, &name, &vartv,
3684                              VAR_FLAVOUR_DEFAULT | VAR_FLAVOUR_SESSION | VAR_FLAVOUR_SHADA);
3685    if (name == NULL) {
3686      break;
3687    }
3688    if (vartv.v_type != VAR_FUNC && vartv.v_type != VAR_PARTIAL) {
3689      typval_T tgttv;
3690      tv_copy(&vartv, &tgttv);
3691      ShaDaWriteResult r = shada_pack_entry(&packer, (ShadaEntry) {
3692        .type = kSDItemVariable,
3693        .timestamp = cur_timestamp,
3694        .data = {
3695          .global_var = {
3696            .name = (char *)name,
3697            .value = tgttv,
3698          }
3699        },
3700        .additional_data = NULL,
3701      }, 0);
3702      if (kSDWriteFailed == r) {
3703        abort();
3704      }
3705      tv_clear(&tgttv);
3706    }
3707    tv_clear(&vartv);
3708  } while (var_iter != NULL);
3709  return packer_take_string(&packer);
3710}
3711
3712/// Read ShaDa from String.
3713///
3714/// @param[in]  string   string to read from.
3715/// @param[in]  flags  Flags, see ShaDaReadFileFlags enum.
3716void shada_read_string(String string, const int flags)
3717  FUNC_ATTR_NONNULL_ALL
3718{
3719  if (string.size == 0) {
3720    return;
3721  }
3722  FileDescriptor sd_reader;
3723  file_open_buffer(&sd_reader, string.data, string.size);
3724  shada_read(&sd_reader, flags);
3725  close_file(&sd_reader);
3726}
3727
3728/// Find the parameter represented by the given character (eg ', :, ", or /),
3729/// and return its associated value in the 'shada' string.
3730/// Only works for number parameters, not for 'r' or 'n'.
3731/// If the parameter is not specified in the string or there is no following
3732/// number, return -1.
3733int get_shada_parameter(int type)
3734{
3735  char *p = find_shada_parameter(type);
3736  if (p != NULL && ascii_isdigit(*p)) {
3737    return atoi(p);
3738  }
3739  return -1;
3740}
3741
3742/// Find the parameter represented by the given character (eg ''', ':', '"', or
3743/// '/') in the 'shada' option and return a pointer to the string after it.
3744/// Return NULL if the parameter is not specified in the string.
3745char *find_shada_parameter(int type)
3746{
3747  for (char *p = p_shada; *p; p++) {
3748    if (*p == type) {
3749      return p + 1;
3750    }
3751    if (*p == 'n') {                // 'n' is always the last one
3752      break;
3753    }
3754    p = vim_strchr(p, ',');         // skip until next ','
3755    if (p == NULL) {                // hit the end without finding parameter
3756      break;
3757    }
3758  }
3759  return NULL;
3760}
3761
3762/// Read marks for the current buffer from the ShaDa file, when we support
3763/// buffer marks and the buffer has a name.
3764void check_marks_read(void)
3765{
3766  if (!curbuf->b_marks_read && get_shada_parameter('\'') > 0
3767      && curbuf->b_ffname != NULL) {
3768    shada_read_marks();
3769  }
3770
3771  // Always set b_marks_read; needed when 'shada' is changed to include
3772  // the ' parameter after opening a buffer.
3773  curbuf->b_marks_read = true;
3774}