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 debugCommand(redisClient *c) { 256 if (!strcasecmp(c->argv[1]->ptr,"segfault")) { 257 *((char*)-1) = 'x'; 258 } else if (!strcasecmp(c->argv[1]->ptr,"oom")) { 259 void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */ 260 zfree(ptr); 261 addReply(c,shared.ok); 262 } else if (!strcasecmp(c->argv[1]->ptr,"assert")) { 263 if (c->argc >= 3) c->argv[2] = tryObjectEncoding(c->argv[2]); 264 redisAssertWithInfo(c,c->argv[0],1 == 2); 265 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) { 266 if (rdbSave(server.rdb_filename) != REDIS_OK) { 267 addReply(c,shared.err); 268 return; 269 } 270 emptyDb(NULL); 271 if (rdbLoad(server.rdb_filename) != REDIS_OK) { 272 addReplyError(c,"Error trying to load the RDB dump"); 273 return; 274 } 275 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD"); 276 addReply(c,shared.ok); 277 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) { 278 emptyDb(NULL); 279 if (loadAppendOnlyFile(server.aof_filename) != REDIS_OK) { 280 addReply(c,shared.err); 281 return; 282 } 283 server.dirty = 0; /* Prevent AOF / replication */ 284 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF"); 285 addReply(c,shared.ok); 286 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) { 287 dictEntry *de; 288 robj *val; 289 char *strenc; 290 291 if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) { 292 addReply(c,shared.nokeyerr); 293 return; 294 } 295 val = dictGetVal(de); 296 strenc = strEncoding(val->encoding); 297 298 addReplyStatusFormat(c, 299 "Value at:%p refcount:%d " 300 "encoding:%s serializedlength:%lld " 301 "lru:%d lru_seconds_idle:%llu", 302 (void*)val, val->refcount, 303 strenc, (long long) rdbSavedObjectLen(val), 304 val->lru, estimateObjectIdleTime(val)); 305 } else if (!strcasecmp(c->argv[1]->ptr,"sdslen") && c->argc == 3) { 306 dictEntry *de; 307 robj *val; 308 sds key; 309 310 if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) { 311 addReply(c,shared.nokeyerr); 312 return; 313 } 314 val = dictGetVal(de); 315 key = dictGetKey(de); 316 317 if (val->type != REDIS_STRING || !sdsEncodedObject(val)) { 318 addReplyError(c,"Not an sds encoded string."); 319 } else { 320 addReplyStatusFormat(c, 321 "key_sds_len:%lld, key_sds_avail:%lld, " 322 "val_sds_len:%lld, val_sds_avail:%lld", 323 (long long) sdslen(key), 324 (long long) sdsavail(key), 325 (long long) sdslen(val->ptr), 326 (long long) sdsavail(val->ptr)); 327 } 328 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) { 329 long keys, j; 330 robj *key, *val; 331 char buf[128]; 332 333 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK) 334 return; 335 dictExpand(c->db->dict,keys); 336 for (j = 0; j < keys; j++) { 337 snprintf(buf,sizeof(buf),"key:%lu",j); 338 key = createStringObject(buf,strlen(buf)); 339 if (lookupKeyRead(c->db,key) != NULL) { 340 decrRefCount(key); 341 continue; 342 } 343 snprintf(buf,sizeof(buf),"value:%lu",j); 344 val = createStringObject(buf,strlen(buf)); 345 dbAdd(c->db,key,val); 346 decrRefCount(key); 347 } 348 addReply(c,shared.ok); 349 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) { 350 unsigned char digest[20]; 351 sds d = sdsempty(); 352 int j; 353 354 computeDatasetDigest(digest); 355 for (j = 0; j < 20; j++) 356 d = sdscatprintf(d, "%02x",digest[j]); 357 addReplyStatus(c,d); 358 sdsfree(d); 359 } else if (!strcasecmp(c->argv[1]->ptr,"sleep") && c->argc == 3) { 360 double dtime = strtod(c->argv[2]->ptr,NULL); 361 long long utime = dtime*1000000; 362 struct timespec tv; 363 364 tv.tv_sec = utime / 1000000; 365 tv.tv_nsec = (utime % 1000000) * 1000; 366 nanosleep(&tv, NULL); 367 addReply(c,shared.ok); 368 } else if (!strcasecmp(c->argv[1]->ptr,"set-active-expire") && 369 c->argc == 3) 370 { 371 server.active_expire_enabled = atoi(c->argv[2]->ptr); 372 addReply(c,shared.ok); 373 } else if (!strcasecmp(c->argv[1]->ptr,"cmdkeys") && c->argc >= 3) { 374 struct redisCommand *cmd = lookupCommand(c->argv[2]->ptr); 375 int *keys, numkeys, j; 376 377 if (!cmd) { 378 addReplyError(c,"Invalid command specified"); 379 return; 380 } else if ((cmd->arity > 0 && cmd->arity != c->argc-2) || 381 ((c->argc-2) < -cmd->arity)) 382 { 383 addReplyError(c,"Invalid number of arguments specified for command"); 384 return; 385 } 386 387 keys = getKeysFromCommand(cmd,c->argv+2,c->argc-2,&numkeys); 388 addReplyMultiBulkLen(c,numkeys); 389 for (j = 0; j < numkeys; j++) addReplyBulk(c,c->argv[keys[j]+2]); 390 getKeysFreeResult(keys); 391 } else if (!strcasecmp(c->argv[1]->ptr,"error") && c->argc == 3) { 392 sds errstr = sdsnewlen("-",1); 393 394 errstr = sdscatsds(errstr,c->argv[2]->ptr); 395 errstr = sdsmapchars(errstr,"\n\r"," ",2); /* no newlines in errors. */ 396 errstr = sdscatlen(errstr,"\r\n",2); 397 addReplySds(c,errstr); 398 } else { 399 addReplyErrorFormat(c, "Unknown DEBUG subcommand or wrong number of arguments for '%s'", 400 (char*)c->argv[1]->ptr); 401 } 402 } 403 404 /* =========================== Crash handling ============================== */ 405 406 void _redisAssert(char *estr, char *file, int line) { 407 bugReportStart(); 408 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ==="); 409 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr); 410 #ifdef HAVE_BACKTRACE 411 server.assert_failed = estr; 412 server.assert_file = file; 413 server.assert_line = line; 414 redisLog(REDIS_WARNING,"(forcing SIGSEGV to print the bug report.)"); 415 #endif 416 *((char*)-1) = 'x'; 417 } 418 419 void _redisAssertPrintClientInfo(redisClient *c) { 420 int j; 421 422 bugReportStart(); 423 redisLog(REDIS_WARNING,"=== ASSERTION FAILED CLIENT CONTEXT ==="); 424 redisLog(REDIS_WARNING,"client->flags = %d", c->flags); 425 redisLog(REDIS_WARNING,"client->fd = %d", c->fd); 426 redisLog(REDIS_WARNING,"client->argc = %d", c->argc); 427 for (j=0; j < c->argc; j++) { 428 char buf[128]; 429 char *arg; 430 431 if (c->argv[j]->type == REDIS_STRING && sdsEncodedObject(c->argv[j])) { 432 arg = (char*) c->argv[j]->ptr; 433 } else { 434 snprintf(buf,sizeof(buf),"Object type: %d, encoding: %d", 435 c->argv[j]->type, c->argv[j]->encoding); 436 arg = buf; 437 } 438 redisLog(REDIS_WARNING,"client->argv[%d] = \"%s\" (refcount: %d)", 439 j, arg, c->argv[j]->refcount); 440 } 441 } 442 443 void redisLogObjectDebugInfo(robj *o) { 444 redisLog(REDIS_WARNING,"Object type: %d", o->type); 445 redisLog(REDIS_WARNING,"Object encoding: %d", o->encoding); 446 redisLog(REDIS_WARNING,"Object refcount: %d", o->refcount); 447 if (o->type == REDIS_STRING && sdsEncodedObject(o)) { 448 redisLog(REDIS_WARNING,"Object raw string len: %zu", sdslen(o->ptr)); 449 if (sdslen(o->ptr) < 4096) { 450 sds repr = sdscatrepr(sdsempty(),o->ptr,sdslen(o->ptr)); 451 redisLog(REDIS_WARNING,"Object raw string content: %s", repr); 452 sdsfree(repr); 453 } 454 } else if (o->type == REDIS_LIST) { 455 redisLog(REDIS_WARNING,"List length: %d", (int) listTypeLength(o)); 456 } else if (o->type == REDIS_SET) { 457 redisLog(REDIS_WARNING,"Set size: %d", (int) setTypeSize(o)); 458 } else if (o->type == REDIS_HASH) { 459 redisLog(REDIS_WARNING,"Hash size: %d", (int) hashTypeLength(o)); 460 } else if (o->type == REDIS_ZSET) { 461 redisLog(REDIS_WARNING,"Sorted set size: %d", (int) zsetLength(o)); 462 if (o->encoding == REDIS_ENCODING_SKIPLIST) 463 redisLog(REDIS_WARNING,"Skiplist level: %d", (int) ((zset*)o->ptr)->zsl->level); 464 } 465 } 466 467 void _redisAssertPrintObject(robj *o) { 468 bugReportStart(); 469 redisLog(REDIS_WARNING,"=== ASSERTION FAILED OBJECT CONTEXT ==="); 470 redisLogObjectDebugInfo(o); 471 } 472 473 void _redisAssertWithInfo(redisClient *c, robj *o, char *estr, char *file, int line) { 474 if (c) _redisAssertPrintClientInfo(c); 475 if (o) _redisAssertPrintObject(o); 476 _redisAssert(estr,file,line); 477 } 478 479 void _redisPanic(char *msg, char *file, int line) { 480 bugReportStart(); 481 redisLog(REDIS_WARNING,"------------------------------------------------"); 482 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue"); 483 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line); 484 #ifdef HAVE_BACKTRACE 485 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)"); 486 #endif 487 redisLog(REDIS_WARNING,"------------------------------------------------"); 488 *((char*)-1) = 'x'; 489 } 490 491 void bugReportStart(void) { 492 if (server.bug_report_start == 0) { 493 redisLog(REDIS_WARNING, 494 "\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ==="); 495 server.bug_report_start = 1; 496 } 497 } 498 499 #ifdef HAVE_BACKTRACE 500 static void *getMcontextEip(ucontext_t *uc) { 501 #if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6) 502 /* OSX < 10.6 */ 503 #if defined(__x86_64__) 504 return (void*) uc->uc_mcontext->__ss.__rip; 505 #elif defined(__i386__) 506 return (void*) uc->uc_mcontext->__ss.__eip; 507 #else 508 return (void*) uc->uc_mcontext->__ss.__srr0; 509 #endif 510 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) 511 /* OSX >= 10.6 */ 512 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) 513 return (void*) uc->uc_mcontext->__ss.__rip; 514 #else 515 return (void*) uc->uc_mcontext->__ss.__eip; 516 #endif 517 #elif defined(__linux__) 518 /* Linux */ 519 #if defined(__i386__) 520 return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */ 521 #elif defined(__X86_64__) || defined(__x86_64__) 522 return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */ 523 #elif defined(__ia64__) /* Linux IA64 */ 524 return (void*) uc->uc_mcontext.sc_ip; 525 #endif 526 #else 527 return NULL; 528 #endif 529 } 530 531 void logStackContent(void **sp) { 532 int i; 533 for (i = 15; i >= 0; i--) { 534 unsigned long addr = (unsigned long) sp+i; 535 unsigned long val = (unsigned long) sp[i]; 536 537 if (sizeof(long) == 4) 538 redisLog(REDIS_WARNING, "(%08lx) -> %08lx", addr, val); 539 else 540 redisLog(REDIS_WARNING, "(%016lx) -> %016lx", addr, val); 541 } 542 } 543 544 void logRegisters(ucontext_t *uc) { 545 redisLog(REDIS_WARNING, "--- REGISTERS"); 546 547 /* OSX */ 548 #if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6) 549 /* OSX AMD64 */ 550 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__) 551 redisLog(REDIS_WARNING, 552 "\n" 553 "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n" 554 "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n" 555 "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n" 556 "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n" 557 "RIP:%016lx EFL:%016lx\nCS :%016lx FS:%016lx GS:%016lx", 558 (unsigned long) uc->uc_mcontext->__ss.__rax, 559 (unsigned long) uc->uc_mcontext->__ss.__rbx, 560 (unsigned long) uc->uc_mcontext->__ss.__rcx, 561 (unsigned long) uc->uc_mcontext->__ss.__rdx, 562 (unsigned long) uc->uc_mcontext->__ss.__rdi, 563 (unsigned long) uc->uc_mcontext->__ss.__rsi, 564 (unsigned long) uc->uc_mcontext->__ss.__rbp, 565 (unsigned long) uc->uc_mcontext->__ss.__rsp, 566 (unsigned long) uc->uc_mcontext->__ss.__r8, 567 (unsigned long) uc->uc_mcontext->__ss.__r9, 568 (unsigned long) uc->uc_mcontext->__ss.__r10, 569 (unsigned long) uc->uc_mcontext->__ss.__r11, 570 (unsigned long) uc->uc_mcontext->__ss.__r12, 571 (unsigned long) uc->uc_mcontext->__ss.__r13, 572 (unsigned long) uc->uc_mcontext->__ss.__r14, 573 (unsigned long) uc->uc_mcontext->__ss.__r15, 574 (unsigned long) uc->uc_mcontext->__ss.__rip, 575 (unsigned long) uc->uc_mcontext->__ss.__rflags, 576 (unsigned long) uc->uc_mcontext->__ss.__cs, 577 (unsigned long) uc->uc_mcontext->__ss.__fs, 578 (unsigned long) uc->uc_mcontext->__ss.__gs 579 ); 580 logStackContent((void**)uc->uc_mcontext->__ss.__rsp); 581 #else 582 /* OSX x86 */ 583 redisLog(REDIS_WARNING, 584 "\n" 585 "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n" 586 "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n" 587 "SS:%08lx EFL:%08lx EIP:%08lx CS :%08lx\n" 588 "DS:%08lx ES:%08lx FS :%08lx GS :%08lx", 589 (unsigned long) uc->uc_mcontext->__ss.__eax, 590 (unsigned long) uc->uc_mcontext->__ss.__ebx, 591 (unsigned long) uc->uc_mcontext->__ss.__ecx, 592 (unsigned long) uc->uc_mcontext->__ss.__edx, 593 (unsigned long) uc->uc_mcontext->__ss.__edi, 594 (unsigned long) uc->uc_mcontext->__ss.__esi, 595 (unsigned long) uc->uc_mcontext->__ss.__ebp, 596 (unsigned long) uc->uc_mcontext->__ss.__esp, 597 (unsigned long) uc->uc_mcontext->__ss.__ss, 598 (unsigned long) uc->uc_mcontext->__ss.__eflags, 599 (unsigned long) uc->uc_mcontext->__ss.__eip, 600 (unsigned long) uc->uc_mcontext->__ss.__cs, 601 (unsigned long) uc->uc_mcontext->__ss.__ds, 602 (unsigned long) uc->uc_mcontext->__ss.__es, 603 (unsigned long) uc->uc_mcontext->__ss.__fs, 604 (unsigned long) uc->uc_mcontext->__ss.__gs 605 ); 606 logStackContent((void**)uc->uc_mcontext->__ss.__esp); 607 #endif 608 /* Linux */ 609 #elif defined(__linux__) 610 /* Linux x86 */ 611 #if defined(__i386__) 612 redisLog(REDIS_WARNING, 613 "\n" 614 "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n" 615 "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n" 616 "SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\n" 617 "DS :%08lx ES :%08lx FS :%08lx GS:%08lx", 618 (unsigned long) uc->uc_mcontext.gregs[11], 619 (unsigned long) uc->uc_mcontext.gregs[8], 620 (unsigned long) uc->uc_mcontext.gregs[10], 621 (unsigned long) uc->uc_mcontext.gregs[9], 622 (unsigned long) uc->uc_mcontext.gregs[4], 623 (unsigned long) uc->uc_mcontext.gregs[5], 624 (unsigned long) uc->uc_mcontext.gregs[6], 625 (unsigned long) uc->uc_mcontext.gregs[7], 626 (unsigned long) uc->uc_mcontext.gregs[18], 627 (unsigned long) uc->uc_mcontext.gregs[17], 628 (unsigned long) uc->uc_mcontext.gregs[14], 629 (unsigned long) uc->uc_mcontext.gregs[15], 630 (unsigned long) uc->uc_mcontext.gregs[3], 631 (unsigned long) uc->uc_mcontext.gregs[2], 632 (unsigned long) uc->uc_mcontext.gregs[1], 633 (unsigned long) uc->uc_mcontext.gregs[0] 634 ); 635 logStackContent((void**)uc->uc_mcontext.gregs[7]); 636 #elif defined(__X86_64__) || defined(__x86_64__) 637 /* Linux AMD64 */ 638 redisLog(REDIS_WARNING, 639 "\n" 640 "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n" 641 "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n" 642 "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n" 643 "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n" 644 "RIP:%016lx EFL:%016lx\nCSGSFS:%016lx", 645 (unsigned long) uc->uc_mcontext.gregs[13], 646 (unsigned long) uc->uc_mcontext.gregs[11], 647 (unsigned long) uc->uc_mcontext.gregs[14], 648 (unsigned long) uc->uc_mcontext.gregs[12], 649 (unsigned long) uc->uc_mcontext.gregs[8], 650 (unsigned long) uc->uc_mcontext.gregs[9], 651 (unsigned long) uc->uc_mcontext.gregs[10], 652 (unsigned long) uc->uc_mcontext.gregs[15], 653 (unsigned long) uc->uc_mcontext.gregs[0], 654 (unsigned long) uc->uc_mcontext.gregs[1], 655 (unsigned long) uc->uc_mcontext.gregs[2], 656 (unsigned long) uc->uc_mcontext.gregs[3], 657 (unsigned long) uc->uc_mcontext.gregs[4], 658 (unsigned long) uc->uc_mcontext.gregs[5], 659 (unsigned long) uc->uc_mcontext.gregs[6], 660 (unsigned long) uc->uc_mcontext.gregs[7], 661 (unsigned long) uc->uc_mcontext.gregs[16], 662 (unsigned long) uc->uc_mcontext.gregs[17], 663 (unsigned long) uc->uc_mcontext.gregs[18] 664 ); 665 logStackContent((void**)uc->uc_mcontext.gregs[15]); 666 #endif 667 #else 668 redisLog(REDIS_WARNING, 669 " Dumping of registers not supported for this OS/arch"); 670 #endif 671 } 672 673 /* Logs the stack trace using the backtrace() call. This function is designed 674 * to be called from signal handlers safely. */ 675 void logStackTrace(ucontext_t *uc) { 676 void *trace[100]; 677 int trace_size = 0, fd; 678 int log_to_stdout = server.logfile[0] == '\0'; 679 680 /* Open the log file in append mode. */ 681 fd = log_to_stdout ? 682 STDOUT_FILENO : 683 open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644); 684 if (fd == -1) return; 685 686 /* Generate the stack trace */ 687 trace_size = backtrace(trace, 100); 688 689 /* overwrite sigaction with caller's address */ 690 if (getMcontextEip(uc) != NULL) 691 trace[1] = getMcontextEip(uc); 692 693 /* Write symbols to log file */ 694 backtrace_symbols_fd(trace, trace_size, fd); 695 696 /* Cleanup */ 697 if (!log_to_stdout) close(fd); 698 } 699 700 /* Log information about the "current" client, that is, the client that is 701 * currently being served by Redis. May be NULL if Redis is not serving a 702 * client right now. */ 703 void logCurrentClient(void) { 704 if (server.current_client == NULL) return; 705 706 redisClient *cc = server.current_client; 707 sds client; 708 int j; 709 710 redisLog(REDIS_WARNING, "--- CURRENT CLIENT INFO"); 711 client = catClientInfoString(sdsempty(),cc); 712 redisLog(REDIS_WARNING,"client: %s", client); 713 sdsfree(client); 714 for (j = 0; j < cc->argc; j++) { 715 robj *decoded; 716 717 decoded = getDecodedObject(cc->argv[j]); 718 redisLog(REDIS_WARNING,"argv[%d]: '%s'", j, (char*)decoded->ptr); 719 decrRefCount(decoded); 720 } 721 /* Check if the first argument, usually a key, is found inside the 722 * selected DB, and if so print info about the associated object. */ 723 if (cc->argc >= 1) { 724 robj *val, *key; 725 dictEntry *de; 726 727 key = getDecodedObject(cc->argv[1]); 728 de = dictFind(cc->db->dict, key->ptr); 729 if (de) { 730 val = dictGetVal(de); 731 redisLog(REDIS_WARNING,"key '%s' found in DB containing the following object:", (char*)key->ptr); 732 redisLogObjectDebugInfo(val); 733 } 734 decrRefCount(key); 735 } 736 } 737 738 #if defined(HAVE_PROC_MAPS) 739 void memtest_non_destructive_invert(void *addr, size_t size); 740 void memtest_non_destructive_swap(void *addr, size_t size); 741 #define MEMTEST_MAX_REGIONS 128 742 743 int memtest_test_linux_anonymous_maps(void) { 744 FILE *fp = fopen("/proc/self/maps","r"); 745 char line[1024]; 746 size_t start_addr, end_addr, size; 747 size_t start_vect[MEMTEST_MAX_REGIONS]; 748 size_t size_vect[MEMTEST_MAX_REGIONS]; 749 int regions = 0, j; 750 uint64_t crc1 = 0, crc2 = 0, crc3 = 0; 751 752 while(fgets(line,sizeof(line),fp) != NULL) { 753 char *start, *end, *p = line; 754 755 start = p; 756 p = strchr(p,'-'); 757 if (!p) continue; 758 *p++ = '\0'; 759 end = p; 760 p = strchr(p,' '); 761 if (!p) continue; 762 *p++ = '\0'; 763 if (strstr(p,"stack") || 764 strstr(p,"vdso") || 765 strstr(p,"vsyscall")) continue; 766 if (!strstr(p,"00:00")) continue; 767 if (!strstr(p,"rw")) continue; 768 769 start_addr = strtoul(start,NULL,16); 770 end_addr = strtoul(end,NULL,16); 771 size = end_addr-start_addr; 772 773 start_vect[regions] = start_addr; 774 size_vect[regions] = size; 775 printf("Testing %lx %lu\n", (unsigned long) start_vect[regions], 776 (unsigned long) size_vect[regions]); 777 regions++; 778 } 779 780 /* Test all the regions as an unique sequential region. 781 * 1) Take the CRC64 of the memory region. */ 782 for (j = 0; j < regions; j++) { 783 crc1 = crc64(crc1,(void*)start_vect[j],size_vect[j]); 784 } 785 786 /* 2) Invert bits, swap adjacent words, swap again, invert bits. 787 * This is the error amplification step. */ 788 for (j = 0; j < regions; j++) 789 memtest_non_destructive_invert((void*)start_vect[j],size_vect[j]); 790 for (j = 0; j < regions; j++) 791 memtest_non_destructive_swap((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_invert((void*)start_vect[j],size_vect[j]); 796 797 /* 3) Take the CRC64 sum again. */ 798 for (j = 0; j < regions; j++) 799 crc2 = crc64(crc2,(void*)start_vect[j],size_vect[j]); 800 801 /* 4) Swap + Swap again */ 802 for (j = 0; j < regions; j++) 803 memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]); 804 for (j = 0; j < regions; j++) 805 memtest_non_destructive_swap((void*)start_vect[j],size_vect[j]); 806 807 /* 5) Take the CRC64 sum again. */ 808 for (j = 0; j < regions; j++) 809 crc3 = crc64(crc3,(void*)start_vect[j],size_vect[j]); 810 811 /* NOTE: It is very important to close the file descriptor only now 812 * because closing it before may result into unmapping of some memory 813 * region that we are testing. */ 814 fclose(fp); 815 816 /* If the two CRC are not the same, we trapped a memory error. */ 817 return crc1 != crc2 || crc2 != crc3; 818 } 819 #endif 820 821 void sigsegvHandler(int sig, siginfo_t *info, void *secret) { 822 ucontext_t *uc = (ucontext_t*) secret; 823 sds infostring, clients; 824 struct sigaction act; 825 REDIS_NOTUSED(info); 826 827 bugReportStart(); 828 redisLog(REDIS_WARNING, 829 " Redis %s crashed by signal: %d", REDIS_VERSION, sig); 830 redisLog(REDIS_WARNING, 831 " Failed assertion: %s (%s:%d)", server.assert_failed, 832 server.assert_file, server.assert_line); 833 834 /* Log the stack trace */ 835 redisLog(REDIS_WARNING, "--- STACK TRACE"); 836 logStackTrace(uc); 837 838 /* Log INFO and CLIENT LIST */ 839 redisLog(REDIS_WARNING, "--- INFO OUTPUT"); 840 infostring = genRedisInfoString("all"); 841 infostring = sdscatprintf(infostring, "hash_init_value: %u\n", 842 dictGetHashFunctionSeed()); 843 redisLogRaw(REDIS_WARNING, infostring); 844 redisLog(REDIS_WARNING, "--- CLIENT LIST OUTPUT"); 845 clients = getAllClientsInfoString(); 846 redisLogRaw(REDIS_WARNING, clients); 847 sdsfree(infostring); 848 sdsfree(clients); 849 850 /* Log the current client */ 851 logCurrentClient(); 852 853 /* Log dump of processor registers */ 854 logRegisters(uc); 855 856 #if defined(HAVE_PROC_MAPS) 857 /* Test memory */ 858 redisLog(REDIS_WARNING, "--- FAST MEMORY TEST"); 859 bioKillThreads(); 860 if (memtest_test_linux_anonymous_maps()) { 861 redisLog(REDIS_WARNING, 862 "!!! MEMORY ERROR DETECTED! Check your memory ASAP !!!"); 863 } else { 864 redisLog(REDIS_WARNING, 865 "Fast memory test PASSED, however your memory can still be broken. Please run a memory test for several hours if possible."); 866 } 867 #endif 868 869 redisLog(REDIS_WARNING, 870 "\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n" 871 " Please report the crash opening an issue on github:\n\n" 872 " http://github.com/antirez/redis/issues\n\n" 873 " Suspect RAM error? Use redis-server --test-memory to verify it.\n\n" 874 ); 875 /* free(messages); Don't call free() with possibly corrupted memory. */ 876 if (server.daemonize) unlink(server.pidfile); 877 878 /* Make sure we exit with the right signal at the end. So for instance 879 * the core will be dumped if enabled. */ 880 sigemptyset (&act.sa_mask); 881 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND; 882 act.sa_handler = SIG_DFL; 883 sigaction (sig, &act, NULL); 884 kill(getpid(),sig); 885 } 886 #endif /* HAVE_BACKTRACE */ 887 888 /* ==================== Logging functions for debugging ===================== */ 889 890 void redisLogHexDump(int level, char *descr, void *value, size_t len) { 891 char buf[65], *b; 892 unsigned char *v = value; 893 char charset[] = "0123456789abcdef"; 894 895 redisLog(level,"%s (hexdump):", descr); 896 b = buf; 897 while(len) { 898 b[0] = charset[(*v)>>4]; 899 b[1] = charset[(*v)&0xf]; 900 b[2] = '\0'; 901 b += 2; 902 len--; 903 v++; 904 if (b-buf == 64 || len == 0) { 905 redisLogRaw(level|REDIS_LOG_RAW,buf); 906 b = buf; 907 } 908 } 909 redisLogRaw(level|REDIS_LOG_RAW,"\n"); 910 } 911 912 /* =========================== Software Watchdog ============================ */ 913 #include <sys/time.h> 914 915 void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) { 916 #ifdef HAVE_BACKTRACE 917 ucontext_t *uc = (ucontext_t*) secret; 918 #endif 919 REDIS_NOTUSED(info); 920 REDIS_NOTUSED(sig); 921 922 redisLogFromHandler(REDIS_WARNING,"\n--- WATCHDOG TIMER EXPIRED ---"); 923 #ifdef HAVE_BACKTRACE 924 logStackTrace(uc); 925 #else 926 redisLogFromHandler(REDIS_WARNING,"Sorry: no support for backtrace()."); 927 #endif 928 redisLogFromHandler(REDIS_WARNING,"--------\n"); 929 } 930 931 /* Schedule a SIGALRM delivery after the specified period in milliseconds. 932 * If a timer is already scheduled, this function will re-schedule it to the 933 * specified time. If period is 0 the current timer is disabled. */ 934 void watchdogScheduleSignal(int period) { 935 struct itimerval it; 936 937 /* Will stop the timer if period is 0. */ 938 it.it_value.tv_sec = period/1000; 939 it.it_value.tv_usec = (period%1000)*1000; 940 /* Don't automatically restart. */ 941 it.it_interval.tv_sec = 0; 942 it.it_interval.tv_usec = 0; 943 setitimer(ITIMER_REAL, &it, NULL); 944 } 945 946 /* Enable the software watchdog with the specified period in milliseconds. */ 947 void enableWatchdog(int period) { 948 int min_period; 949 950 if (server.watchdog_period == 0) { 951 struct sigaction act; 952 953 /* Watchdog was actually disabled, so we have to setup the signal 954 * handler. */ 955 sigemptyset(&act.sa_mask); 956 act.sa_flags = SA_ONSTACK | SA_SIGINFO; 957 act.sa_sigaction = watchdogSignalHandler; 958 sigaction(SIGALRM, &act, NULL); 959 } 960 /* If the configured period is smaller than twice the timer period, it is 961 * too short for the software watchdog to work reliably. Fix it now 962 * if needed. */ 963 min_period = (1000/server.hz)*2; 964 if (period < min_period) period = min_period; 965 watchdogScheduleSignal(period); /* Adjust the current timer. */ 966 server.watchdog_period = period; 967 } 968 969 /* Disable the software watchdog. */ 970 void disableWatchdog(void) { 971 struct sigaction act; 972 if (server.watchdog_period == 0) return; /* Already disabled. */ 973 watchdogScheduleSignal(0); /* Stop the current timer. */ 974 975 /* Set the signal handler to SIG_IGN, this will also remove pending 976 * signals from the queue. */ 977 sigemptyset(&act.sa_mask); 978 act.sa_flags = 0; 979 act.sa_handler = SIG_IGN; 980 sigaction(SIGALRM, &act, NULL); 981 server.watchdog_period = 0; 982 } 983