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