]> git.saurik.com Git - redis.git/blame - src/debug.c
SRANDMEMBER <count> leak fixed.
[redis.git] / src / debug.c
CommitLineData
e2641e09 1#include "redis.h"
2#include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
3
3688d7f3 4#include <arpa/inet.h>
d4d20859 5#include <signal.h>
6
7#ifdef HAVE_BACKTRACE
8#include <execinfo.h>
9#include <ucontext.h>
9db4cea2 10#include <fcntl.h>
d4d20859 11#endif /* HAVE_BACKTRACE */
3688d7f3 12
e2641e09 13/* ================================= Debugging ============================== */
14
15/* Compute the sha1 of string at 's' with 'len' bytes long.
16 * The SHA1 is then xored againt the string pointed by digest.
17 * Since xor is commutative, this operation is used in order to
18 * "add" digests relative to unordered elements.
19 *
20 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
21void xorDigest(unsigned char *digest, void *ptr, size_t len) {
22 SHA1_CTX ctx;
23 unsigned char hash[20], *s = ptr;
24 int j;
25
26 SHA1Init(&ctx);
27 SHA1Update(&ctx,s,len);
28 SHA1Final(hash,&ctx);
29
30 for (j = 0; j < 20; j++)
31 digest[j] ^= hash[j];
32}
33
34void xorObjectDigest(unsigned char *digest, robj *o) {
35 o = getDecodedObject(o);
36 xorDigest(digest,o->ptr,sdslen(o->ptr));
37 decrRefCount(o);
38}
39
40/* This function instead of just computing the SHA1 and xoring it
41 * against diget, also perform the digest of "digest" itself and
42 * replace the old value with the new one.
43 *
44 * So the final digest will be:
45 *
46 * digest = SHA1(digest xor SHA1(data))
47 *
48 * This function is used every time we want to preserve the order so
49 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
50 *
51 * Also note that mixdigest("foo") followed by mixdigest("bar")
52 * will lead to a different digest compared to "fo", "obar".
53 */
54void mixDigest(unsigned char *digest, void *ptr, size_t len) {
55 SHA1_CTX ctx;
56 char *s = ptr;
57
58 xorDigest(digest,s,len);
59 SHA1Init(&ctx);
60 SHA1Update(&ctx,digest,20);
61 SHA1Final(digest,&ctx);
62}
63
64void mixObjectDigest(unsigned char *digest, robj *o) {
65 o = getDecodedObject(o);
66 mixDigest(digest,o->ptr,sdslen(o->ptr));
67 decrRefCount(o);
68}
69
70/* Compute the dataset digest. Since keys, sets elements, hashes elements
71 * are not ordered, we use a trick: every aggregate digest is the xor
72 * of the digests of their elements. This way the order will not change
73 * the result. For list instead we use a feedback entering the output digest
74 * as input in order to ensure that a different ordered list will result in
75 * a different digest. */
76void computeDatasetDigest(unsigned char *final) {
77 unsigned char digest[20];
78 char buf[128];
79 dictIterator *di = NULL;
80 dictEntry *de;
81 int j;
82 uint32_t aux;
83
84 memset(final,0,20); /* Start with a clean result */
85
86 for (j = 0; j < server.dbnum; j++) {
87 redisDb *db = server.db+j;
88
89 if (dictSize(db->dict) == 0) continue;
90 di = dictGetIterator(db->dict);
91
92 /* hash the DB id, so the same dataset moved in a different
93 * DB will lead to a different digest */
94 aux = htonl(j);
95 mixDigest(final,&aux,sizeof(aux));
96
97 /* Iterate this DB writing every entry */
98 while((de = dictNext(di)) != NULL) {
99 sds key;
100 robj *keyobj, *o;
4be855e7 101 long long expiretime;
e2641e09 102
103 memset(digest,0,20); /* This key-val digest */
c0ba9ebe 104 key = dictGetKey(de);
e2641e09 105 keyobj = createStringObject(key,sdslen(key));
106
107 mixDigest(digest,key,sdslen(key));
108
c0ba9ebe 109 o = dictGetVal(de);
e2641e09 110
111 aux = htonl(o->type);
112 mixDigest(digest,&aux,sizeof(aux));
113 expiretime = getExpire(db,keyobj);
114
115 /* Save the key and associated value */
116 if (o->type == REDIS_STRING) {
117 mixObjectDigest(digest,o);
118 } else if (o->type == REDIS_LIST) {
119 listTypeIterator *li = listTypeInitIterator(o,0,REDIS_TAIL);
120 listTypeEntry entry;
121 while(listTypeNext(li,&entry)) {
122 robj *eleobj = listTypeGet(&entry);
123 mixObjectDigest(digest,eleobj);
124 decrRefCount(eleobj);
125 }
126 listTypeReleaseIterator(li);
127 } else if (o->type == REDIS_SET) {
cb72d0f1 128 setTypeIterator *si = setTypeInitIterator(o);
2767f1c0 129 robj *ele;
1b508da7 130 while((ele = setTypeNextObject(si)) != NULL) {
2767f1c0
PN
131 xorObjectDigest(digest,ele);
132 decrRefCount(ele);
e2641e09 133 }
2767f1c0 134 setTypeReleaseIterator(si);
e2641e09 135 } else if (o->type == REDIS_ZSET) {
dddf5335
PN
136 unsigned char eledigest[20];
137
138 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
139 unsigned char *zl = o->ptr;
140 unsigned char *eptr, *sptr;
141 unsigned char *vstr;
142 unsigned int vlen;
143 long long vll;
144 double score;
145
146 eptr = ziplistIndex(zl,0);
147 redisAssert(eptr != NULL);
148 sptr = ziplistNext(zl,eptr);
149 redisAssert(sptr != NULL);
150
151 while (eptr != NULL) {
152 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vll));
153 score = zzlGetScore(sptr);
154
155 memset(eledigest,0,20);
156 if (vstr != NULL) {
157 mixDigest(eledigest,vstr,vlen);
158 } else {
159 ll2string(buf,sizeof(buf),vll);
160 mixDigest(eledigest,buf,strlen(buf));
161 }
162
163 snprintf(buf,sizeof(buf),"%.17g",score);
164 mixDigest(eledigest,buf,strlen(buf));
165 xorDigest(digest,eledigest,20);
166 zzlNext(zl,&eptr,&sptr);
167 }
100ed062 168 } else if (o->encoding == REDIS_ENCODING_SKIPLIST) {
dddf5335
PN
169 zset *zs = o->ptr;
170 dictIterator *di = dictGetIterator(zs->dict);
171 dictEntry *de;
172
173 while((de = dictNext(di)) != NULL) {
c0ba9ebe 174 robj *eleobj = dictGetKey(de);
175 double *score = dictGetVal(de);
dddf5335
PN
176
177 snprintf(buf,sizeof(buf),"%.17g",*score);
178 memset(eledigest,0,20);
179 mixObjectDigest(eledigest,eleobj);
180 mixDigest(eledigest,buf,strlen(buf));
181 xorDigest(digest,eledigest,20);
182 }
183 dictReleaseIterator(di);
184 } else {
185 redisPanic("Unknown sorted set encoding");
e2641e09 186 }
e2641e09 187 } else if (o->type == REDIS_HASH) {
188 hashTypeIterator *hi;
189 robj *obj;
190
191 hi = hashTypeInitIterator(o);
192 while (hashTypeNext(hi) != REDIS_ERR) {
193 unsigned char eledigest[20];
194
195 memset(eledigest,0,20);
8c304be3 196 obj = hashTypeCurrentObject(hi,REDIS_HASH_KEY);
e2641e09 197 mixObjectDigest(eledigest,obj);
198 decrRefCount(obj);
8c304be3 199 obj = hashTypeCurrentObject(hi,REDIS_HASH_VALUE);
e2641e09 200 mixObjectDigest(eledigest,obj);
201 decrRefCount(obj);
202 xorDigest(digest,eledigest,20);
203 }
204 hashTypeReleaseIterator(hi);
205 } else {
206 redisPanic("Unknown object type");
207 }
208 /* If the key has an expire, add it to the mix */
209 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
210 /* We can finally xor the key-val digest to the final digest */
211 xorDigest(final,digest,20);
212 decrRefCount(keyobj);
213 }
214 dictReleaseIterator(di);
215 }
216}
217
218void debugCommand(redisClient *c) {
219 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
220 *((char*)-1) = 'x';
5de75120 221 } else if (!strcasecmp(c->argv[1]->ptr,"oom")) {
222 void *ptr = zmalloc(ULONG_MAX); /* Should trigger an out of memory. */
223 zfree(ptr);
224 addReply(c,shared.ok);
e3e69935 225 } else if (!strcasecmp(c->argv[1]->ptr,"assert")) {
226 if (c->argc >= 3) c->argv[2] = tryObjectEncoding(c->argv[2]);
bab205f7 227 redisAssertWithInfo(c,c->argv[0],1 == 2);
e2641e09 228 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
f48cd4b9 229 if (rdbSave(server.rdb_filename) != REDIS_OK) {
e2641e09 230 addReply(c,shared.err);
231 return;
232 }
233 emptyDb();
f48cd4b9 234 if (rdbLoad(server.rdb_filename) != REDIS_OK) {
80ad7189 235 addReplyError(c,"Error trying to load the RDB dump");
e2641e09 236 return;
237 }
238 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
239 addReply(c,shared.ok);
240 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
241 emptyDb();
2c915bcf 242 if (loadAppendOnlyFile(server.aof_filename) != REDIS_OK) {
e2641e09 243 addReply(c,shared.err);
244 return;
245 }
efb60225 246 server.dirty = 0; /* Prevent AOF / replication */
e2641e09 247 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
248 addReply(c,shared.ok);
249 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
b39619d8 250 dictEntry *de;
e2641e09 251 robj *val;
5ef64098 252 char *strenc;
e2641e09 253
b39619d8 254 if ((de = dictFind(c->db->dict,c->argv[2]->ptr)) == NULL) {
e2641e09 255 addReply(c,shared.nokeyerr);
256 return;
257 }
c0ba9ebe 258 val = dictGetVal(de);
5ef64098 259 strenc = strEncoding(val->encoding);
3be00d7e 260
5ef64098 261 addReplyStatusFormat(c,
262 "Value at:%p refcount:%d "
263 "encoding:%s serializedlength:%lld "
3be00d7e 264 "lru:%d lru_seconds_idle:%lu",
5ef64098 265 (void*)val, val->refcount,
266 strenc, (long long) rdbSavedObjectLen(val),
3be00d7e 267 val->lru, estimateObjectIdleTime(val));
e2641e09 268 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
269 long keys, j;
270 robj *key, *val;
271 char buf[128];
272
273 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
274 return;
275 for (j = 0; j < keys; j++) {
276 snprintf(buf,sizeof(buf),"key:%lu",j);
277 key = createStringObject(buf,strlen(buf));
278 if (lookupKeyRead(c->db,key) != NULL) {
279 decrRefCount(key);
280 continue;
281 }
282 snprintf(buf,sizeof(buf),"value:%lu",j);
283 val = createStringObject(buf,strlen(buf));
284 dbAdd(c->db,key,val);
285 decrRefCount(key);
286 }
287 addReply(c,shared.ok);
288 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
289 unsigned char digest[20];
3ab20376 290 sds d = sdsempty();
e2641e09 291 int j;
292
293 computeDatasetDigest(digest);
294 for (j = 0; j < 20; j++)
295 d = sdscatprintf(d, "%02x",digest[j]);
3ab20376
PN
296 addReplyStatus(c,d);
297 sdsfree(d);
404345d8 298 } else if (!strcasecmp(c->argv[1]->ptr,"sleep") && c->argc == 3) {
299 double dtime = strtod(c->argv[2]->ptr,NULL);
300 long long utime = dtime*1000000;
301
302 usleep(utime);
303 addReply(c,shared.ok);
e2641e09 304 } else {
3ab20376
PN
305 addReplyError(c,
306 "Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]");
e2641e09 307 }
308}
309
d4d20859 310/* =========================== Crash handling ============================== */
311
e2641e09 312void _redisAssert(char *estr, char *file, int line) {
fa5af017 313 bugReportStart();
e2641e09 314 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
315 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
316#ifdef HAVE_BACKTRACE
fa5af017 317 server.assert_failed = estr;
318 server.assert_file = file;
319 server.assert_line = line;
320 redisLog(REDIS_WARNING,"(forcing SIGSEGV to print the bug report.)");
e2641e09 321#endif
57be4775 322 *((char*)-1) = 'x';
e2641e09 323}
324
e3e69935 325void _redisAssertPrintClientInfo(redisClient *c) {
bab205f7 326 int j;
e3e69935 327
fa5af017 328 bugReportStart();
bab205f7 329 redisLog(REDIS_WARNING,"=== ASSERTION FAILED CLIENT CONTEXT ===");
330 redisLog(REDIS_WARNING,"client->flags = %d", c->flags);
331 redisLog(REDIS_WARNING,"client->fd = %d", c->fd);
332 redisLog(REDIS_WARNING,"client->argc = %d", c->argc);
333 for (j=0; j < c->argc; j++) {
334 char buf[128];
335 char *arg;
336
337 if (c->argv[j]->type == REDIS_STRING &&
338 c->argv[j]->encoding == REDIS_ENCODING_RAW)
339 {
340 arg = (char*) c->argv[j]->ptr;
341 } else {
342 snprintf(buf,sizeof(buf),"Object type: %d, encoding: %d",
343 c->argv[j]->type, c->argv[j]->encoding);
344 arg = buf;
e3e69935 345 }
bab205f7 346 redisLog(REDIS_WARNING,"client->argv[%d] = \"%s\" (refcount: %d)",
347 j, arg, c->argv[j]->refcount);
348 }
349}
350
00010fa9 351void redisLogObjectDebugInfo(robj *o) {
bab205f7 352 redisLog(REDIS_WARNING,"Object type: %d", o->type);
353 redisLog(REDIS_WARNING,"Object encoding: %d", o->encoding);
354 redisLog(REDIS_WARNING,"Object refcount: %d", o->refcount);
355 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_RAW) {
356 redisLog(REDIS_WARNING,"Object raw string len: %d", sdslen(o->ptr));
357 if (sdslen(o->ptr) < 4096)
358 redisLog(REDIS_WARNING,"Object raw string content: \"%s\"", (char*)o->ptr);
00010fa9 359 } else if (o->type == REDIS_LIST) {
360 redisLog(REDIS_WARNING,"List length: %d", (int) listTypeLength(o));
361 } else if (o->type == REDIS_SET) {
362 redisLog(REDIS_WARNING,"Set size: %d", (int) setTypeSize(o));
363 } else if (o->type == REDIS_HASH) {
364 redisLog(REDIS_WARNING,"Hash size: %d", (int) hashTypeLength(o));
365 } else if (o->type == REDIS_ZSET) {
366 redisLog(REDIS_WARNING,"Sorted set size: %d", (int) zsetLength(o));
367 if (o->encoding == REDIS_ENCODING_SKIPLIST)
368 redisLog(REDIS_WARNING,"Skiplist level: %d", (int) ((zset*)o->ptr)->zsl->level);
e3e69935 369 }
370}
371
00010fa9 372void _redisAssertPrintObject(robj *o) {
373 bugReportStart();
374 redisLog(REDIS_WARNING,"=== ASSERTION FAILED OBJECT CONTEXT ===");
375 redisLogObjectDebugInfo(o);
376}
377
bab205f7 378void _redisAssertWithInfo(redisClient *c, robj *o, char *estr, char *file, int line) {
379 if (c) _redisAssertPrintClientInfo(c);
380 if (o) _redisAssertPrintObject(o);
e3e69935 381 _redisAssert(estr,file,line);
382}
383
e2641e09 384void _redisPanic(char *msg, char *file, int line) {
fa5af017 385 bugReportStart();
120b9ba8 386 redisLog(REDIS_WARNING,"------------------------------------------------");
e2641e09 387 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
388 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
389#ifdef HAVE_BACKTRACE
390 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
57be4775 391#endif
120b9ba8 392 redisLog(REDIS_WARNING,"------------------------------------------------");
e2641e09 393 *((char*)-1) = 'x';
e2641e09 394}
d4d20859 395
ac834d23 396void bugReportStart(void) {
397 if (server.bug_report_start == 0) {
398 redisLog(REDIS_WARNING,
399 "\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ===");
400 server.bug_report_start = 1;
401 }
402}
403
d4d20859 404#ifdef HAVE_BACKTRACE
405static void *getMcontextEip(ucontext_t *uc) {
38b60dea 406#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
407 /* OSX < 10.6 */
408 #if defined(__x86_64__)
d4d20859 409 return (void*) uc->uc_mcontext->__ss.__rip;
38b60dea 410 #elif defined(__i386__)
d4d20859 411 return (void*) uc->uc_mcontext->__ss.__eip;
38b60dea 412 #else
d4d20859 413 return (void*) uc->uc_mcontext->__ss.__srr0;
38b60dea 414 #endif
d4d20859 415#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
38b60dea 416 /* OSX >= 10.6 */
417 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
d4d20859 418 return (void*) uc->uc_mcontext->__ss.__rip;
38b60dea 419 #else
d4d20859 420 return (void*) uc->uc_mcontext->__ss.__eip;
38b60dea 421 #endif
422#elif defined(__linux__)
423 /* Linux */
424 #if defined(__i386__)
d4d20859 425 return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
38b60dea 426 #elif defined(__X86_64__) || defined(__x86_64__)
d4d20859 427 return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
38b60dea 428 #elif defined(__ia64__) /* Linux IA64 */
d4d20859 429 return (void*) uc->uc_mcontext.sc_ip;
38b60dea 430 #endif
d4d20859 431#else
432 return NULL;
433#endif
434}
435
d4d20859 436void logStackContent(void **sp) {
437 int i;
438 for (i = 15; i >= 0; i--) {
447ebf3b 439 if (sizeof(long) == 4)
440 redisLog(REDIS_WARNING, "(%08lx) -> %08lx", sp+i, sp[i]);
441 else
442 redisLog(REDIS_WARNING, "(%016lx) -> %016lx", sp+i, sp[i]);
d4d20859 443 }
444}
445
446void logRegisters(ucontext_t *uc) {
447 redisLog(REDIS_WARNING, "--- REGISTERS");
38b60dea 448
449/* OSX */
d4d20859 450#if defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
38b60dea 451 /* OSX AMD64 */
452 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
d4d20859 453 redisLog(REDIS_WARNING,
454 "\n"
447ebf3b 455 "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
456 "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
457 "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
458 "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
459 "RIP:%016lx EFL:%016lx\nCS :%016lx FS:%016lx GS:%016lx",
d4d20859 460 uc->uc_mcontext->__ss.__rax,
461 uc->uc_mcontext->__ss.__rbx,
462 uc->uc_mcontext->__ss.__rcx,
463 uc->uc_mcontext->__ss.__rdx,
464 uc->uc_mcontext->__ss.__rdi,
465 uc->uc_mcontext->__ss.__rsi,
466 uc->uc_mcontext->__ss.__rbp,
467 uc->uc_mcontext->__ss.__rsp,
468 uc->uc_mcontext->__ss.__r8,
469 uc->uc_mcontext->__ss.__r9,
470 uc->uc_mcontext->__ss.__r10,
471 uc->uc_mcontext->__ss.__r11,
472 uc->uc_mcontext->__ss.__r12,
473 uc->uc_mcontext->__ss.__r13,
474 uc->uc_mcontext->__ss.__r14,
475 uc->uc_mcontext->__ss.__r15,
476 uc->uc_mcontext->__ss.__rip,
477 uc->uc_mcontext->__ss.__rflags,
478 uc->uc_mcontext->__ss.__cs,
479 uc->uc_mcontext->__ss.__fs,
480 uc->uc_mcontext->__ss.__gs
481 );
482 logStackContent((void**)uc->uc_mcontext->__ss.__rsp);
38b60dea 483 #else
484 /* OSX x86 */
d4d20859 485 redisLog(REDIS_WARNING,
486 "\n"
447ebf3b 487 "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
488 "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
489 "SS:%08lx EFL:%08lx EIP:%08lx CS :%08lx\n"
490 "DS:%08lx ES:%08lx FS :%08lx GS :%08lx",
d4d20859 491 uc->uc_mcontext->__ss.__eax,
492 uc->uc_mcontext->__ss.__ebx,
493 uc->uc_mcontext->__ss.__ecx,
494 uc->uc_mcontext->__ss.__edx,
495 uc->uc_mcontext->__ss.__edi,
496 uc->uc_mcontext->__ss.__esi,
497 uc->uc_mcontext->__ss.__ebp,
498 uc->uc_mcontext->__ss.__esp,
499 uc->uc_mcontext->__ss.__ss,
500 uc->uc_mcontext->__ss.__eflags,
501 uc->uc_mcontext->__ss.__eip,
502 uc->uc_mcontext->__ss.__cs,
503 uc->uc_mcontext->__ss.__ds,
504 uc->uc_mcontext->__ss.__es,
505 uc->uc_mcontext->__ss.__fs,
506 uc->uc_mcontext->__ss.__gs
507 );
508 logStackContent((void**)uc->uc_mcontext->__ss.__esp);
38b60dea 509 #endif
510/* Linux */
511#elif defined(__linux__)
512 /* Linux x86 */
513 #if defined(__i386__)
632da605 514 redisLog(REDIS_WARNING,
515 "\n"
447ebf3b 516 "EAX:%08lx EBX:%08lx ECX:%08lx EDX:%08lx\n"
517 "EDI:%08lx ESI:%08lx EBP:%08lx ESP:%08lx\n"
518 "SS :%08lx EFL:%08lx EIP:%08lx CS:%08lx\n"
519 "DS :%08lx ES :%08lx FS :%08lx GS:%08lx",
632da605 520 uc->uc_mcontext.gregs[11],
521 uc->uc_mcontext.gregs[8],
522 uc->uc_mcontext.gregs[10],
523 uc->uc_mcontext.gregs[9],
524 uc->uc_mcontext.gregs[4],
525 uc->uc_mcontext.gregs[5],
526 uc->uc_mcontext.gregs[6],
527 uc->uc_mcontext.gregs[7],
528 uc->uc_mcontext.gregs[18],
529 uc->uc_mcontext.gregs[17],
530 uc->uc_mcontext.gregs[14],
531 uc->uc_mcontext.gregs[15],
532 uc->uc_mcontext.gregs[3],
533 uc->uc_mcontext.gregs[2],
534 uc->uc_mcontext.gregs[1],
535 uc->uc_mcontext.gregs[0]
536 );
537 logStackContent((void**)uc->uc_mcontext.gregs[7]);
38b60dea 538 #elif defined(__X86_64__) || defined(__x86_64__)
539 /* Linux AMD64 */
eea8c7a4 540 redisLog(REDIS_WARNING,
541 "\n"
447ebf3b 542 "RAX:%016lx RBX:%016lx\nRCX:%016lx RDX:%016lx\n"
543 "RDI:%016lx RSI:%016lx\nRBP:%016lx RSP:%016lx\n"
544 "R8 :%016lx R9 :%016lx\nR10:%016lx R11:%016lx\n"
545 "R12:%016lx R13:%016lx\nR14:%016lx R15:%016lx\n"
546 "RIP:%016lx EFL:%016lx\nCSGSFS:%016lx",
eea8c7a4 547 uc->uc_mcontext.gregs[13],
548 uc->uc_mcontext.gregs[11],
549 uc->uc_mcontext.gregs[14],
550 uc->uc_mcontext.gregs[12],
551 uc->uc_mcontext.gregs[8],
552 uc->uc_mcontext.gregs[9],
553 uc->uc_mcontext.gregs[10],
554 uc->uc_mcontext.gregs[15],
555 uc->uc_mcontext.gregs[0],
556 uc->uc_mcontext.gregs[1],
557 uc->uc_mcontext.gregs[2],
558 uc->uc_mcontext.gregs[3],
559 uc->uc_mcontext.gregs[4],
560 uc->uc_mcontext.gregs[5],
561 uc->uc_mcontext.gregs[6],
562 uc->uc_mcontext.gregs[7],
563 uc->uc_mcontext.gregs[16],
564 uc->uc_mcontext.gregs[17],
565 uc->uc_mcontext.gregs[18]
566 );
567 logStackContent((void**)uc->uc_mcontext.gregs[15]);
38b60dea 568 #endif
d4d20859 569#else
570 redisLog(REDIS_WARNING,
571 " Dumping of registers not supported for this OS/arch");
572#endif
573}
574
9db4cea2 575/* Logs the stack trace using the backtrace() call. This function is designed
576 * to be called from signal handlers safely. */
577void logStackTrace(ucontext_t *uc) {
d4d20859 578 void *trace[100];
9db4cea2 579 int trace_size = 0, fd;
580
581 /* Open the log file in append mode. */
582 fd = server.logfile ?
583 open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644) :
584 STDOUT_FILENO;
585 if (fd == -1) return;
d4d20859 586
587 /* Generate the stack trace */
588 trace_size = backtrace(trace, 100);
589
590 /* overwrite sigaction with caller's address */
9db4cea2 591 if (getMcontextEip(uc) != NULL)
d4d20859 592 trace[1] = getMcontextEip(uc);
9db4cea2 593
594 /* Write symbols to log file */
595 backtrace_symbols_fd(trace, trace_size, fd);
596
597 /* Cleanup */
598 if (server.logfile) close(fd);
9ea95e6c 599}
600
601/* Log information about the "current" client, that is, the client that is
602 * currently being served by Redis. May be NULL if Redis is not serving a
603 * client right now. */
604void logCurrentClient(void) {
605 if (server.current_client == NULL) return;
606
607 redisClient *cc = server.current_client;
608 sds client;
609 int j;
610
611 redisLog(REDIS_WARNING, "--- CURRENT CLIENT INFO");
612 client = getClientInfoString(cc);
613 redisLog(REDIS_WARNING,"client: %s", client);
614 sdsfree(client);
615 for (j = 0; j < cc->argc; j++) {
616 robj *decoded;
617
618 decoded = getDecodedObject(cc->argv[j]);
619 redisLog(REDIS_WARNING,"argv[%d]: '%s'", j, (char*)decoded->ptr);
620 decrRefCount(decoded);
621 }
622 /* Check if the first argument, usually a key, is found inside the
623 * selected DB, and if so print info about the associated object. */
624 if (cc->argc >= 1) {
625 robj *val, *key;
626 dictEntry *de;
627
628 key = getDecodedObject(cc->argv[1]);
629 de = dictFind(cc->db->dict, key->ptr);
630 if (de) {
631 val = dictGetVal(de);
632 redisLog(REDIS_WARNING,"key '%s' found in DB containing the following object:", key->ptr);
633 redisLogObjectDebugInfo(val);
634 }
635 decrRefCount(key);
636 }
637}
638
639void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
640 ucontext_t *uc = (ucontext_t*) secret;
9db4cea2 641 sds infostring, clients;
9ea95e6c 642 struct sigaction act;
643 REDIS_NOTUSED(info);
644
645 bugReportStart();
646 redisLog(REDIS_WARNING,
647 " Redis %s crashed by signal: %d", REDIS_VERSION, sig);
648 redisLog(REDIS_WARNING,
649 " Failed assertion: %s (%s:%d)", server.assert_failed,
650 server.assert_file, server.assert_line);
651
652 /* Log the stack trace */
9db4cea2 653 redisLog(REDIS_WARNING, "--- STACK TRACE");
654 logStackTrace(uc);
d4d20859 655
656 /* Log INFO and CLIENT LIST */
657 redisLog(REDIS_WARNING, "--- INFO OUTPUT");
658 infostring = genRedisInfoString("all");
a48c8d87 659 infostring = sdscatprintf(infostring, "hash_init_value: %u\n",
660 dictGetHashFunctionSeed());
d4d20859 661 redisLogRaw(REDIS_WARNING, infostring);
662 redisLog(REDIS_WARNING, "--- CLIENT LIST OUTPUT");
663 clients = getAllClientsInfoString();
664 redisLogRaw(REDIS_WARNING, clients);
9ea95e6c 665 sdsfree(infostring);
666 sdsfree(clients);
d4d20859 667
9ea95e6c 668 /* Log the current client */
669 logCurrentClient();
d4d20859 670
671 /* Log dump of processor registers */
672 logRegisters(uc);
673
674 redisLog(REDIS_WARNING,
675"\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
d4e6ce3e 676" Please report the crash opening an issue on github:\n\n"
677" http://github.com/antirez/redis/issues\n\n"
678" Suspect RAM error? Use redis-server --test-memory to veryfy it.\n\n"
d4d20859 679);
680 /* free(messages); Don't call free() with possibly corrupted memory. */
681 if (server.daemonize) unlink(server.pidfile);
682
683 /* Make sure we exit with the right signal at the end. So for instance
684 * the core will be dumped if enabled. */
685 sigemptyset (&act.sa_mask);
d4d20859 686 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
687 act.sa_handler = SIG_DFL;
688 sigaction (sig, &act, NULL);
689 kill(getpid(),sig);
690}
691#endif /* HAVE_BACKTRACE */
fc030ac7 692
0b8441c1 693/* ==================== Logging functions for debugging ===================== */
694
695void redisLogHexDump(int level, char *descr, void *value, size_t len) {
696 char buf[65], *b;
697 unsigned char *v = value;
698 char charset[] = "0123456789abcdef";
699
700 redisLog(level,"%s (hexdump):", descr);
701 b = buf;
702 while(len) {
703 b[0] = charset[(*v)>>4];
704 b[1] = charset[(*v)&0xf];
705 b[2] = '\0';
706 b += 2;
707 len--;
708 v++;
709 if (b-buf == 64 || len == 0) {
710 redisLogRaw(level|REDIS_LOG_RAW,buf);
711 b = buf;
712 }
713 }
714 redisLogRaw(level|REDIS_LOG_RAW,"\n");
715}
716
fc030ac7 717/* =========================== Software Watchdog ============================ */
718#include <sys/time.h>
719
720void watchdogSignalHandler(int sig, siginfo_t *info, void *secret) {
38b60dea 721#ifdef HAVE_BACKTRACE
fc030ac7 722 ucontext_t *uc = (ucontext_t*) secret;
38b60dea 723#endif
fc030ac7 724 REDIS_NOTUSED(info);
725 REDIS_NOTUSED(sig);
726
9db4cea2 727 redisLogFromHandler(REDIS_WARNING,"\n--- WATCHDOG TIMER EXPIRED ---");
fc030ac7 728#ifdef HAVE_BACKTRACE
9db4cea2 729 logStackTrace(uc);
59d884af 730#else
9db4cea2 731 redisLogFromHandler(REDIS_WARNING,"Sorry: no support for backtrace().");
fc030ac7 732#endif
9db4cea2 733 redisLogFromHandler(REDIS_WARNING,"--------\n");
fc030ac7 734}
735
736/* Schedule a SIGALRM delivery after the specified period in milliseconds.
737 * If a timer is already scheduled, this function will re-schedule it to the
738 * specified time. If period is 0 the current timer is disabled. */
739void watchdogScheduleSignal(int period) {
740 struct itimerval it;
741
742 /* Will stop the timer if period is 0. */
743 it.it_value.tv_sec = period/1000;
1507be5b 744 it.it_value.tv_usec = (period%1000)*1000;
fc030ac7 745 /* Don't automatically restart. */
746 it.it_interval.tv_sec = 0;
747 it.it_interval.tv_usec = 0;
748 setitimer(ITIMER_REAL, &it, NULL);
749}
750
751/* Enable the software watchdong with the specified period in milliseconds. */
752void enableWatchdog(int period) {
a8a981a8 753 int min_period;
754
fc030ac7 755 if (server.watchdog_period == 0) {
756 struct sigaction act;
757
758 /* Watchdog was actually disabled, so we have to setup the signal
759 * handler. */
760 sigemptyset(&act.sa_mask);
761 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_SIGINFO;
762 act.sa_sigaction = watchdogSignalHandler;
763 sigaction(SIGALRM, &act, NULL);
764 }
a8a981a8 765 /* If the configured period is smaller than twice the timer period, it is
766 * too short for the software watchdog to work reliably. Fix it now
767 * if needed. */
768 min_period = (1000/REDIS_HZ)*2;
769 if (period < min_period) period = min_period;
fc030ac7 770 watchdogScheduleSignal(period); /* Adjust the current timer. */
771 server.watchdog_period = period;
772}
773
774/* Disable the software watchdog. */
775void disableWatchdog(void) {
776 struct sigaction act;
777 if (server.watchdog_period == 0) return; /* Already disabled. */
778 watchdogScheduleSignal(0); /* Stop the current timer. */
779
780 /* Set the signal handler to SIG_IGN, this will also remove pending
781 * signals from the queue. */
782 sigemptyset(&act.sa_mask);
783 act.sa_flags = 0;
784 act.sa_handler = SIG_IGN;
785 sigaction(SIGALRM, &act, NULL);
786 server.watchdog_period = 0;
787}