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