xref: /redis-3.2.3/src/debug.c (revision 5e362b84)
1 /*
2  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *   * Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *   * Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *   * Neither the name of Redis nor the names of its contributors may be used
14  *     to endorse or promote products derived from this software without
15  *     specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "redis.h"
31 #include "sha1.h"   /* SHA1 is used for DEBUG DIGEST */
32 #include "crc64.h"
33 
34 #include <arpa/inet.h>
35 #include <signal.h>
36 
37 #ifdef HAVE_BACKTRACE
38 #include <execinfo.h>
39 #include <ucontext.h>
40 #include <fcntl.h>
41 #include "bio.h"
42 #endif /* HAVE_BACKTRACE */
43 
44 #ifdef __CYGWIN__
45 #ifndef SA_ONSTACK
46 #define SA_ONSTACK 0x08000000
47 #endif
48 #endif
49 
50 /* ================================= Debugging ============================== */
51 
52 /* Compute the sha1 of string at 's' with 'len' bytes long.
53  * The SHA1 is then xored against the string pointed by digest.
54  * Since xor is commutative, this operation is used in order to
55  * "add" digests relative to unordered elements.
56  *
57  * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
58 void xorDigest(unsigned char *digest, void *ptr, size_t len) {
59     SHA1_CTX ctx;
60     unsigned char hash[20], *s = ptr;
61     int j;
62 
63     SHA1Init(&ctx);
64     SHA1Update(&ctx,s,len);
65     SHA1Final(hash,&ctx);
66 
67     for (j = 0; j < 20; j++)
68         digest[j] ^= hash[j];
69 }
70 
71 void xorObjectDigest(unsigned char *digest, robj *o) {
72     o = getDecodedObject(o);
73     xorDigest(digest,o->ptr,sdslen(o->ptr));
74     decrRefCount(o);
75 }
76 
77 /* This function instead of just computing the SHA1 and xoring it
78  * against digest, also perform the digest of "digest" itself and
79  * replace the old value with the new one.
80  *
81  * So the final digest will be:
82  *
83  * digest = SHA1(digest xor SHA1(data))
84  *
85  * This function is used every time we want to preserve the order so
86  * that digest(a,b,c,d) will be different than digest(b,c,d,a)
87  *
88  * Also note that mixdigest("foo") followed by mixdigest("bar")
89  * will lead to a different digest compared to "fo", "obar".
90  */
91 void mixDigest(unsigned char *digest, void *ptr, size_t len) {
92     SHA1_CTX ctx;
93     char *s = ptr;
94 
95     xorDigest(digest,s,len);
96     SHA1Init(&ctx);
97     SHA1Update(&ctx,digest,20);
98     SHA1Final(digest,&ctx);
99 }
100 
101 void mixObjectDigest(unsigned char *digest, robj *o) {
102     o = getDecodedObject(o);
103     mixDigest(digest,o->ptr,sdslen(o->ptr));
104     decrRefCount(o);
105 }
106 
107 /* Compute the dataset digest. Since keys, sets elements, hashes elements
108  * are not ordered, we use a trick: every aggregate digest is the xor
109  * of the digests of their elements. This way the order will not change
110  * the result. For list instead we use a feedback entering the output digest
111  * as input in order to ensure that a different ordered list will result in
112  * a different digest. */
113 void computeDatasetDigest(unsigned char *final) {
114     unsigned char digest[20];
115     char buf[128];
116     dictIterator *di = NULL;
117     dictEntry *de;
118     int j;
119     uint32_t aux;
120 
121     memset(final,0,20); /* Start with a clean result */
122 
123     for (j = 0; j < server.dbnum; j++) {
124         redisDb *db = server.db+j;
125 
126         if (dictSize(db->dict) == 0) continue;
127         di = dictGetIterator(db->dict);
128 
129         /* hash the DB id, so the same dataset moved in a different
130          * DB will lead to a different digest */
131         aux = htonl(j);
132         mixDigest(final,&aux,sizeof(aux));
133 
134         /* Iterate this DB writing every entry */
135         while((de = dictNext(di)) != NULL) {
136             sds key;
137             robj *keyobj, *o;
138             long long expiretime;
139 
140             memset(digest,0,20); /* This key-val digest */
141             key = dictGetKey(de);
142             keyobj = createStringObject(key,sdslen(key));
143 
144             mixDigest(digest,key,sdslen(key));
145 
146             o = dictGetVal(de);
147 
148             aux = htonl(o->type);
149             mixDigest(digest,&aux,sizeof(aux));
150             expiretime = getExpire(db,keyobj);
151 
152             /* Save the key and associated value */
153             if (o->type == REDIS_STRING) {
154                 mixObjectDigest(digest,o);
155             } else if (o->type == REDIS_LIST) {
156                 listTypeIterator *li = listTypeInitIterator(o,0,REDIS_TAIL);
157                 listTypeEntry entry;
158                 while(listTypeNext(li,&entry)) {
159                     robj *eleobj = listTypeGet(&entry);
160                     mixObjectDigest(digest,eleobj);
161                     decrRefCount(eleobj);
162                 }
163                 listTypeReleaseIterator(li);
164             } else if (o->type == REDIS_SET) {
165                 setTypeIterator *si = setTypeInitIterator(o);
166                 robj *ele;
167                 while((ele = setTypeNextObject(si)) != NULL) {
168                     xorObjectDigest(digest,ele);
169                     decrRefCount(ele);
170                 }
171                 setTypeReleaseIterator(si);
172             } else if (o->type == REDIS_ZSET) {
173                 unsigned char eledigest[20];
174 
175                 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
176                     unsigned char *zl = o->ptr;
177                     unsigned char *eptr, *sptr;
178                     unsigned char *vstr;
179                     unsigned int vlen;
180                     long long vll;
181                     double score;
182 
183                     eptr = ziplistIndex(zl,0);
184                     redisAssert(eptr != NULL);
185                     sptr = ziplistNext(zl,eptr);
186                     redisAssert(sptr != NULL);
187 
188                     while (eptr != NULL) {
189                         redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
190                         score = zzlGetScore(sptr);
191 
192                         memset(eledigest,0,20);
193                         if (vstr != NULL) {
194                             mixDigest(eledigest,vstr,vlen);
195                         } else {
196                             ll2string(buf,sizeof(buf),vll);
197                             mixDigest(eledigest,buf,strlen(buf));
198                         }
199 
200                         snprintf(buf,sizeof(buf),"%.17g",score);
201                         mixDigest(eledigest,buf,strlen(buf));
202                         xorDigest(digest,eledigest,20);
203                         zzlNext(zl,&eptr,&sptr);
204                     }
205                 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
206                     zset *zs = o->ptr;
207                     dictIterator *di = dictGetIterator(zs->dict);
208                     dictEntry *de;
209 
210                     while((de = dictNext(di)) != NULL) {
211                         robj *eleobj = dictGetKey(de);
212                         double *score = dictGetVal(de);
213 
214                         snprintf(buf,sizeof(buf),"%.17g",*score);
215                         memset(eledigest,0,20);
216                         mixObjectDigest(eledigest,eleobj);
217                         mixDigest(eledigest,buf,strlen(buf));
218                         xorDigest(digest,eledigest,20);
219                     }
220                     dictReleaseIterator(di);
221                 } else {
222                     redisPanic("Unknown sorted set encoding");
223                 }
224             } else if (o->type == REDIS_HASH) {
225                 hashTypeIterator *hi;
226                 robj *obj;
227 
228                 hi = hashTypeInitIterator(o);
229                 while (hashTypeNext(hi) != REDIS_ERR) {
230                     unsigned char eledigest[20];
231 
232                     memset(eledigest,0,20);
233                     obj = hashTypeCurrentObject(hi,REDIS_HASH_KEY);
234                     mixObjectDigest(eledigest,obj);
235                     decrRefCount(obj);
236                     obj = hashTypeCurrentObject(hi,REDIS_HASH_VALUE);
237                     mixObjectDigest(eledigest,obj);
238                     decrRefCount(obj);
239                     xorDigest(digest,eledigest,20);
240                 }
241                 hashTypeReleaseIterator(hi);
242             } else {
243                 redisPanic("Unknown object type");
244             }
245             /* If the key has an expire, add it to the mix */
246             if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
247             /* We can finally xor the key-val digest to the final digest */
248             xorDigest(final,digest,20);
249             decrRefCount(keyobj);
250         }
251         dictReleaseIterator(di);
252     }
253 }
254 
255 void inputCatSds(void *result, const char *str) {
256     /* result is actually a (sds *), so re-cast it here */
257     sds *info = (sds *)result;
258     *info = sdscat(*info, str);
259 }
260 
261 void debugCommand(redisClient *c) {
262     if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
263         *((char*)-1) = 'x';
264     } else if (!strcasecmp(c->argv[1]->ptr,"oom")) {
265         void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */
266         zfree(ptr);
267         addReply(c,shared.ok);
268     } else if (!strcasecmp(c->argv[1]->ptr,"assert")) {
269         if (c->argc >= 3) c->argv[2] = tryObjectEncoding(c->argv[2]);
270         redisAssertWithInfo(c,c->argv[0],1 == 2);
271     } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
272         if (rdbSave(server.rdb_filename) != REDIS_OK) {
273             addReply(c,shared.err);
274             return;
275         }
276         emptyDb(NULL);
277         if (rdbLoad(server.rdb_filename) != REDIS_OK) {
278             addReplyError(c,"Error trying to load the RDB dump");
279             return;
280         }
281         redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
282         addReply(c,shared.ok);
283     } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
284         emptyDb(NULL);
285         if (loadAppendOnlyFile(server.aof_filename) != REDIS_OK) {
286             addReply(c,shared.err);
287             return;
288         }
289         server.dirty = 0; /* Prevent AOF / replication */
290         redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
291         addReply(c,shared.ok);
292     } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
293         dictEntry *de;
294         robj *val;
295         char *strenc;
296 
297         if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {
298             addReply(c,shared.nokeyerr);
299             return;
300         }
301         val = dictGetVal(de);
302         strenc = strEncoding(val->encoding);
303 
304         addReplyStatusFormat(c,
305             "Value at:%p refcount:%d "
306             "encoding:%s serializedlength:%lld "
307             "lru:%d lru_seconds_idle:%llu",
308             (void*)val, val->refcount,
309             strenc, (long long) rdbSavedObjectLen(val),
310             val->lru, estimateObjectIdleTime(val)/1000);
311     } else if (!strcasecmp(c->argv[1]->ptr,"sdslen") && c->argc == 3) {
312         dictEntry *de;
313         robj *val;
314         sds key;
315 
316         if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {
317             addReply(c,shared.nokeyerr);
318             return;
319         }
320         val = dictGetVal(de);
321         key = dictGetKey(de);
322 
323         if (val->type != REDIS_STRING || !sdsEncodedObject(val)) {
324             addReplyError(c,"Not an sds encoded string.");
325         } else {
326             addReplyStatusFormat(c,
327                 "key_sds_len:%lld, key_sds_avail:%lld, "
328                 "val_sds_len:%lld, val_sds_avail:%lld",
329                 (long long) sdslen(key),
330                 (long long) sdsavail(key),
331                 (long long) sdslen(val->ptr),
332                 (long long) sdsavail(val->ptr));
333         }
334     } else if (!strcasecmp(c->argv[1]->ptr,"populate") &&
335                (c->argc == 3 || c->argc == 4)) {
336         long keys, j;
337         robj *key, *val;
338         char buf[128];
339 
340         if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
341             return;
342         dictExpand(c->db->dict,keys);
343         for (j = 0; j < keys; j++) {
344             snprintf(buf,sizeof(buf),"%s:%lu",
345                 (c->argc == 3) ? "key" : (char*)c->argv[3]->ptr, j);
346             key = createStringObject(buf,strlen(buf));
347             if (lookupKeyWrite(c->db,key) != NULL) {
348                 decrRefCount(key);
349                 continue;
350             }
351             snprintf(buf,sizeof(buf),"value:%lu",j);
352             val = createStringObject(buf,strlen(buf));
353             dbAdd(c->db,key,val);
354             decrRefCount(key);
355         }
356         addReply(c,shared.ok);
357     } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
358         unsigned char digest[20];
359         sds d = sdsempty();
360         int j;
361 
362         computeDatasetDigest(digest);
363         for (j = 0; j < 20; j++)
364             d = sdscatprintf(d, "%02x",digest[j]);
365         addReplyStatus(c,d);
366         sdsfree(d);
367     } else if (!strcasecmp(c->argv[1]->ptr,"sleep") && c->argc == 3) {
368         double dtime = strtod(c->argv[2]->ptr,NULL);
369         long long utime = dtime*1000000;
370         struct timespec tv;
371 
372         tv.tv_sec = utime / 1000000;
373         tv.tv_nsec = (utime % 1000000) * 1000;
374         nanosleep(&tv, NULL);
375         addReply(c,shared.ok);
376     } else if (!strcasecmp(c->argv[1]->ptr,"set-active-expire") &&
377                c->argc == 3)
378     {
379         server.active_expire_enabled = atoi(c->argv[2]->ptr);
380         addReply(c,shared.ok);
381     } else if (!strcasecmp(c->argv[1]->ptr,"error") && c->argc == 3) {
382         sds errstr = sdsnewlen("-",1);
383 
384         errstr = sdscatsds(errstr,c->argv[2]->ptr);
385         errstr = sdsmapchars(errstr,"\n\r","  ",2); /* no newlines in errors. */
386         errstr = sdscatlen(errstr,"\r\n",2);
387         addReplySds(c,errstr);
388     } else if (!strcasecmp(c->argv[1]->ptr,"jemalloc") && c->argc == 3) {
389 #if defined(USE_JEMALLOC)
390         if (!strcasecmp(c->argv[2]->ptr, "info")) {
391             sds info = sdsempty();
392             je_malloc_stats_print(inputCatSds, &info, NULL);
393             addReplyBulkSds(c, info);
394         } else {
395             addReplyErrorFormat(c, "Valid jemalloc debug fields: info");
396         }
397 #else
398         addReplyErrorFormat(c, "jemalloc support not available");
399 #endif
400     } else {
401         addReplyErrorFormat(c, "Unknown DEBUG subcommand or wrong number of arguments for '%s'",
402             (char*)c->argv[1]->ptr);
403     }
404 }
405 
406 /* =========================== Crash handling  ============================== */
407 
408 void _redisAssert(char *estr, char *file, int line) {
409     bugReportStart();
410     redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
411     redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
412 #ifdef HAVE_BACKTRACE
413     server.assert_failed = estr;
414     server.assert_file = file;
415     server.assert_line = line;
416     redisLog(REDIS_WARNING,"(forcing SIGSEGV to print the bug report.)");
417 #endif
418     *((char*)-1) = 'x';
419 }
420 
421 void _redisAssertPrintClientInfo(redisClient *c) {
422     int j;
423 
424     bugReportStart();
425     redisLog(REDIS_WARNING,"=== ASSERTION FAILED CLIENT CONTEXT ===");
426     redisLog(REDIS_WARNING,"client->flags = %d", c->flags);
427     redisLog(REDIS_WARNING,"client->fd = %d", c->fd);
428     redisLog(REDIS_WARNING,"client->argc = %d", c->argc);
429     for (j=0; j < c->argc; j++) {
430         char buf[128];
431         char *arg;
432 
433         if (c->argv[j]->type == REDIS_STRING && sdsEncodedObject(c->argv[j])) {
434             arg = (char*) c->argv[j]->ptr;
435         } else {
436             snprintf(buf,sizeof(buf),"Object type: %d, encoding: %d",
437                 c->argv[j]->type, c->argv[j]->encoding);
438             arg = buf;
439         }
440         redisLog(REDIS_WARNING,"client->argv[%d] = \"%s\" (refcount: %d)",
441             j, arg, c->argv[j]->refcount);
442     }
443 }
444 
445 void redisLogObjectDebugInfo(robj *o) {
446     redisLog(REDIS_WARNING,"Object type: %d", o->type);
447     redisLog(REDIS_WARNING,"Object encoding: %d", o->encoding);
448     redisLog(REDIS_WARNING,"Object refcount: %d", o->refcount);
449     if (o->type == REDIS_STRING && sdsEncodedObject(o)) {
450         redisLog(REDIS_WARNING,"Object raw string len: %zu", sdslen(o->ptr));
451         if (sdslen(o->ptr) < 4096) {
452             sds repr = sdscatrepr(sdsempty(),o->ptr,sdslen(o->ptr));
453             redisLog(REDIS_WARNING,"Object raw string content: %s", repr);
454             sdsfree(repr);
455         }
456     } else if (o->type == REDIS_LIST) {
457         redisLog(REDIS_WARNING,"List length: %d", (int) listTypeLength(o));
458     } else if (o->type == REDIS_SET) {
459         redisLog(REDIS_WARNING,"Set size: %d", (int) setTypeSize(o));
460     } else if (o->type == REDIS_HASH) {
461         redisLog(REDIS_WARNING,"Hash size: %d", (int) hashTypeLength(o));
462     } else if (o->type == REDIS_ZSET) {
463         redisLog(REDIS_WARNING,"Sorted set size: %d", (int) zsetLength(o));
464         if (o->encoding == REDIS_ENCODING_SKIPLIST)
465             redisLog(REDIS_WARNING,"Skiplist level: %d", (int) ((zset*)o->ptr)->zsl->level);
466     }
467 }
468 
469 void _redisAssertPrintObject(robj *o) {
470     bugReportStart();
471     redisLog(REDIS_WARNING,"=== ASSERTION FAILED OBJECT CONTEXT ===");
472     redisLogObjectDebugInfo(o);
473 }
474 
475 void _redisAssertWithInfo(redisClient *c, robj *o, char *estr, char *file, int line) {
476     if (c) _redisAssertPrintClientInfo(c);
477     if (o) _redisAssertPrintObject(o);
478     _redisAssert(estr,file,line);
479 }
480 
481 void _redisPanic(char *msg, char *file, int line) {
482     bugReportStart();
483     redisLog(REDIS_WARNING,"------------------------------------------------");
484     redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
485     redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
486 #ifdef HAVE_BACKTRACE
487     redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
488 #endif
489     redisLog(REDIS_WARNING,"------------------------------------------------");
490     *((char*)-1) = 'x';
491 }
492 
493 void bugReportStart(void) {
494     if (server.bug_report_start == 0) {
495         redisLog(REDIS_WARNING,
496             "\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ===");
497         server.bug_report_start = 1;
498     }
499 }
500 
501 #ifdef HAVE_BACKTRACE
502 static void *getMcontextEip(ucontext_t *uc) {
503 #if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
504     /* OSX < 10.6 */
505     #if defined(__x86_64__)
506     return (void*) uc->uc_mcontext->__ss.__rip;
507     #elif defined(__i386__)
508     return (void*) uc->uc_mcontext->__ss.__eip;
509     #else
510     return (void*) uc->uc_mcontext->__ss.__srr0;
511     #endif
512 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
513     /* OSX >= 10.6 */
514     #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
515     return (void*) uc->uc_mcontext->__ss.__rip;
516     #else
517     return (void*) uc->uc_mcontext->__ss.__eip;
518     #endif
519 #elif defined(__linux__)
520     /* Linux */
521     #if defined(__i386__)
522     return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
523     #elif defined(__X86_64__) || defined(__x86_64__)
524     return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
525     #elif defined(__ia64__) /* Linux IA64 */
526     return (void*) uc->uc_mcontext.sc_ip;
527     #endif
528 #else
529     return NULL;
530 #endif
531 }
532 
533 void logStackContent(void **sp) {
534     int i;
535     for (i = 15; i >= 0; i--) {
536         unsigned long addr = (unsigned long) sp+i;
537         unsigned long val = (unsigned long) sp[i];
538 
539         if (sizeof(long) == 4)
540             redisLog(REDIS_WARNING, "(%08lx) -> %08lx", addr, val);
541         else
542             redisLog(REDIS_WARNING, "(%016lx) -> %016lx", addr, val);
543     }
544 }
545 
546 void logRegisters(ucontext_t *uc) {
547     redisLog(REDIS_WARNING, "--- REGISTERS");
548 
549 /* OSX */
550 #if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
551   /* OSX AMD64 */
552     #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
553     redisLog(REDIS_WARNING,
554     "\n"
555     "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
556     "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
557     "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
558     "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
559     "RIP:%016lx EFL:%016lx\nCS :%016lx FS:%016lx  GS:%016lx",
560         (unsigned long) uc->uc_mcontext->__ss.__rax,
561         (unsigned long) uc->uc_mcontext->__ss.__rbx,
562         (unsigned long) uc->uc_mcontext->__ss.__rcx,
563         (unsigned long) uc->uc_mcontext->__ss.__rdx,
564         (unsigned long) uc->uc_mcontext->__ss.__rdi,
565         (unsigned long) uc->uc_mcontext->__ss.__rsi,
566         (unsigned long) uc->uc_mcontext->__ss.__rbp,
567         (unsigned long) uc->uc_mcontext->__ss.__rsp,
568         (unsigned long) uc->uc_mcontext->__ss.__r8,
569         (unsigned long) uc->uc_mcontext->__ss.__r9,
570         (unsigned long) uc->uc_mcontext->__ss.__r10,
571         (unsigned long) uc->uc_mcontext->__ss.__r11,
572         (unsigned long) uc->uc_mcontext->__ss.__r12,
573         (unsigned long) uc->uc_mcontext->__ss.__r13,
574         (unsigned long) uc->uc_mcontext->__ss.__r14,
575         (unsigned long) uc->uc_mcontext->__ss.__r15,
576         (unsigned long) uc->uc_mcontext->__ss.__rip,
577         (unsigned long) uc->uc_mcontext->__ss.__rflags,
578         (unsigned long) uc->uc_mcontext->__ss.__cs,
579         (unsigned long) uc->uc_mcontext->__ss.__fs,
580         (unsigned long) uc->uc_mcontext->__ss.__gs
581     );
582     logStackContent((void**)uc->uc_mcontext->__ss.__rsp);
583     #else
584     /* OSX x86 */
585     redisLog(REDIS_WARNING,
586     "\n"
587     "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
588     "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
589     "SS:%08lx  EFL:%08lx EIP:%08lx CS :%08lx\n"
590     "DS:%08lx  ES:%08lx  FS :%08lx GS :%08lx",
591         (unsigned long) uc->uc_mcontext->__ss.__eax,
592         (unsigned long) uc->uc_mcontext->__ss.__ebx,
593         (unsigned long) uc->uc_mcontext->__ss.__ecx,
594         (unsigned long) uc->uc_mcontext->__ss.__edx,
595         (unsigned long) uc->uc_mcontext->__ss.__edi,
596         (unsigned long) uc->uc_mcontext->__ss.__esi,
597         (unsigned long) uc->uc_mcontext->__ss.__ebp,
598         (unsigned long) uc->uc_mcontext->__ss.__esp,
599         (unsigned long) uc->uc_mcontext->__ss.__ss,
600         (unsigned long) uc->uc_mcontext->__ss.__eflags,
601         (unsigned long) uc->uc_mcontext->__ss.__eip,
602         (unsigned long) uc->uc_mcontext->__ss.__cs,
603         (unsigned long) uc->uc_mcontext->__ss.__ds,
604         (unsigned long) uc->uc_mcontext->__ss.__es,
605         (unsigned long) uc->uc_mcontext->__ss.__fs,
606         (unsigned long) uc->uc_mcontext->__ss.__gs
607     );
608     logStackContent((void**)uc->uc_mcontext->__ss.__esp);
609     #endif
610 /* Linux */
611 #elif defined(__linux__)
612     /* Linux x86 */
613     #if defined(__i386__)
614     redisLog(REDIS_WARNING,
615     "\n"
616     "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
617     "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
618     "SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\n"
619     "DS :%08lx ES :%08lx FS :%08lx GS:%08lx",
620         (unsigned long) uc->uc_mcontext.gregs[11],
621         (unsigned long) uc->uc_mcontext.gregs[8],
622         (unsigned long) uc->uc_mcontext.gregs[10],
623         (unsigned long) uc->uc_mcontext.gregs[9],
624         (unsigned long) uc->uc_mcontext.gregs[4],
625         (unsigned long) uc->uc_mcontext.gregs[5],
626         (unsigned long) uc->uc_mcontext.gregs[6],
627         (unsigned long) uc->uc_mcontext.gregs[7],
628         (unsigned long) uc->uc_mcontext.gregs[18],
629         (unsigned long) uc->uc_mcontext.gregs[17],
630         (unsigned long) uc->uc_mcontext.gregs[14],
631         (unsigned long) uc->uc_mcontext.gregs[15],
632         (unsigned long) uc->uc_mcontext.gregs[3],
633         (unsigned long) uc->uc_mcontext.gregs[2],
634         (unsigned long) uc->uc_mcontext.gregs[1],
635         (unsigned long) uc->uc_mcontext.gregs[0]
636     );
637     logStackContent((void**)uc->uc_mcontext.gregs[7]);
638     #elif defined(__X86_64__) || defined(__x86_64__)
639     /* Linux AMD64 */
640     redisLog(REDIS_WARNING,
641     "\n"
642     "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
643     "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
644     "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
645     "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
646     "RIP:%016lx EFL:%016lx\nCSGSFS:%016lx",
647         (unsigned long) uc->uc_mcontext.gregs[13],
648         (unsigned long) uc->uc_mcontext.gregs[11],
649         (unsigned long) uc->uc_mcontext.gregs[14],
650         (unsigned long) uc->uc_mcontext.gregs[12],
651         (unsigned long) uc->uc_mcontext.gregs[8],
652         (unsigned long) uc->uc_mcontext.gregs[9],
653         (unsigned long) uc->uc_mcontext.gregs[10],
654         (unsigned long) uc->uc_mcontext.gregs[15],
655         (unsigned long) uc->uc_mcontext.gregs[0],
656         (unsigned long) uc->uc_mcontext.gregs[1],
657         (unsigned long) uc->uc_mcontext.gregs[2],
658         (unsigned long) uc->uc_mcontext.gregs[3],
659         (unsigned long) uc->uc_mcontext.gregs[4],
660         (unsigned long) uc->uc_mcontext.gregs[5],
661         (unsigned long) uc->uc_mcontext.gregs[6],
662         (unsigned long) uc->uc_mcontext.gregs[7],
663         (unsigned long) uc->uc_mcontext.gregs[16],
664         (unsigned long) uc->uc_mcontext.gregs[17],
665         (unsigned long) uc->uc_mcontext.gregs[18]
666     );
667     logStackContent((void**)uc->uc_mcontext.gregs[15]);
668     #endif
669 #else
670     redisLog(REDIS_WARNING,
671         "  Dumping of registers not supported for this OS/arch");
672 #endif
673 }
674 
675 /* Logs the stack trace using the backtrace() call. This function is designed
676  * to be called from signal handlers safely. */
677 void logStackTrace(ucontext_t *uc) {
678     void *trace[100];
679     int trace_size = 0, fd;
680     int log_to_stdout = server.logfile[0] == '\0';
681 
682     /* Open the log file in append mode. */
683     fd = log_to_stdout ?
684         STDOUT_FILENO :
685         open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);
686     if (fd == -1) return;
687 
688     /* Generate the stack trace */
689     trace_size = backtrace(trace, 100);
690 
691     /* overwrite sigaction with caller's address */
692     if (getMcontextEip(uc) != NULL)
693         trace[1] = getMcontextEip(uc);
694 
695     /* Write symbols to log file */
696     backtrace_symbols_fd(trace, trace_size, fd);
697 
698     /* Cleanup */
699     if (!log_to_stdout) close(fd);
700 }
701 
702 /* Log information about the "current" client, that is, the client that is
703  * currently being served by Redis. May be NULL if Redis is not serving a
704  * client right now. */
705 void logCurrentClient(void) {
706     if (server.current_client == NULL) return;
707 
708     redisClient *cc = server.current_client;
709     sds client;
710     int j;
711 
712     redisLog(REDIS_WARNING, "--- CURRENT CLIENT INFO");
713     client = catClientInfoString(sdsempty(),cc);
714     redisLog(REDIS_WARNING,"client: %s", client);
715     sdsfree(client);
716     for (j = 0; j < cc->argc; j++) {
717         robj *decoded;
718 
719         decoded = getDecodedObject(cc->argv[j]);
720         redisLog(REDIS_WARNING,"argv[%d]: '%s'", j, (char*)decoded->ptr);
721         decrRefCount(decoded);
722     }
723     /* Check if the first argument, usually a key, is found inside the
724      * selected DB, and if so print info about the associated object. */
725     if (cc->argc >= 1) {
726         robj *val, *key;
727         dictEntry *de;
728 
729         key = getDecodedObject(cc->argv[1]);
730         de = dictFind(cc->db->dict, key->ptr);
731         if (de) {
732             val = dictGetVal(de);
733             redisLog(REDIS_WARNING,"key '%s' found in DB containing the following object:", (char*)key->ptr);
734             redisLogObjectDebugInfo(val);
735         }
736         decrRefCount(key);
737     }
738 }
739 
740 #if defined(HAVE_PROC_MAPS)
741 void memtest_non_destructive_invert(void *addr, size_t size);
742 void memtest_non_destructive_swap(void *addr, size_t size);
743 #define MEMTEST_MAX_REGIONS 128
744 
745 int memtest_test_linux_anonymous_maps(void) {
746     FILE *fp = fopen("/proc/self/maps","r");
747     char line[1024];
748     size_t start_addr, end_addr, size;
749     size_t start_vect[MEMTEST_MAX_REGIONS];
750     size_t size_vect[MEMTEST_MAX_REGIONS];
751     int regions = 0, j;
752     uint64_t crc1 = 0, crc2 = 0, crc3 = 0;
753 
754     while(fgets(line,sizeof(line),fp) != NULL) {
755         char *start, *end, *p = line;
756 
757         start = p;
758         p = strchr(p,'-');
759         if (!p) continue;
760         *p++ = '\0';
761         end = p;
762         p = strchr(p,' ');
763         if (!p) continue;
764         *p++ = '\0';
765         if (strstr(p,"stack") ||
766             strstr(p,"vdso") ||
767             strstr(p,"vsyscall")) continue;
768         if (!strstr(p,"00:00")) continue;
769         if (!strstr(p,"rw")) continue;
770 
771         start_addr = strtoul(start,NULL,16);
772         end_addr = strtoul(end,NULL,16);
773         size = end_addr-start_addr;
774 
775         start_vect[regions] = start_addr;
776         size_vect[regions] = size;
777         printf("Testing %lx %lu\n", (unsigned long) start_vect[regions],
778                                     (unsigned long) size_vect[regions]);
779         regions++;
780     }
781 
782     /* Test all the regions as an unique sequential region.
783      * 1) Take the CRC64 of the memory region. */
784     for (j = 0; j < regions; j++) {
785         crc1 = crc64(crc1,(void*)start_vect[j],size_vect[j]);
786     }
787 
788     /* 2) Invert bits, swap adjacent words, swap again, invert bits.
789      * This is the error amplification step. */
790     for (j = 0; j < regions; j++)
791         memtest_non_destructive_invert((void*)start_vect[j],size_vect[j]);
792     for (j = 0; j < regions; j++)
793         memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]);
794     for (j = 0; j < regions; j++)
795         memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]);
796     for (j = 0; j < regions; j++)
797         memtest_non_destructive_invert((void*)start_vect[j],size_vect[j]);
798 
799     /* 3) Take the CRC64 sum again. */
800     for (j = 0; j < regions; j++)
801         crc2 = crc64(crc2,(void*)start_vect[j],size_vect[j]);
802 
803     /* 4) Swap + Swap again */
804     for (j = 0; j < regions; j++)
805         memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]);
806     for (j = 0; j < regions; j++)
807         memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]);
808 
809     /* 5) Take the CRC64 sum again. */
810     for (j = 0; j < regions; j++)
811         crc3 = crc64(crc3,(void*)start_vect[j],size_vect[j]);
812 
813     /* NOTE: It is very important to close the file descriptor only now
814      * because closing it before may result into unmapping of some memory
815      * region that we are testing. */
816     fclose(fp);
817 
818     /* If the two CRC are not the same, we trapped a memory error. */
819     return crc1 != crc2 || crc2 != crc3;
820 }
821 #endif
822 
823 void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
824     ucontext_t *uc = (ucontext_t*) secret;
825     sds infostring, clients;
826     struct sigaction act;
827     REDIS_NOTUSED(info);
828 
829     bugReportStart();
830     redisLog(REDIS_WARNING,
831         "    Redis %s crashed by signal: %d", REDIS_VERSION, sig);
832     redisLog(REDIS_WARNING,
833         "    Failed assertion: %s (%s:%d)", server.assert_failed,
834                         server.assert_file, server.assert_line);
835 
836     /* Log the stack trace */
837     redisLog(REDIS_WARNING, "--- STACK TRACE");
838     logStackTrace(uc);
839 
840     /* Log INFO and CLIENT LIST */
841     redisLog(REDIS_WARNING, "--- INFO OUTPUT");
842     infostring = genRedisInfoString("all");
843     infostring = sdscatprintf(infostring, "hash_init_value: %u\n",
844         dictGetHashFunctionSeed());
845     redisLogRaw(REDIS_WARNING, infostring);
846     redisLog(REDIS_WARNING, "--- CLIENT LIST OUTPUT");
847     clients = getAllClientsInfoString();
848     redisLogRaw(REDIS_WARNING, clients);
849     sdsfree(infostring);
850     sdsfree(clients);
851 
852     /* Log the current client */
853     logCurrentClient();
854 
855     /* Log dump of processor registers */
856     logRegisters(uc);
857 
858 #if defined(HAVE_PROC_MAPS)
859     /* Test memory */
860     redisLog(REDIS_WARNING, "--- FAST MEMORY TEST");
861     bioKillThreads();
862     if (memtest_test_linux_anonymous_maps()) {
863         redisLog(REDIS_WARNING,
864             "!!! MEMORY ERROR DETECTED! Check your memory ASAP !!!");
865     } else {
866         redisLog(REDIS_WARNING,
867             "Fast memory test PASSED, however your memory can still be broken. Please run a memory test for several hours if possible.");
868     }
869 #endif
870 
871     redisLog(REDIS_WARNING,
872 "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
873 "       Please report the crash by opening an issue on github:\n\n"
874 "           http://github.com/antirez/redis/issues\n\n"
875 "  Suspect RAM error? Use redis-server --test-memory to verify it.\n\n"
876 );
877     /* free(messages); Don't call free() with possibly corrupted memory. */
878     if (server.daemonize && server.supervised == 0) unlink(server.pidfile);
879 
880     /* Make sure we exit with the right signal at the end. So for instance
881      * the core will be dumped if enabled. */
882     sigemptyset (&act.sa_mask);
883     act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
884     act.sa_handler = SIG_DFL;
885     sigaction (sig, &act, NULL);
886     kill(getpid(),sig);
887 }
888 #endif /* HAVE_BACKTRACE */
889 
890 /* ==================== Logging functions for debugging ===================== */
891 
892 void redisLogHexDump(int level, char *descr, void *value, size_t len) {
893     char buf[65], *b;
894     unsigned char *v = value;
895     char charset[] = "0123456789abcdef";
896 
897     redisLog(level,"%s (hexdump):", descr);
898     b = buf;
899     while(len) {
900         b[0] = charset[(*v)>>4];
901         b[1] = charset[(*v)&0xf];
902         b[2] = '\0';
903         b += 2;
904         len--;
905         v++;
906         if (b-buf == 64 || len == 0) {
907             redisLogRaw(level|REDIS_LOG_RAW,buf);
908             b = buf;
909         }
910     }
911     redisLogRaw(level|REDIS_LOG_RAW,"\n");
912 }
913 
914 /* =========================== Software Watchdog ============================ */
915 #include <sys/time.h>
916 
917 void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) {
918 #ifdef HAVE_BACKTRACE
919     ucontext_t *uc = (ucontext_t*) secret;
920 #endif
921     REDIS_NOTUSED(info);
922     REDIS_NOTUSED(sig);
923 
924     redisLogFromHandler(REDIS_WARNING,"\n--- WATCHDOG TIMER EXPIRED ---");
925 #ifdef HAVE_BACKTRACE
926     logStackTrace(uc);
927 #else
928     redisLogFromHandler(REDIS_WARNING,"Sorry: no support for backtrace().");
929 #endif
930     redisLogFromHandler(REDIS_WARNING,"--------\n");
931 }
932 
933 /* Schedule a SIGALRM delivery after the specified period in milliseconds.
934  * If a timer is already scheduled, this function will re-schedule it to the
935  * specified time. If period is 0 the current timer is disabled. */
936 void watchdogScheduleSignal(int period) {
937     struct itimerval it;
938 
939     /* Will stop the timer if period is 0. */
940     it.it_value.tv_sec = period/1000;
941     it.it_value.tv_usec = (period%1000)*1000;
942     /* Don't automatically restart. */
943     it.it_interval.tv_sec = 0;
944     it.it_interval.tv_usec = 0;
945     setitimer(ITIMER_REAL, &it, NULL);
946 }
947 
948 /* Enable the software watchdog with the specified period in milliseconds. */
949 void enableWatchdog(int period) {
950     int min_period;
951 
952     if (server.watchdog_period == 0) {
953         struct sigaction act;
954 
955         /* Watchdog was actually disabled, so we have to setup the signal
956          * handler. */
957         sigemptyset(&act.sa_mask);
958         act.sa_flags = SA_ONSTACK | SA_SIGINFO;
959         act.sa_sigaction = watchdogSignalHandler;
960         sigaction(SIGALRM, &act, NULL);
961     }
962     /* If the configured period is smaller than twice the timer period, it is
963      * too short for the software watchdog to work reliably. Fix it now
964      * if needed. */
965     min_period = (1000/server.hz)*2;
966     if (period < min_period) period = min_period;
967     watchdogScheduleSignal(period); /* Adjust the current timer. */
968     server.watchdog_period = period;
969 }
970 
971 /* Disable the software watchdog. */
972 void disableWatchdog(void) {
973     struct sigaction act;
974     if (server.watchdog_period == 0) return; /* Already disabled. */
975     watchdogScheduleSignal(0); /* Stop the current timer. */
976 
977     /* Set the signal handler to SIG_IGN, this will also remove pending
978      * signals from the queue. */
979     sigemptyset(&act.sa_mask);
980     act.sa_flags = 0;
981     act.sa_handler = SIG_IGN;
982     sigaction(SIGALRM, &act, NULL);
983     server.watchdog_period = 0;
984 }
985