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