Back to home page

Redis cross reference

 
 

    


0001 /*
0002  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
0003  * All rights reserved.
0004  *
0005  * Redistribution and use in source and binary forms, with or without
0006  * modification, are permitted provided that the following conditions are met:
0007  *
0008  *   * Redistributions of source code must retain the above copyright notice,
0009  *     this list of conditions and the following disclaimer.
0010  *   * Redistributions in binary form must reproduce the above copyright
0011  *     notice, this list of conditions and the following disclaimer in the
0012  *     documentation and/or other materials provided with the distribution.
0013  *   * Neither the name of Redis nor the names of its contributors may be used
0014  *     to endorse or promote products derived from this software without
0015  *     specific prior written permission.
0016  *
0017  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
0018  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
0019  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
0020  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
0021  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
0022  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
0023  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
0024  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
0025  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
0026  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
0027  * POSSIBILITY OF SUCH DAMAGE.
0028  */
0029 
0030 #include "redis.h"
0031 #include "sha1.h"
0032 
0033 #include <arpa/inet.h>
0034 #include <signal.h>
0035 
0036 #ifdef HAVE_BACKTRACE
0037 #include <execinfo.h>
0038 #include <ucontext.h>
0039 #include <fcntl.h>
0040 #endif /* HAVE_BACKTRACE */
0041 
0042 /* ================================= Debugging ============================== */
0043 
0044 /* Compute the sha1 of string at 's' with 'len' bytes long.
0045  * The SHA1 is then xored against the string pointed by digest.
0046  * Since xor is commutative, this operation is used in order to
0047  * "add" digests relative to unordered elements.
0048  *
0049  * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
0050 void xorDigest(unsigned char *digest, void *ptr, size_t len) {
0051     SHA1_CTX ctx;
0052     unsigned char hash[20], *s = ptr;
0053     int j;
0054 
0055     SHA1Init(&ctx);
0056     SHA1Update(&ctx,s,len);
0057     SHA1Final(hash,&ctx);
0058 
0059     for (j = 0; j < 20; j++)
0060         digest[j] ^= hash[j];
0061 }
0062 
0063 void xorObjectDigest(unsigned char *digest, robj *o) {
0064     o = getDecodedObject(o);
0065     xorDigest(digest,o->ptr,sdslen(o->ptr));
0066     decrRefCount(o);
0067 }
0068 
0069 /* This function instead of just computing the SHA1 and xoring it
0070  * against digest, also perform the digest of "digest" itself and
0071  * replace the old value with the new one.
0072  *
0073  * So the final digest will be:
0074  *
0075  * digest = SHA1(digest xor SHA1(data))
0076  *
0077  * This function is used every time we want to preserve the order so
0078  * that digest(a,b,c,d) will be different than digest(b,c,d,a)
0079  *
0080  * Also note that mixdigest("foo") followed by mixdigest("bar")
0081  * will lead to a different digest compared to "fo", "obar".
0082  */
0083 void mixDigest(unsigned char *digest, void *ptr, size_t len) {
0084     SHA1_CTX ctx;
0085     char *s = ptr;
0086 
0087     xorDigest(digest,s,len);
0088     SHA1Init(&ctx);
0089     SHA1Update(&ctx,digest,20);
0090     SHA1Final(digest,&ctx);
0091 }
0092 
0093 void mixObjectDigest(unsigned char *digest, robj *o) {
0094     o = getDecodedObject(o);
0095     mixDigest(digest,o->ptr,sdslen(o->ptr));
0096     decrRefCount(o);
0097 }
0098 
0099 /* Compute the dataset digest. Since keys, sets elements, hashes elements
0100  * are not ordered, we use a trick: every aggregate digest is the xor
0101  * of the digests of their elements. This way the order will not change
0102  * the result. For list instead we use a feedback entering the output digest
0103  * as input in order to ensure that a different ordered list will result in
0104  * a different digest. */
0105 void computeDatasetDigest(unsigned char *final) {
0106     unsigned char digest[20];
0107     char buf[128];
0108     dictIterator *di = NULL;
0109     dictEntry *de;
0110     int j;
0111     uint32_t aux;
0112 
0113     memset(final,0,20); /* Start with a clean result */
0114 
0115     for (j = 0; j < server.dbnum; j++) {
0116         redisDb *db = server.db+j;
0117 
0118         if (dictSize(db->dict) == 0) continue;
0119         di = dictGetIterator(db->dict);
0120 
0121         /* hash the DB id, so the same dataset moved in a different
0122          * DB will lead to a different digest */
0123         aux = htonl(j);
0124         mixDigest(final,&aux,sizeof(aux));
0125 
0126         /* Iterate this DB writing every entry */
0127         while((de = dictNext(di)) != NULL) {
0128             sds key;
0129             robj *keyobj, *o;
0130             long long expiretime;
0131 
0132             memset(digest,0,20); /* This key-val digest */
0133             key = dictGetKey(de);
0134             keyobj = createStringObject(key,sdslen(key));
0135 
0136             mixDigest(digest,key,sdslen(key));
0137 
0138             o = dictGetVal(de);
0139 
0140             aux = htonl(o->type);
0141             mixDigest(digest,&aux,sizeof(aux));
0142             expiretime = getExpire(db,keyobj);
0143 
0144             /* Save the key and associated value */
0145             if (o->type == REDIS_STRING) {
0146                 mixObjectDigest(digest,o);
0147             } else if (o->type == REDIS_LIST) {
0148                 listTypeIterator *li = listTypeInitIterator(o,0,REDIS_TAIL);
0149                 listTypeEntry entry;
0150                 while(listTypeNext(li,&entry)) {
0151                     robj *eleobj = listTypeGet(&entry);
0152                     mixObjectDigest(digest,eleobj);
0153                     decrRefCount(eleobj);
0154                 }
0155                 listTypeReleaseIterator(li);
0156             } else if (o->type == REDIS_SET) {
0157                 setTypeIterator *si = setTypeInitIterator(o);
0158                 robj *ele;
0159                 while((ele = setTypeNextObject(si)) != NULL) {
0160                     xorObjectDigest(digest,ele);
0161                     decrRefCount(ele);
0162                 }
0163                 setTypeReleaseIterator(si);
0164             } else if (o->type == REDIS_ZSET) {
0165                 unsigned char eledigest[20];
0166 
0167                 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
0168                     unsigned char *zl = o->ptr;
0169                     unsigned char *eptr, *sptr;
0170                     unsigned char *vstr;
0171                     unsigned int vlen;
0172                     long long vll;
0173                     double score;
0174 
0175                     eptr = ziplistIndex(zl,0);
0176                     redisAssert(eptr != NULL);
0177                     sptr = ziplistNext(zl,eptr);
0178                     redisAssert(sptr != NULL);
0179 
0180                     while (eptr != NULL) {
0181                         redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
0182                         score = zzlGetScore(sptr);
0183 
0184                         memset(eledigest,0,20);
0185                         if (vstr != NULL) {
0186                             mixDigest(eledigest,vstr,vlen);
0187                         } else {
0188                             ll2string(buf,sizeof(buf),vll);
0189                             mixDigest(eledigest,buf,strlen(buf));
0190                         }
0191 
0192                         snprintf(buf,sizeof(buf),"%.17g",score);
0193                         mixDigest(eledigest,buf,strlen(buf));
0194                         xorDigest(digest,eledigest,20);
0195                         zzlNext(zl,&eptr,&sptr);
0196                     }
0197                 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
0198                     zset *zs = o->ptr;
0199                     dictIterator *di = dictGetIterator(zs->dict);
0200                     dictEntry *de;
0201 
0202                     while((de = dictNext(di)) != NULL) {
0203                         robj *eleobj = dictGetKey(de);
0204                         double *score = dictGetVal(de);
0205 
0206                         snprintf(buf,sizeof(buf),"%.17g",*score);
0207                         memset(eledigest,0,20);
0208                         mixObjectDigest(eledigest,eleobj);
0209                         mixDigest(eledigest,buf,strlen(buf));
0210                         xorDigest(digest,eledigest,20);
0211                     }
0212                     dictReleaseIterator(di);
0213                 } else {
0214                     redisPanic("Unknown sorted set encoding");
0215                 }
0216             } else if (o->type == REDIS_HASH) {
0217                 hashTypeIterator *hi;
0218                 robj *obj;
0219 
0220                 hi = hashTypeInitIterator(o);
0221                 while (hashTypeNext(hi) != REDIS_ERR) {
0222                     unsigned char eledigest[20];
0223 
0224                     memset(eledigest,0,20);
0225                     obj = hashTypeCurrentObject(hi,REDIS_HASH_KEY);
0226                     mixObjectDigest(eledigest,obj);
0227                     decrRefCount(obj);
0228                     obj = hashTypeCurrentObject(hi,REDIS_HASH_VALUE);
0229                     mixObjectDigest(eledigest,obj);
0230                     decrRefCount(obj);
0231                     xorDigest(digest,eledigest,20);
0232                 }
0233                 hashTypeReleaseIterator(hi);
0234             } else {
0235                 redisPanic("Unknown object type");
0236             }
0237             /* If the key has an expire, add it to the mix */
0238             if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
0239             /* We can finally xor the key-val digest to the final digest */
0240             xorDigest(final,digest,20);
0241             decrRefCount(keyobj);
0242         }
0243         dictReleaseIterator(di);
0244     }
0245 }
0246 
0247 void debugCommand(redisClient *c) {
0248     if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
0249         *((char*)-1) = 'x';
0250     } else if (!strcasecmp(c->argv[1]->ptr,"oom")) {
0251         void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */
0252         zfree(ptr);
0253         addReply(c,shared.ok);
0254     } else if (!strcasecmp(c->argv[1]->ptr,"assert")) {
0255         if (c->argc >= 3) c->argv[2] = tryObjectEncoding(c->argv[2]);
0256         redisAssertWithInfo(c,c->argv[0],1 == 2);
0257     } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
0258         if (rdbSave(server.rdb_filename) != REDIS_OK) {
0259             addReply(c,shared.err);
0260             return;
0261         }
0262         emptyDb();
0263         if (rdbLoad(server.rdb_filename) != REDIS_OK) {
0264             addReplyError(c,"Error trying to load the RDB dump");
0265             return;
0266         }
0267         redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
0268         addReply(c,shared.ok);
0269     } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
0270         emptyDb();
0271         if (loadAppendOnlyFile(server.aof_filename) != REDIS_OK) {
0272             addReply(c,shared.err);
0273             return;
0274         }
0275         server.dirty = 0; /* Prevent AOF / replication */
0276         redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
0277         addReply(c,shared.ok);
0278     } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
0279         dictEntry *de;
0280         robj *val;
0281         char *strenc;
0282 
0283         if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {
0284             addReply(c,shared.nokeyerr);
0285             return;
0286         }
0287         val = dictGetVal(de);
0288         strenc = strEncoding(val->encoding);
0289 
0290         addReplyStatusFormat(c,
0291             "Value at:%p refcount:%d "
0292             "encoding:%s serializedlength:%lld "
0293             "lru:%d lru_seconds_idle:%lu",
0294             (void*)val, val->refcount,
0295             strenc, (long long) rdbSavedObjectLen(val),
0296             val->lru, estimateObjectIdleTime(val));
0297     } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
0298         long keys, j;
0299         robj *key, *val;
0300         char buf[128];
0301 
0302         if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
0303             return;
0304         for (j = 0; j < keys; j++) {
0305             snprintf(buf,sizeof(buf),"key:%lu",j);
0306             key = createStringObject(buf,strlen(buf));
0307             if (lookupKeyRead(c->db,key) != NULL) {
0308                 decrRefCount(key);
0309                 continue;
0310             }
0311             snprintf(buf,sizeof(buf),"value:%lu",j);
0312             val = createStringObject(buf,strlen(buf));
0313             dbAdd(c->db,key,val);
0314             decrRefCount(key);
0315         }
0316         addReply(c,shared.ok);
0317     } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
0318         unsigned char digest[20];
0319         sds d = sdsempty();
0320         int j;
0321 
0322         computeDatasetDigest(digest);
0323         for (j = 0; j < 20; j++)
0324             d = sdscatprintf(d, "%02x",digest[j]);
0325         addReplyStatus(c,d);
0326         sdsfree(d);
0327     } else if (!strcasecmp(c->argv[1]->ptr,"sleep") && c->argc == 3) {
0328         double dtime = strtod(c->argv[2]->ptr,NULL);
0329         long long utime = dtime*1000000;
0330 
0331         usleep(utime);
0332         addReply(c,shared.ok);
0333     } else if (!strcasecmp(c->argv[1]->ptr,"set-active-expire") &&
0334                c->argc == 3)
0335     {
0336         server.active_expire_enabled = atoi(c->argv[2]->ptr);
0337         addReply(c,shared.ok);
0338     } else {
0339         addReplyErrorFormat(c, "Unknown DEBUG subcommand or wrong number of arguments for '%s'",
0340             (char*)c->argv[1]->ptr);
0341     }
0342 }
0343 
0344 /* =========================== Crash handling  ============================== */
0345 
0346 void _redisAssert(char *estr, char *file, int line) {
0347     bugReportStart();
0348     redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
0349     redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
0350 #ifdef HAVE_BACKTRACE
0351     server.assert_failed = estr;
0352     server.assert_file = file;
0353     server.assert_line = line;
0354     redisLog(REDIS_WARNING,"(forcing SIGSEGV to print the bug report.)");
0355 #endif
0356     *((char*)-1) = 'x';
0357 }
0358 
0359 void _redisAssertPrintClientInfo(redisClient *c) {
0360     int j;
0361 
0362     bugReportStart();
0363     redisLog(REDIS_WARNING,"=== ASSERTION FAILED CLIENT CONTEXT ===");
0364     redisLog(REDIS_WARNING,"client->flags = %d", c->flags);
0365     redisLog(REDIS_WARNING,"client->fd = %d", c->fd);
0366     redisLog(REDIS_WARNING,"client->argc = %d", c->argc);
0367     for (j=0; j < c->argc; j++) {
0368         char buf[128];
0369         char *arg;
0370 
0371         if (c->argv[j]->type == REDIS_STRING &&
0372             c->argv[j]->encoding == REDIS_ENCODING_RAW)
0373         {
0374             arg = (char*) c->argv[j]->ptr;
0375         } else {
0376             snprintf(buf,sizeof(buf),"Object type: %d, encoding: %d",
0377                 c->argv[j]->type, c->argv[j]->encoding);
0378             arg = buf;
0379         }
0380         redisLog(REDIS_WARNING,"client->argv[%d] = \"%s\" (refcount: %d)",
0381             j, arg, c->argv[j]->refcount);
0382     }
0383 }
0384 
0385 void redisLogObjectDebugInfo(robj *o) {
0386     redisLog(REDIS_WARNING,"Object type: %d", o->type);
0387     redisLog(REDIS_WARNING,"Object encoding: %d", o->encoding);
0388     redisLog(REDIS_WARNING,"Object refcount: %d", o->refcount);
0389     if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_RAW) {
0390         redisLog(REDIS_WARNING,"Object raw string len: %d", sdslen(o->ptr));
0391         if (sdslen(o->ptr) < 4096)
0392             redisLog(REDIS_WARNING,"Object raw string content: \"%s\"", (char*)o->ptr);
0393     } else if (o->type == REDIS_LIST) {
0394         redisLog(REDIS_WARNING,"List length: %d", (int) listTypeLength(o));
0395     } else if (o->type == REDIS_SET) {
0396         redisLog(REDIS_WARNING,"Set size: %d", (int) setTypeSize(o));
0397     } else if (o->type == REDIS_HASH) {
0398         redisLog(REDIS_WARNING,"Hash size: %d", (int) hashTypeLength(o));
0399     } else if (o->type == REDIS_ZSET) {
0400         redisLog(REDIS_WARNING,"Sorted set size: %d", (int) zsetLength(o));
0401         if (o->encoding == REDIS_ENCODING_SKIPLIST)
0402             redisLog(REDIS_WARNING,"Skiplist level: %d", (int) ((zset*)o->ptr)->zsl->level);
0403     }
0404 }
0405 
0406 void _redisAssertPrintObject(robj *o) {
0407     bugReportStart();
0408     redisLog(REDIS_WARNING,"=== ASSERTION FAILED OBJECT CONTEXT ===");
0409     redisLogObjectDebugInfo(o);
0410 }
0411 
0412 void _redisAssertWithInfo(redisClient *c, robj *o, char *estr, char *file, int line) {
0413     if (c) _redisAssertPrintClientInfo(c);
0414     if (o) _redisAssertPrintObject(o);
0415     _redisAssert(estr,file,line);
0416 }
0417 
0418 void _redisPanic(char *msg, char *file, int line) {
0419     bugReportStart();
0420     redisLog(REDIS_WARNING,"------------------------------------------------");
0421     redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
0422     redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
0423 #ifdef HAVE_BACKTRACE
0424     redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
0425 #endif
0426     redisLog(REDIS_WARNING,"------------------------------------------------");
0427     *((char*)-1) = 'x';
0428 }
0429 
0430 void bugReportStart(void) {
0431     if (server.bug_report_start == 0) {
0432         redisLog(REDIS_WARNING,
0433             "\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ===");
0434         server.bug_report_start = 1;
0435     }
0436 }
0437 
0438 #ifdef HAVE_BACKTRACE
0439 static void *getMcontextEip(ucontext_t *uc) {
0440 #if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
0441     /* OSX < 10.6 */
0442     #if defined(__x86_64__)
0443     return (void*) uc->uc_mcontext->__ss.__rip;
0444     #elif defined(__i386__)
0445     return (void*) uc->uc_mcontext->__ss.__eip;
0446     #else
0447     return (void*) uc->uc_mcontext->__ss.__srr0;
0448     #endif
0449 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
0450     /* OSX >= 10.6 */
0451     #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
0452     return (void*) uc->uc_mcontext->__ss.__rip;
0453     #else
0454     return (void*) uc->uc_mcontext->__ss.__eip;
0455     #endif
0456 #elif defined(__linux__)
0457     /* Linux */
0458     #if defined(__i386__)
0459     return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
0460     #elif defined(__X86_64__) || defined(__x86_64__)
0461     return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
0462     #elif defined(__ia64__) /* Linux IA64 */
0463     return (void*) uc->uc_mcontext.sc_ip;
0464     #endif
0465 #else
0466     return NULL;
0467 #endif
0468 }
0469 
0470 void logStackContent(void **sp) {
0471     int i;
0472     for (i = 15; i >= 0; i--) {
0473         if (sizeof(long) == 4)
0474             redisLog(REDIS_WARNING, "(%08lx) -> %08lx", sp+i, sp[i]);
0475         else
0476             redisLog(REDIS_WARNING, "(%016lx) -> %016lx", sp+i, sp[i]);
0477     }
0478 }
0479 
0480 void logRegisters(ucontext_t *uc) {
0481     redisLog(REDIS_WARNING, "--- REGISTERS");
0482 
0483 /* OSX */
0484 #if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
0485   /* OSX AMD64 */
0486     #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
0487     redisLog(REDIS_WARNING,
0488     "\n"
0489     "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
0490     "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
0491     "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
0492     "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
0493     "RIP:%016lx EFL:%016lx\nCS :%016lx FS:%016lx  GS:%016lx",
0494         uc->uc_mcontext->__ss.__rax,
0495         uc->uc_mcontext->__ss.__rbx,
0496         uc->uc_mcontext->__ss.__rcx,
0497         uc->uc_mcontext->__ss.__rdx,
0498         uc->uc_mcontext->__ss.__rdi,
0499         uc->uc_mcontext->__ss.__rsi,
0500         uc->uc_mcontext->__ss.__rbp,
0501         uc->uc_mcontext->__ss.__rsp,
0502         uc->uc_mcontext->__ss.__r8,
0503         uc->uc_mcontext->__ss.__r9,
0504         uc->uc_mcontext->__ss.__r10,
0505         uc->uc_mcontext->__ss.__r11,
0506         uc->uc_mcontext->__ss.__r12,
0507         uc->uc_mcontext->__ss.__r13,
0508         uc->uc_mcontext->__ss.__r14,
0509         uc->uc_mcontext->__ss.__r15,
0510         uc->uc_mcontext->__ss.__rip,
0511         uc->uc_mcontext->__ss.__rflags,
0512         uc->uc_mcontext->__ss.__cs,
0513         uc->uc_mcontext->__ss.__fs,
0514         uc->uc_mcontext->__ss.__gs
0515     );
0516     logStackContent((void**)uc->uc_mcontext->__ss.__rsp);
0517     #else
0518     /* OSX x86 */
0519     redisLog(REDIS_WARNING,
0520     "\n"
0521     "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
0522     "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
0523     "SS:%08lx  EFL:%08lx EIP:%08lx CS :%08lx\n"
0524     "DS:%08lx  ES:%08lx  FS :%08lx GS :%08lx",
0525         uc->uc_mcontext->__ss.__eax,
0526         uc->uc_mcontext->__ss.__ebx,
0527         uc->uc_mcontext->__ss.__ecx,
0528         uc->uc_mcontext->__ss.__edx,
0529         uc->uc_mcontext->__ss.__edi,
0530         uc->uc_mcontext->__ss.__esi,
0531         uc->uc_mcontext->__ss.__ebp,
0532         uc->uc_mcontext->__ss.__esp,
0533         uc->uc_mcontext->__ss.__ss,
0534         uc->uc_mcontext->__ss.__eflags,
0535         uc->uc_mcontext->__ss.__eip,
0536         uc->uc_mcontext->__ss.__cs,
0537         uc->uc_mcontext->__ss.__ds,
0538         uc->uc_mcontext->__ss.__es,
0539         uc->uc_mcontext->__ss.__fs,
0540         uc->uc_mcontext->__ss.__gs
0541     );
0542     logStackContent((void**)uc->uc_mcontext->__ss.__esp);
0543     #endif
0544 /* Linux */
0545 #elif defined(__linux__)
0546     /* Linux x86 */
0547     #if defined(__i386__)
0548     redisLog(REDIS_WARNING,
0549     "\n"
0550     "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
0551     "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
0552     "SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\n"
0553     "DS :%08lx ES :%08lx FS :%08lx GS:%08lx",
0554         uc->uc_mcontext.gregs[11],
0555         uc->uc_mcontext.gregs[8],
0556         uc->uc_mcontext.gregs[10],
0557         uc->uc_mcontext.gregs[9],
0558         uc->uc_mcontext.gregs[4],
0559         uc->uc_mcontext.gregs[5],
0560         uc->uc_mcontext.gregs[6],
0561         uc->uc_mcontext.gregs[7],
0562         uc->uc_mcontext.gregs[18],
0563         uc->uc_mcontext.gregs[17],
0564         uc->uc_mcontext.gregs[14],
0565         uc->uc_mcontext.gregs[15],
0566         uc->uc_mcontext.gregs[3],
0567         uc->uc_mcontext.gregs[2],
0568         uc->uc_mcontext.gregs[1],
0569         uc->uc_mcontext.gregs[0]
0570     );
0571     logStackContent((void**)uc->uc_mcontext.gregs[7]);
0572     #elif defined(__X86_64__) || defined(__x86_64__)
0573     /* Linux AMD64 */
0574     redisLog(REDIS_WARNING,
0575     "\n"
0576     "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
0577     "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
0578     "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
0579     "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
0580     "RIP:%016lx EFL:%016lx\nCSGSFS:%016lx",
0581         uc->uc_mcontext.gregs[13],
0582         uc->uc_mcontext.gregs[11],
0583         uc->uc_mcontext.gregs[14],
0584         uc->uc_mcontext.gregs[12],
0585         uc->uc_mcontext.gregs[8],
0586         uc->uc_mcontext.gregs[9],
0587         uc->uc_mcontext.gregs[10],
0588         uc->uc_mcontext.gregs[15],
0589         uc->uc_mcontext.gregs[0],
0590         uc->uc_mcontext.gregs[1],
0591         uc->uc_mcontext.gregs[2],
0592         uc->uc_mcontext.gregs[3],
0593         uc->uc_mcontext.gregs[4],
0594         uc->uc_mcontext.gregs[5],
0595         uc->uc_mcontext.gregs[6],
0596         uc->uc_mcontext.gregs[7],
0597         uc->uc_mcontext.gregs[16],
0598         uc->uc_mcontext.gregs[17],
0599         uc->uc_mcontext.gregs[18]
0600     );
0601     logStackContent((void**)uc->uc_mcontext.gregs[15]);
0602     #endif
0603 #else
0604     redisLog(REDIS_WARNING,
0605         "  Dumping of registers not supported for this OS/arch");
0606 #endif
0607 }
0608 
0609 /* Logs the stack trace using the backtrace() call. This function is designed
0610  * to be called from signal handlers safely. */
0611 void logStackTrace(ucontext_t *uc) {
0612     void *trace[100];
0613     int trace_size = 0, fd;
0614 
0615     /* Open the log file in append mode. */
0616     fd = server.logfile ?
0617         open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644) :
0618         STDOUT_FILENO;
0619     if (fd == -1) return;
0620 
0621     /* Generate the stack trace */
0622     trace_size = backtrace(trace, 100);
0623 
0624     /* overwrite sigaction with caller's address */
0625     if (getMcontextEip(uc) != NULL)
0626         trace[1] = getMcontextEip(uc);
0627 
0628     /* Write symbols to log file */
0629     backtrace_symbols_fd(trace, trace_size, fd);
0630 
0631     /* Cleanup */
0632     if (server.logfile) close(fd);
0633 }
0634 
0635 /* Log information about the "current" client, that is, the client that is
0636  * currently being served by Redis. May be NULL if Redis is not serving a
0637  * client right now. */
0638 void logCurrentClient(void) {
0639     if (server.current_client == NULL) return;
0640 
0641     redisClient *cc = server.current_client;
0642     sds client;
0643     int j;
0644 
0645     redisLog(REDIS_WARNING, "--- CURRENT CLIENT INFO");
0646     client = getClientInfoString(cc);
0647     redisLog(REDIS_WARNING,"client: %s", client);
0648     sdsfree(client);
0649     for (j = 0; j < cc->argc; j++) {
0650         robj *decoded;
0651 
0652         decoded = getDecodedObject(cc->argv[j]);
0653         redisLog(REDIS_WARNING,"argv[%d]: '%s'", j, (char*)decoded->ptr);
0654         decrRefCount(decoded);
0655     }
0656     /* Check if the first argument, usually a key, is found inside the
0657      * selected DB, and if so print info about the associated object. */
0658     if (cc->argc >= 1) {
0659         robj *val, *key;
0660         dictEntry *de;
0661 
0662         key = getDecodedObject(cc->argv[1]);
0663         de = dictFind(cc->db->dict, key->ptr);
0664         if (de) {
0665             val = dictGetVal(de);
0666             redisLog(REDIS_WARNING,"key '%s' found in DB containing the following object:", key->ptr);
0667             redisLogObjectDebugInfo(val);
0668         }
0669         decrRefCount(key);
0670     }
0671 }
0672 
0673 void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
0674     ucontext_t *uc = (ucontext_t*) secret;
0675     sds infostring, clients;
0676     struct sigaction act;
0677     REDIS_NOTUSED(info);
0678 
0679     bugReportStart();
0680     redisLog(REDIS_WARNING,
0681         "    Redis %s crashed by signal: %d", REDIS_VERSION, sig);
0682     redisLog(REDIS_WARNING,
0683         "    Failed assertion: %s (%s:%d)", server.assert_failed,
0684                         server.assert_file, server.assert_line);
0685 
0686     /* Log the stack trace */
0687     redisLog(REDIS_WARNING, "--- STACK TRACE");
0688     logStackTrace(uc);
0689 
0690     /* Log INFO and CLIENT LIST */
0691     redisLog(REDIS_WARNING, "--- INFO OUTPUT");
0692     infostring = genRedisInfoString("all");
0693     infostring = sdscatprintf(infostring, "hash_init_value: %u\n",
0694         dictGetHashFunctionSeed());
0695     redisLogRaw(REDIS_WARNING, infostring);
0696     redisLog(REDIS_WARNING, "--- CLIENT LIST OUTPUT");
0697     clients = getAllClientsInfoString();
0698     redisLogRaw(REDIS_WARNING, clients);
0699     sdsfree(infostring);
0700     sdsfree(clients);
0701 
0702     /* Log the current client */
0703     logCurrentClient();
0704 
0705     /* Log dump of processor registers */
0706     logRegisters(uc);
0707 
0708     redisLog(REDIS_WARNING,
0709 "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
0710 "       Please report the crash opening an issue on github:\n\n"
0711 "           http://github.com/antirez/redis/issues\n\n"
0712 "  Suspect RAM error? Use redis-server --test-memory to veryfy it.\n\n"
0713 );
0714     /* free(messages); Don't call free() with possibly corrupted memory. */
0715     if (server.daemonize) unlink(server.pidfile);
0716 
0717     /* Make sure we exit with the right signal at the end. So for instance
0718      * the core will be dumped if enabled. */
0719     sigemptyset (&act.sa_mask);
0720     act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
0721     act.sa_handler = SIG_DFL;
0722     sigaction (sig, &act, NULL);
0723     kill(getpid(),sig);
0724 }
0725 #endif /* HAVE_BACKTRACE */
0726 
0727 /* ==================== Logging functions for debugging ===================== */
0728 
0729 void redisLogHexDump(int level, char *descr, void *value, size_t len) {
0730     char buf[65], *b;
0731     unsigned char *v = value;
0732     char charset[] = "0123456789abcdef";
0733 
0734     redisLog(level,"%s (hexdump):", descr);
0735     b = buf;
0736     while(len) {
0737         b[0] = charset[(*v)>>4];
0738         b[1] = charset[(*v)&0xf];
0739         b[2] = '\0';
0740         b += 2;
0741         len--;
0742         v++;
0743         if (b-buf == 64 || len == 0) {
0744             redisLogRaw(level|REDIS_LOG_RAW,buf);
0745             b = buf;
0746         }
0747     }
0748     redisLogRaw(level|REDIS_LOG_RAW,"\n");
0749 }
0750 
0751 /* =========================== Software Watchdog ============================ */
0752 #include <sys/time.h>
0753 
0754 void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) {
0755 #ifdef HAVE_BACKTRACE
0756     ucontext_t *uc = (ucontext_t*) secret;
0757 #endif
0758     REDIS_NOTUSED(info);
0759     REDIS_NOTUSED(sig);
0760 
0761     redisLogFromHandler(REDIS_WARNING,"\n--- WATCHDOG TIMER EXPIRED ---");
0762 #ifdef HAVE_BACKTRACE
0763     logStackTrace(uc);
0764 #else
0765     redisLogFromHandler(REDIS_WARNING,"Sorry: no support for backtrace().");
0766 #endif
0767     redisLogFromHandler(REDIS_WARNING,"--------\n");
0768 }
0769 
0770 /* Schedule a SIGALRM delivery after the specified period in milliseconds.
0771  * If a timer is already scheduled, this function will re-schedule it to the
0772  * specified time. If period is 0 the current timer is disabled. */
0773 void watchdogScheduleSignal(int period) {
0774     struct itimerval it;
0775 
0776     /* Will stop the timer if period is 0. */
0777     it.it_value.tv_sec = period/1000;
0778     it.it_value.tv_usec = (period%1000)*1000;
0779     /* Don't automatically restart. */
0780     it.it_interval.tv_sec = 0;
0781     it.it_interval.tv_usec = 0;
0782     setitimer(ITIMER_REAL, &it, NULL);
0783 }
0784 
0785 /* Enable the software watchdong with the specified period in milliseconds. */
0786 void enableWatchdog(int period) {
0787     int min_period;
0788 
0789     if (server.watchdog_period == 0) {
0790         struct sigaction act;
0791 
0792         /* Watchdog was actually disabled, so we have to setup the signal
0793          * handler. */
0794         sigemptyset(&act.sa_mask);
0795         act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_SIGINFO;
0796         act.sa_sigaction = watchdogSignalHandler;
0797         sigaction(SIGALRM, &act, NULL);
0798     }
0799     /* If the configured period is smaller than twice the timer period, it is
0800      * too short for the software watchdog to work reliably. Fix it now
0801      * if needed. */
0802     min_period = (1000/server.hz)*2;
0803     if (period < min_period) period = min_period;
0804     watchdogScheduleSignal(period); /* Adjust the current timer. */
0805     server.watchdog_period = period;
0806 }
0807 
0808 /* Disable the software watchdog. */
0809 void disableWatchdog(void) {
0810     struct sigaction act;
0811     if (server.watchdog_period == 0) return; /* Already disabled. */
0812     watchdogScheduleSignal(0); /* Stop the current timer. */
0813 
0814     /* Set the signal handler to SIG_IGN, this will also remove pending
0815      * signals from the queue. */
0816     sigemptyset(&act.sa_mask);
0817     act.sa_flags = 0;
0818     act.sa_handler = SIG_IGN;
0819     sigaction(SIGALRM, &act, NULL);
0820     server.watchdog_period = 0;
0821 }