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