Fixed issue #3815: TortoiseGitMerge crashes on Win7 on startup when winrt libraries...
[TortoiseGit.git] / src / TortoisePlink / MISC.H
blobcdbb184775a339a09f5945c1fe20e48b6a9f3b5a
1 /*\r
2  * Header for misc.c.\r
3  */\r
4 \r
5 #ifndef PUTTY_MISC_H\r
6 #define PUTTY_MISC_H\r
7 \r
8 #include "defs.h"\r
9 #include "puttymem.h"\r
10 #include "marshal.h"\r
12 #include <stdio.h>                     /* for FILE * */\r
13 #include <stdarg.h>                    /* for va_list */\r
14 #include <stdlib.h>                    /* for abort */\r
15 #include <time.h>                      /* for struct tm */\r
16 #include <limits.h>                    /* for INT_MAX/MIN */\r
17 #include <assert.h>                    /* for assert (obviously) */\r
19 unsigned long parse_blocksize(const char *bs);\r
20 char ctrlparse(char *s, char **next);\r
22 size_t host_strcspn(const char *s, const char *set);\r
23 char *host_strchr(const char *s, int c);\r
24 char *host_strrchr(const char *s, int c);\r
25 char *host_strduptrim(const char *s);\r
27 char *dupstr(const char *s);\r
28 char *dupcat_fn(const char *s1, ...);\r
29 #define dupcat(...) dupcat_fn(__VA_ARGS__, (const char *)NULL)\r
30 char *dupprintf(const char *fmt, ...) PRINTF_LIKE(1, 2);\r
31 char *dupvprintf(const char *fmt, va_list ap);\r
32 void burnstr(char *string);\r
34 /*\r
35  * The visible part of a strbuf structure. There's a surrounding\r
36  * implementation struct in misc.c, which isn't exposed to client\r
37  * code.\r
38  */\r
39 struct strbuf {\r
40     char *s;\r
41     unsigned char *u;\r
42     size_t len;\r
43     BinarySink_IMPLEMENTATION;\r
44 };\r
46 /* strbuf constructors: strbuf_new_nm and strbuf_new differ in that a\r
47  * strbuf constructed using the _nm version will resize itself by\r
48  * alloc/copy/smemclr/free instead of realloc. Use that version for\r
49  * data sensitive enough that it's worth costing performance to\r
50  * avoid copies of it lingering in process memory. */\r
51 strbuf *strbuf_new(void);\r
52 strbuf *strbuf_new_nm(void);\r
54 void strbuf_free(strbuf *buf);\r
55 void *strbuf_append(strbuf *buf, size_t len);\r
56 void strbuf_shrink_to(strbuf *buf, size_t new_len);\r
57 void strbuf_shrink_by(strbuf *buf, size_t amount_to_remove);\r
58 char *strbuf_to_str(strbuf *buf); /* does free buf, but you must free result */\r
59 void strbuf_catf(strbuf *buf, const char *fmt, ...) PRINTF_LIKE(2, 3);\r
60 void strbuf_catfv(strbuf *buf, const char *fmt, va_list ap);\r
61 static inline void strbuf_clear(strbuf *buf) { strbuf_shrink_to(buf, 0); }\r
62 bool strbuf_chomp(strbuf *buf, char char_to_remove);\r
64 strbuf *strbuf_new_for_agent_query(void);\r
65 void strbuf_finalise_agent_query(strbuf *buf);\r
67 /* String-to-Unicode converters that auto-allocate the destination and\r
68  * work around the rather deficient interface of mb_to_wc.\r
69  *\r
70  * These actually live in miscucs.c, not misc.c (the distinction being\r
71  * that the former is only linked into tools that also have the main\r
72  * Unicode support). */\r
73 wchar_t *dup_mb_to_wc_c(int codepage, int flags, const char *string, int len);\r
74 wchar_t *dup_mb_to_wc(int codepage, int flags, const char *string);\r
76 static inline int toint(unsigned u)\r
77 {\r
78     /*\r
79      * Convert an unsigned to an int, without running into the\r
80      * undefined behaviour which happens by the strict C standard if\r
81      * the value overflows. You'd hope that sensible compilers would\r
82      * do the sensible thing in response to a cast, but actually I\r
83      * don't trust modern compilers not to do silly things like\r
84      * assuming that _obviously_ you wouldn't have caused an overflow\r
85      * and so they can elide an 'if (i < 0)' test immediately after\r
86      * the cast.\r
87      *\r
88      * Sensible compilers ought of course to optimise this entire\r
89      * function into 'just return the input value', and since it's\r
90      * also declared inline, elide it completely in their output.\r
91      */\r
92     if (u <= (unsigned)INT_MAX)\r
93         return (int)u;\r
94     else if (u >= (unsigned)INT_MIN)   /* wrap in cast _to_ unsigned is OK */\r
95         return INT_MIN + (int)(u - (unsigned)INT_MIN);\r
96     else\r
97         return INT_MIN; /* fallback; should never occur on binary machines */\r
98 }\r
100 char *fgetline(FILE *fp);\r
101 bool read_file_into(BinarySink *bs, FILE *fp);\r
102 char *chomp(char *str);\r
103 bool strstartswith(const char *s, const char *t);\r
104 bool strendswith(const char *s, const char *t);\r
106 void base64_encode_atom(const unsigned char *data, int n, char *out);\r
107 int base64_decode_atom(const char *atom, unsigned char *out);\r
109 struct bufchain_granule;\r
110 struct bufchain_tag {\r
111     struct bufchain_granule *head, *tail;\r
112     size_t buffersize;           /* current amount of buffered data */\r
114     void (*queue_idempotent_callback)(IdempotentCallback *ic);\r
115     IdempotentCallback *ic;\r
116 };\r
118 void bufchain_init(bufchain *ch);\r
119 void bufchain_clear(bufchain *ch);\r
120 size_t bufchain_size(bufchain *ch);\r
121 void bufchain_add(bufchain *ch, const void *data, size_t len);\r
122 ptrlen bufchain_prefix(bufchain *ch);\r
123 void bufchain_consume(bufchain *ch, size_t len);\r
124 void bufchain_fetch(bufchain *ch, void *data, size_t len);\r
125 void bufchain_fetch_consume(bufchain *ch, void *data, size_t len);\r
126 bool bufchain_try_fetch_consume(bufchain *ch, void *data, size_t len);\r
127 size_t bufchain_fetch_consume_up_to(bufchain *ch, void *data, size_t len);\r
128 void bufchain_set_callback_inner(\r
129     bufchain *ch, IdempotentCallback *ic,\r
130     void (*queue_idempotent_callback)(IdempotentCallback *ic));\r
131 static inline void bufchain_set_callback(bufchain *ch, IdempotentCallback *ic)\r
133     extern void queue_idempotent_callback(struct IdempotentCallback *ic);\r
134     /* Wrapper that puts in the standard queue_idempotent_callback\r
135      * function. Lives here rather than in utils.c so that standalone\r
136      * programs can use the bufchain facility without this optional\r
137      * callback feature and not need to provide a stub of\r
138      * queue_idempotent_callback. */\r
139     bufchain_set_callback_inner(ch, ic, queue_idempotent_callback);\r
142 bool validate_manual_hostkey(char *key);\r
144 struct tm ltime(void);\r
146 /*\r
147  * Special form of strcmp which can cope with NULL inputs. NULL is\r
148  * defined to sort before even the empty string.\r
149  */\r
150 int nullstrcmp(const char *a, const char *b);\r
152 static inline ptrlen make_ptrlen(const void *ptr, size_t len)\r
154     ptrlen pl;\r
155     pl.ptr = ptr;\r
156     pl.len = len;\r
157     return pl;\r
160 static inline ptrlen ptrlen_from_asciz(const char *str)\r
162     return make_ptrlen(str, strlen(str));\r
165 static inline ptrlen ptrlen_from_strbuf(strbuf *sb)\r
167     return make_ptrlen(sb->u, sb->len);\r
170 bool ptrlen_eq_string(ptrlen pl, const char *str);\r
171 bool ptrlen_eq_ptrlen(ptrlen pl1, ptrlen pl2);\r
172 int ptrlen_strcmp(ptrlen pl1, ptrlen pl2);\r
173 /* ptrlen_startswith and ptrlen_endswith write through their 'tail'\r
174  * argument if and only if it is non-NULL and they return true. Hence\r
175  * you can write ptrlen_startswith(thing, prefix, &thing), writing\r
176  * back to the same ptrlen it read from, to remove a prefix if present\r
177  * and say whether it did so. */\r
178 bool ptrlen_startswith(ptrlen whole, ptrlen prefix, ptrlen *tail);\r
179 bool ptrlen_endswith(ptrlen whole, ptrlen suffix, ptrlen *tail);\r
180 ptrlen ptrlen_get_word(ptrlen *input, const char *separators);\r
181 char *mkstr(ptrlen pl);\r
182 int string_length_for_printf(size_t);\r
183 /* Derive two printf arguments from a ptrlen, suitable for "%.*s" */\r
184 #define PTRLEN_PRINTF(pl) \\r
185     string_length_for_printf((pl).len), (const char *)(pl).ptr\r
186 /* Make a ptrlen out of a compile-time string literal. We try to\r
187  * enforce that it _is_ a string literal by token-pasting "" on to it,\r
188  * which should provoke a compile error if it's any other kind of\r
189  * string. */\r
190 #define PTRLEN_LITERAL(stringlit) \\r
191     TYPECHECK("" stringlit "", make_ptrlen(stringlit, sizeof(stringlit)-1))\r
192 /* Make a ptrlen out of a compile-time string literal in a way that\r
193  * allows you to declare the ptrlen itself as a compile-time initialiser. */\r
194 #define PTRLEN_DECL_LITERAL(stringlit) \\r
195     { TYPECHECK("" stringlit "", stringlit), sizeof(stringlit)-1 }\r
196 /* Make a ptrlen out of a constant byte array. */\r
197 #define PTRLEN_FROM_CONST_BYTES(a) make_ptrlen(a, sizeof(a))\r
199 /* Wipe sensitive data out of memory that's about to be freed. Simpler\r
200  * than memset because we don't need the fill char parameter; also\r
201  * attempts (by fiddly use of volatile) to inhibit the compiler from\r
202  * over-cleverly trying to optimise the memset away because it knows\r
203  * the variable is going out of scope. */\r
204 void smemclr(void *b, size_t len);\r
206 /* Compare two fixed-length chunks of memory for equality, without\r
207  * data-dependent control flow (so an attacker with a very accurate\r
208  * stopwatch can't try to guess where the first mismatching byte was).\r
209  * Returns false for mismatch or true for equality (unlike memcmp),\r
210  * hinted at by the 'eq' in the name. */\r
211 bool smemeq(const void *av, const void *bv, size_t len);\r
213 /* Encode a single UTF-8 character. Assumes that illegal characters\r
214  * (such as things in the surrogate range, or > 0x10FFFF) have already\r
215  * been removed. */\r
216 size_t encode_utf8(void *output, unsigned long ch);\r
218 /* Write a string out in C string-literal format. */\r
219 void write_c_string_literal(FILE *fp, ptrlen str);\r
221 char *buildinfo(const char *newline);\r
223 /*\r
224  * A function you can put at points in the code where execution should\r
225  * never reach in the first place. Better than assert(false), or even\r
226  * assert(false && "some explanatory message"), because some compilers\r
227  * don't interpret assert(false) as a declaration of unreachability,\r
228  * so they may still warn about pointless things like some variable\r
229  * not being initialised on the unreachable code path.\r
230  *\r
231  * I follow the assertion with a call to abort() just in case someone\r
232  * compiles with -DNDEBUG, and I wrap that abort inside my own\r
233  * function labelled NORETURN just in case some unusual kind of system\r
234  * header wasn't foresighted enough to label abort() itself that way.\r
235  */\r
236 static inline NORETURN void unreachable_internal(void) { abort(); }\r
237 #define unreachable(msg) (assert(false && msg), unreachable_internal())\r
239 /*\r
240  * Debugging functions.\r
241  *\r
242  * Output goes to debug.log\r
243  *\r
244  * debug() is like printf().\r
245  *\r
246  * dmemdump() and dmemdumpl() both do memory dumps.  The difference\r
247  * is that dmemdumpl() is more suited for when the memory address is\r
248  * important (say because you'll be recording pointer values later\r
249  * on).  dmemdump() is more concise.\r
250  */\r
252 #ifdef DEBUG\r
253 void debug_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);\r
254 void debug_memdump(const void *buf, int len, bool L);\r
255 #define debug(...) (debug_printf(__VA_ARGS__))\r
256 #define dmemdump(buf,len) (debug_memdump(buf, len, false))\r
257 #define dmemdumpl(buf,len) (debug_memdump(buf, len, true))\r
258 #else\r
259 #define debug(...) ((void)0)\r
260 #define dmemdump(buf,len) ((void)0)\r
261 #define dmemdumpl(buf,len) ((void)0)\r
262 #endif\r
264 #ifndef lenof\r
265 #define lenof(x) ( (sizeof((x))) / (sizeof(*(x))))\r
266 #endif\r
268 #ifndef min\r
269 #define min(x,y) ( (x) < (y) ? (x) : (y) )\r
270 #endif\r
271 #ifndef max\r
272 #define max(x,y) ( (x) > (y) ? (x) : (y) )\r
273 #endif\r
275 static inline uint64_t GET_64BIT_LSB_FIRST(const void *vp)\r
277     const uint8_t *p = (const uint8_t *)vp;\r
278     return (((uint64_t)p[0]      ) | ((uint64_t)p[1] <<  8) |\r
279             ((uint64_t)p[2] << 16) | ((uint64_t)p[3] << 24) |\r
280             ((uint64_t)p[4] << 32) | ((uint64_t)p[5] << 40) |\r
281             ((uint64_t)p[6] << 48) | ((uint64_t)p[7] << 56));\r
284 static inline void PUT_64BIT_LSB_FIRST(void *vp, uint64_t value)\r
286     uint8_t *p = (uint8_t *)vp;\r
287     p[0] = (uint8_t)(value);\r
288     p[1] = (uint8_t)(value >> 8);\r
289     p[2] = (uint8_t)(value >> 16);\r
290     p[3] = (uint8_t)(value >> 24);\r
291     p[4] = (uint8_t)(value >> 32);\r
292     p[5] = (uint8_t)(value >> 40);\r
293     p[6] = (uint8_t)(value >> 48);\r
294     p[7] = (uint8_t)(value >> 56);\r
297 static inline uint32_t GET_32BIT_LSB_FIRST(const void *vp)\r
299     const uint8_t *p = (const uint8_t *)vp;\r
300     return (((uint32_t)p[0]      ) | ((uint32_t)p[1] <<  8) |\r
301             ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24));\r
304 static inline void PUT_32BIT_LSB_FIRST(void *vp, uint32_t value)\r
306     uint8_t *p = (uint8_t *)vp;\r
307     p[0] = (uint8_t)(value);\r
308     p[1] = (uint8_t)(value >> 8);\r
309     p[2] = (uint8_t)(value >> 16);\r
310     p[3] = (uint8_t)(value >> 24);\r
313 static inline uint16_t GET_16BIT_LSB_FIRST(const void *vp)\r
315     const uint8_t *p = (const uint8_t *)vp;\r
316     return (((uint16_t)p[0]      ) | ((uint16_t)p[1] <<  8));\r
319 static inline void PUT_16BIT_LSB_FIRST(void *vp, uint16_t value)\r
321     uint8_t *p = (uint8_t *)vp;\r
322     p[0] = (uint8_t)(value);\r
323     p[1] = (uint8_t)(value >> 8);\r
326 static inline uint64_t GET_64BIT_MSB_FIRST(const void *vp)\r
328     const uint8_t *p = (const uint8_t *)vp;\r
329     return (((uint64_t)p[7]      ) | ((uint64_t)p[6] <<  8) |\r
330             ((uint64_t)p[5] << 16) | ((uint64_t)p[4] << 24) |\r
331             ((uint64_t)p[3] << 32) | ((uint64_t)p[2] << 40) |\r
332             ((uint64_t)p[1] << 48) | ((uint64_t)p[0] << 56));\r
335 static inline void PUT_64BIT_MSB_FIRST(void *vp, uint64_t value)\r
337     uint8_t *p = (uint8_t *)vp;\r
338     p[7] = (uint8_t)(value);\r
339     p[6] = (uint8_t)(value >> 8);\r
340     p[5] = (uint8_t)(value >> 16);\r
341     p[4] = (uint8_t)(value >> 24);\r
342     p[3] = (uint8_t)(value >> 32);\r
343     p[2] = (uint8_t)(value >> 40);\r
344     p[1] = (uint8_t)(value >> 48);\r
345     p[0] = (uint8_t)(value >> 56);\r
348 static inline uint32_t GET_32BIT_MSB_FIRST(const void *vp)\r
350     const uint8_t *p = (const uint8_t *)vp;\r
351     return (((uint32_t)p[3]      ) | ((uint32_t)p[2] <<  8) |\r
352             ((uint32_t)p[1] << 16) | ((uint32_t)p[0] << 24));\r
355 static inline void PUT_32BIT_MSB_FIRST(void *vp, uint32_t value)\r
357     uint8_t *p = (uint8_t *)vp;\r
358     p[3] = (uint8_t)(value);\r
359     p[2] = (uint8_t)(value >> 8);\r
360     p[1] = (uint8_t)(value >> 16);\r
361     p[0] = (uint8_t)(value >> 24);\r
364 static inline uint16_t GET_16BIT_MSB_FIRST(const void *vp)\r
366     const uint8_t *p = (const uint8_t *)vp;\r
367     return (((uint16_t)p[1]      ) | ((uint16_t)p[0] <<  8));\r
370 static inline void PUT_16BIT_MSB_FIRST(void *vp, uint16_t value)\r
372     uint8_t *p = (uint8_t *)vp;\r
373     p[1] = (uint8_t)(value);\r
374     p[0] = (uint8_t)(value >> 8);\r
377 /* Replace NULL with the empty string, permitting an idiom in which we\r
378  * get a string (pointer,length) pair that might be NULL,0 and can\r
379  * then safely say things like printf("%.*s", length, NULLTOEMPTY(ptr)) */\r
380 static inline const char *NULLTOEMPTY(const char *s)\r
382     return s ? s : "";\r
385 /* StripCtrlChars, defined in stripctrl.c: an adapter you can put on\r
386  * the front of one BinarySink and which functions as one in turn.\r
387  * Interprets its input as a stream of multibyte characters in the\r
388  * system locale, and removes any that are not either printable\r
389  * characters or newlines. */\r
390 struct StripCtrlChars {\r
391     BinarySink_IMPLEMENTATION;\r
392     /* and this is contained in a larger structure */\r
393 };\r
394 StripCtrlChars *stripctrl_new(\r
395     BinarySink *bs_out, bool permit_cr, wchar_t substitution);\r
396 StripCtrlChars *stripctrl_new_term_fn(\r
397     BinarySink *bs_out, bool permit_cr, wchar_t substitution,\r
398     Terminal *term, unsigned long (*translate)(\r
399         Terminal *, term_utf8_decode *, unsigned char));\r
400 #define stripctrl_new_term(bs, cr, sub, term) \\r
401     stripctrl_new_term_fn(bs, cr, sub, term, term_translate)\r
402 void stripctrl_retarget(StripCtrlChars *sccpub, BinarySink *new_bs_out);\r
403 void stripctrl_reset(StripCtrlChars *sccpub);\r
404 void stripctrl_free(StripCtrlChars *sanpub);\r
405 void stripctrl_enable_line_limiting(StripCtrlChars *sccpub);\r
406 char *stripctrl_string_ptrlen(StripCtrlChars *sccpub, ptrlen str);\r
407 static inline char *stripctrl_string(StripCtrlChars *sccpub, const char *str)\r
409     return stripctrl_string_ptrlen(sccpub, ptrlen_from_asciz(str));\r
412 /*\r
413  * A mechanism for loading a file from disk into a memory buffer where\r
414  * it can be picked apart as a BinarySource.\r
415  */\r
416 struct LoadedFile {\r
417     char *data;\r
418     size_t len, max_size;\r
419     BinarySource_IMPLEMENTATION;\r
420 };\r
421 typedef enum {\r
422     LF_OK,      /* file loaded successfully */\r
423     LF_TOO_BIG, /* file didn't fit in buffer */\r
424     LF_ERROR,   /* error from stdio layer */\r
425 } LoadFileStatus;\r
426 LoadedFile *lf_new(size_t max_size);\r
427 void lf_free(LoadedFile *lf);\r
428 LoadFileStatus lf_load_fp(LoadedFile *lf, FILE *fp);\r
429 LoadFileStatus lf_load(LoadedFile *lf, const Filename *filename);\r
430 static inline ptrlen ptrlen_from_lf(LoadedFile *lf)\r
431 { return make_ptrlen(lf->data, lf->len); }\r
433 /* Set the memory block of 'size' bytes at 'out' to the bitwise XOR of\r
434  * the two blocks of the same size at 'in1' and 'in2'.\r
435  *\r
436  * 'out' may point to exactly the same address as one of the inputs,\r
437  * but if the input and output blocks overlap in any other way, the\r
438  * result of this function is not guaranteed. No memmove-style effort\r
439  * is made to handle difficult overlap cases. */\r
440 void memxor(uint8_t *out, const uint8_t *in1, const uint8_t *in2, size_t size);\r
442 #endif\r