summaryrefslogtreecommitdiff
path: root/src/crash-stack/crash-stack.c
blob: a377306053afeef70e83052e300155c468df52f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Authors: Adrian Szyndela <adrian.s@samsung.com>
 *          Łukasz Stelmach <l.stelmach@samsung.com>
 */
/**
 * @file crash-stack.c
 * @brief This file contains Main module of call stack unwinding program
 *
 * Crash-stack is a single purpose program. Its duty is to show call stack
 * of a crashed program. Crash-stack must be called with proper arguments:
 * either core dump file name or PID of a crashed program.
 */
#include <stdlib.h>
#include <stdio.h>
#include <libelf.h>
#include <elfutils/libdwfl.h>
/*
 * In case the program is compiled with core dumps, the license may switch to GPL2.
 */
#ifdef WITH_CORE_DUMP
#include <elfutils/libebl.h>
#endif
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <linux/prctl.h>
#include "crash-stack.h"
#include <string.h>
#include <elfutils/version.h>
#include <getopt.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/syscall.h>

static siginfo_t __siginfo;
static FILE *outputfile = NULL;		///< global output stream
static FILE *errfile = NULL;		///< global error stream

/**
 * @brief definitions for getopt options: identifiers
 */
enum {
	OPT_PID,
	OPT_TID,
	OPT_OUTPUTFILE,
	OPT_ERRFILE
};

/**
 * @brief definitions for getopt options: full specifications
 */
const struct option opts[] = {
	{ "pid", required_argument, 0, OPT_PID },
	{ "tid", required_argument, 0, OPT_TID },
	{ "output", required_argument, 0, OPT_OUTPUTFILE },
	{ "erroutput", required_argument, 0, OPT_ERRFILE },
	{ 0, 0, 0, 0 }
};

/*
 * __cxa_demangle() is taken from libstdc++, however there is no header that we
 * can take a declaration from. Importing through 'extern' allows using it.
 */
/// @cond false
extern char *__cxa_demangle(const char *mangled_name, char *output_buffer,
		size_t *length, int *status);
///@endcond

/**
 * @brief A callback for dwfl_getmodules().
 *
 * This callback is called once for every module discovered by dwfl_getmodules().
 *
 * @param module the dwfl module
 * @param userdata unused, required by dwfl_getmodules()
 * @param name name of the module
 * @param address address of the module
 * @param arg 4th argument to dwfl_getmodules is passed here
 */
static int __module_callback(Dwfl_Module *module, void **userdata,
		const char *name, Dwarf_Addr address,
		void *arg)
{
	if (name != NULL && name[0] == '[') {
		/* libdwfl couldn't get the module file - we will get it later from notes */
		Mappings *mappings = arg;
		if (mappings->elems < MAX_MAPPINGS_NUM) {
			size_t elems = mappings->elems;
			mappings->tab[elems].m_start = address;
			mappings->tab[elems].m_end = 0;
			mappings->tab[elems].m_offset = 0;
			mappings->tab[elems].m_name = NULL;
			mappings->tab[elems].m_fd = -1;
			mappings->tab[elems].m_elf = 0;
			mappings->elems++;
		}
	}
	return DWARF_CB_OK;
}

/**
 * @brief Reads a value of specified size from core dump file.
 *
 * @param core ELF handler for the core dump file
 * @param from the source address in the ELF file
 * @param size size of the value in bits
 * @param to the address of allocated memory, where the value will be copied
 */
static void __get_value(Elf *core, const void *from, size_t size, void *to)
{
	Elf_Type type = ELF_T_BYTE;
	switch (size) {
	case 8: type = ELF_T_BYTE; break;
	case 16: type = ELF_T_HALF; break;
	case 32: type = ELF_T_WORD; break;
	case 64: type = ELF_T_XWORD; break;
	default:
		 fprintf(stderr, "__get_value for strange size: %llu\n", (unsigned long long)size);
		 break;
	}
	Elf_Data out = {
		.d_buf = to,
		.d_type = type,
		.d_version = EV_CURRENT,
		.d_size = size/8,
		.d_off = 0,
		.d_align = 0
	};
	Elf_Data in = {
		.d_buf = (void*)(from),
		.d_type = out.d_type,
		.d_version = out.d_version,
		.d_size = out.d_size,
		.d_off = 0,
		.d_align = 0
	};
	Elf_Data *data;
	if (gelf_getclass(core) == ELFCLASS32)
		data = elf32_xlatetom(&out, &in, elf_getident(core, NULL)[EI_DATA]);
	else
		data = elf64_xlatetom(&out, &in, elf_getident(core, NULL)[EI_DATA]);
	if (data == NULL)
		fprintf(errfile, "failed to get value from core file\n");
}

/**
 * @brief gets number of values, page size, address size, values and names from ELF notes
 *
 * @remarks This is very specific for organization of notes part in ELF files
 *
 * @param elf ELF handler - may be core file
 * @param desc address of ELF notes descriptor
 * @param[out] values_cnt a place for number of values
 * @param[out] page_size a place for page size
 * @param[out] addr_size a place for address size
 * @param[out] values a place for address of values
 * @param[out] filenames a place for address of filenames
 */
static void __parse_note_file(Elf *elf, const char *desc, uint64_t *values_cnt, uint64_t *page_size,
		size_t *addr_size, const char **values, const char **filenames)
{
	*addr_size = gelf_fsize(elf, ELF_T_ADDR, 1, EV_CURRENT);
	__get_value(elf, desc, *addr_size*8, values_cnt);
	__get_value(elf, desc + *addr_size, *addr_size*8, page_size);
	/* First: triplets of <mapping-start> <mapping-end> <offset-in-pages>
	 *     count = values_cnt
	 * Then the names of files.
	 */
	*values = desc + 2 * *addr_size;
	*filenames = *values + 3 * *addr_size * *values_cnt;
}

/**
 * @brief Simple accessor for mapping items in ELF files
 *
 * @remarks This is very specific for organization of notes part in ELF files
 *
 * @param elf ELF handler - may be core file
 * @param addr_size size of addresses in this ELF
 * @param item address of mapping item to get data from
 * @param[out] mapping_start value of the start of the mapping
 * @param[out] mapping_end value of the end of the mapping
 * @param[out] offset_in_pages number of pages of offset in the file
 */
static void __get_mapping_item(Elf *elf, size_t addr_size, const void *item,
		uint64_t *mapping_start, uint64_t *mapping_end, uint64_t *offset_in_pages)
{
	__get_value(elf, item, addr_size*8, mapping_start);
	__get_value(elf, item + addr_size, addr_size*8, mapping_end);
	__get_value(elf, item + 2 * addr_size, addr_size*8, offset_in_pages);
}

void __find_symbol_in_elf(ProcInfo *proc_info, Dwarf_Addr mapping_start)
{
	Elf *elf;
	int fd;
	const char *elf_name = proc_info->module_name;
	Dwarf_Addr address = proc_info->addr;

	fd = open(elf_name, O_RDONLY);
	if (-1 == fd)
		return;

	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);

	if (NULL == elf) {
		close(fd);
		return;
	}

	Elf_Scn *scn = NULL;
	int found = 0;

	while ((scn = elf_nextscn(elf, scn)) != NULL && !found) {
		GElf_Shdr shdr_mem;
		GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
		if (shdr != NULL && (shdr->sh_type == SHT_SYMTAB || shdr->sh_type == SHT_DYNSYM)) {
			Elf_Data *sdata = elf_getdata(scn, NULL);
			unsigned int nsyms = sdata->d_size / (gelf_getclass(elf) == ELFCLASS32 ?
					sizeof(Elf32_Sym) :
					sizeof(Elf64_Sym));
			unsigned int cnt;
			uintptr_t address_offset = address;
			if (shdr->sh_type == SHT_DYNSYM)
				address_offset -= mapping_start;
			for (cnt = 0; cnt < nsyms; ++cnt) {
				GElf_Sym sym_mem;
				Elf32_Word xndx;
				GElf_Sym *sym = gelf_getsymshndx(sdata, NULL, cnt, &sym_mem, &xndx);
				if (sym != NULL && sym->st_shndx != SHN_UNDEF) {
					if (sym->st_value <= address_offset && address_offset < sym->st_value + sym->st_size) {
						free(proc_info->name);
						proc_info->name = strdup(elf_strptr(elf, shdr->sh_link, sym->st_name));
						proc_info->offset = address_offset - sym->st_value;
						found = 1;
						break;
					}
				}
			}
		}
	}

	elf_end(elf);
	close(fd);
}

/**
 * @brief Opens libdwfl for using with live process
 *
 * @param pid pid of the process to attach to
 * @return Dwfl handle
 */
static Dwfl *__open_dwfl_with_pid(pid_t pid, pid_t tid)
{
	int status;
	pid_t stopped_pid;

	if (ptrace(PTRACE_SEIZE, tid, NULL, PTRACE_O_TRACEEXIT) != 0) {
		fprintf(errfile, "PTRACE_SEIZE failed on TID %d: %m\n", tid);
		return NULL;
	}

	if (pid != tid)
		if (ptrace(PTRACE_SEIZE, pid, NULL, PTRACE_O_TRACEEXIT) != 0) {
			fprintf(errfile, "PTRACE_SEIZE failed on PID %d: %m\n", pid);
			return NULL;
		}

	ptrace(PTRACE_INTERRUPT, pid, 0, 0);
	ptrace(PTRACE_INTERRUPT, tid, 0, 0);

	stopped_pid = waitpid(pid, &status, 0);
	if (stopped_pid == -1 || stopped_pid != pid || !WIFSTOPPED(status)) {
		fprintf(errfile, "waitpid failed: %m, stopped_pid=%d, status=%d\n", stopped_pid, status);
		return NULL;
	}

	if (ptrace(PTRACE_GETSIGINFO, pid, NULL, &__siginfo) != 0)
		return NULL;

	static const Dwfl_Callbacks proc_callbacks = {
		.find_elf = dwfl_linux_proc_find_elf,
		.find_debuginfo = dwfl_standard_find_debuginfo,
		.section_address = NULL,
		.debuginfo_path = NULL
	};

	Dwfl *dwfl = dwfl_begin(&proc_callbacks);
	if (dwfl == NULL) {
		fprintf(errfile, "process %d : Can't start dwfl (%s)\n", pid, dwfl_errmsg(-1));
		return NULL;
	}

	if (dwfl_linux_proc_report(dwfl, pid) < 0) {
		fprintf(errfile, "process %d : dwfl report failed (%s)\n", pid, dwfl_errmsg(-1));
		dwfl_end(dwfl);
		return NULL;
	}

#if _ELFUTILS_PREREQ(0,158)
	if (dwfl_linux_proc_attach(dwfl, pid, true) < 0) {
		fprintf(errfile, "process %d : dwfl attach failed (%s)\n", pid, dwfl_errmsg(-1));
		dwfl_end(dwfl);
		return NULL;
	}
#endif
	return dwfl;
}

/**
 * @brief Opens libdwfl for using with core dump file
 *
 * @remarks This function will open core file regardless of WITH_CORE_DUMP setting.
 *          It may help with detecting issues with using dwfl even without support
 *          for dumps.
 *
 * @param core elf handler for the core dump file
 * @param core_file_name name of the core file; needed only for diagnostics
 * @return Dwfl handle
 */
static Dwfl *__open_dwfl_with_core(Elf *core, const char *core_file_name)
{
	static const Dwfl_Callbacks core_callbacks = {
		.find_elf = dwfl_build_id_find_elf,
		.find_debuginfo = dwfl_standard_find_debuginfo,
		.section_address = NULL,
		.debuginfo_path = NULL
	};

	Dwfl *dwfl = dwfl_begin(&core_callbacks);
	if (dwfl == NULL) {
		fprintf(errfile, "%s : Can't start dwfl (%s)\n", core_file_name, dwfl_errmsg(-1));
		return NULL;
	}

#if _ELFUTILS_PREREQ(0,158)
	if (dwfl_core_file_report(dwfl, core, NULL) < 0)
#else
		if (dwfl_core_file_report(dwfl, core) < 0)
#endif
		{
			fprintf(errfile, "%s : dwfl report failed (%s)\n", core_file_name, dwfl_errmsg(-1));
			dwfl_end(dwfl);
			return NULL;
		}

#if _ELFUTILS_PREREQ(0,158)
	if (dwfl_core_file_attach(dwfl, core) < 0) {
		fprintf(errfile, "%s : dwfl attach failed (%s)\n", core_file_name, dwfl_errmsg(-1));
		dwfl_end(dwfl);
		return NULL;
	}
#endif
	return dwfl;
}

/**
 * @brief Gets registers information for live process
 *
 * @param pid pid of the live process
 * @return 0 on success, -1 otherwise
 */
static int __get_registers_ptrace(pid_t pid)
{
	struct iovec data;
	data.iov_base = _crash_stack_get_memory_for_ptrace_registers(&data.iov_len);

	if (NULL == data.iov_base) {
		fprintf(errfile, "Cannot get memory for registers for ptrace (not implemented for this architecture\n");
		return -1;
	}

	if (ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &data) != 0) {
		fprintf(errfile, "PTRACE_GETREGSET failed on PID %d: %m\n", pid);
		return -1;
	}

	_crash_stack_set_ptrace_registers(data.iov_base);

	return 0;
}

/**
 * @brief Get information about the signal that stopped the process
 *
 * @param pid pid of the live process
 * @return 0 on success, -1 otherwise
 */
static int __get_signal_ptrace(pid_t pid)
{
	const char* const signal_table[] = {
		[SIGHUP]="SIGHUP", [SIGINT]="SIGINT", [SIGQUIT]="SIGQUIT",
		[SIGILL]="SIGILL", [SIGTRAP]="SIGTRAP", [SIGABRT]="SIGABRT",
		[SIGIOT]="SIGIOT", [SIGBUS]="SIGBUS", [SIGFPE]="SIGFPE",
		[SIGKILL]="SIGKILL", [SIGUSR1]="SIGUSR1", [SIGSEGV]="SIGSEGV",
		[SIGUSR2]="SIGUSR2", [SIGPIPE]="SIGPIPE", [SIGALRM]="SIGALRM",
		[SIGTERM]="SIGTERM", [SIGSTKFLT]="SIGSTKFLT", [SIGCHLD]="SIGCHLD",
		[SIGCONT]="SIGCONT", [SIGSTOP]="SIGSTOP", [SIGTSTP]="SIGTSTP",
		[SIGTTIN]="SIGTTIN", [SIGTTOU]="SIGTTOU", [SIGURG]="SIGURG",
		[SIGXCPU]="SIGXCPU", [SIGXFSZ]="SIGXFSZ", [SIGVTALRM]="SIGVTALRM",
		[SIGPROF]="SIGPROF", [SIGWINCH]="SIGWINCH", [SIGIO]="SIGIO",
		[SIGPWR]="SIGPWR", [SIGSYS]="SIGSYS", [SIGUNUSED]="SIGUNUSED",
	};

	printf("Signal: %d\n"
	       "\t(%s)\n"
	       "\tsi_code: %d\n",
	       __siginfo.si_signo,
	       signal_table[__siginfo.si_signo],
	       __siginfo.si_code);
	switch (__siginfo.si_code) {
	case SI_TKILL:
	case SI_USER:
		printf("\tsignal sent by %s (sent by pid %d, uid %d)",
		       __siginfo.si_code == SI_TKILL ? "tkill" : "kill",
		       __siginfo.si_pid, __siginfo.si_uid);
		break;
	case SI_KERNEL:
		printf("\tsignal sent by the kernel\n");
		break;
	}
	return 0;
}

#ifdef WITH_CORE_DUMP
/**
 * @brief Helper function for updating mappings.
 *
 * @remarks Old versions of libelf not always extract full information about modules.
 *          For such cases we maintain mappings for every module. Those mappings
 *          may be updated while reading notes from core file.
 *
 * @param mappings mappings database
 * @param mapping_start address of the mapped start of the module; module is identified
 *                      by mapping_start
 * @param mapping_end address of the end of the module; needed to compute module boundaries
 * @param offset offset within core file - unused
 * @param name file name of the module
 */
static void __updateMapping(Mappings *mappings, uint64_t mapping_start, uint64_t mapping_end,
		uint64_t offset, const char *name)
{
	int i;
	for (i = 0; i < mappings->elems; i++) {
		if (mappings->tab[i].m_start == mapping_start) {
			mappings->tab[i].m_end = mapping_end;
			mappings->tab[i].m_name = name;
			mappings->tab[i].m_offset = offset;
			mappings->tab[i].m_fd = open(name, O_RDONLY);
			mappings->tab[i].m_elf = elf_begin(mappings->tab[i].m_fd, ELF_C_READ_MMAP, NULL);
			return;
		}
	}
}
#endif

/**
 * @brief Gets registers from core dump
 *
 * @param core ELF handler for the core dump file
 * @param core_file_name name of the core file; needed only for diagnostics
 * @param mappings mappings database
 * @return notes handler, NULL on error
 */
static Elf_Data *__get_registers_core(Elf *core, const char *core_file_name, Mappings *mappings)
{
	Elf_Data *notes = NULL;
	/* The part below uses libebl. In case WITH_CORE_DUMP is enabled, the license
	 * may switch to GPL2.
	 */
#ifdef WITH_CORE_DUMP
	GElf_Phdr mem;
	GElf_Phdr *phdr = gelf_getphdr(core, 0, &mem);

	if (phdr == NULL || phdr->p_type != PT_NOTE) {
		fprintf(errfile, "%s : Missing note section at the first position in core file\n",
				core_file_name);
		return NULL;
	}

	notes = elf_getdata_rawchunk(core, phdr->p_offset, phdr->p_filesz, ELF_T_NHDR);
	if (notes == NULL) {
		fprintf(errfile, "%s : error getting notes (%s)\n", core_file_name, dwfl_errmsg(-1));
		return NULL;
	}

	Ebl *ebl = ebl_openbackend(core);
	if (ebl == NULL) {
		fprintf(errfile, "%s : Can't initialize ebl\n", core_file_name);
		return NULL;
	}

	GElf_Nhdr nhdr;
	size_t name_pos;
	size_t desc_pos;
	size_t pos = 0;
	size_t new_pos = 0;
	int got_regs = 0;
	/* registers should be in the first note! */
	while ((new_pos = gelf_getnote(notes, pos, &nhdr, &name_pos, &desc_pos)) > 0) {
		if (nhdr.n_type == NT_PRSTATUS && !got_regs) {
			GElf_Word regs_offset;
			size_t nregloc;
			const Ebl_Register_Location *reglocs;
			size_t nitems;
			const Ebl_Core_Item *items;

			got_regs = 1;

			if (0 == ebl_core_note(ebl, &nhdr, "CORE", &regs_offset, &nregloc,
						&reglocs, &nitems, &items)) {
				fprintf(errfile,
						"%s : error parsing notes (built with different build of libebl?)\n",
						core_file_name);
				return NULL;
			}

			const char *regs_location = (const char *)(notes->d_buf) + pos + desc_pos
				+ regs_offset;
			unsigned i;

			for (i = 0; i < nregloc; i++) {
				const char *register_location = regs_location + reglocs[i].offset;
				int regnum;
				for (regnum = reglocs[i].regno;
						regnum < reglocs[i].regno + reglocs[i].count;
						regnum++) {
					char regname[5];
					int bits, type;
					const char *prefix = 0;
					const char *setname = 0;

					ssize_t ret = ebl_register_info(ebl, regnum, regname,
							sizeof(regname), &prefix, &setname,
							&bits, &type);
					if (ret < 0) {
						fprintf(errfile, "%s : can't get register info\n", core_file_name);
						return NULL;
					}
					void *place_for_reg_value = _get_place_for_register_value(regname, regnum);

					if (place_for_reg_value != NULL)
						__get_value(core, register_location, bits, place_for_reg_value);

					register_location += bits / 8 + reglocs[i].pad;
				}
			}
		} else if (nhdr.n_type == NT_FILE) {
			uint64_t values_cnt = 0, page_size = 0;
			const char *values;
			const char *filenames;
			size_t addr_size = 0;

			__parse_note_file(core, notes->d_buf + desc_pos, &values_cnt, &page_size,
					&addr_size, &values, &filenames);

			int ii;
			/* First: triplets of <mapping-start> <mapping-end> <offset-in-pages>
			 *     count = values_cnt
			 * Then the names of files.
			 */
			for (ii = 0; ii < values_cnt; ii++) {
				uint64_t mapping_start = 0, mapping_end = 0, offset_in_pages = 0;
				const char *item = values + 3 * addr_size * ii;

				__get_mapping_item(core, addr_size, item, &mapping_start, &mapping_end,
						&offset_in_pages);
				__updateMapping(mappings, mapping_start, mapping_end,
						offset_in_pages*page_size, filenames);
				filenames += strlen(filenames)+1;
			}
		}
		pos = new_pos;
	}
	ebl_closebackend(ebl);
#else
	fprintf(errfile, "Configured without support for core dump files\n");
#endif
	return notes;
}

/**
 * @brief Resolves procedure and module names using libdwfl
 *
 * @param proc_info gathered call stack element
 * @param dwfl dwfl handler
 */
static void __resolve_symbols_from_dwfl(ProcInfo *proc_info, Dwfl *dwfl)
{
	uintptr_t address = proc_info->addr;
	Dwfl_Module *module = dwfl_addrmodule(dwfl, address);
	if (module) {

		Dwarf_Addr mapping_start = 0;
		const char *fname = 0;
		const char *module_name = dwfl_module_info(module, NULL, &mapping_start, NULL, NULL, NULL, &fname, NULL);
		if (!proc_info->module_name) {
			if (fname)
				proc_info->module_name = strdup(fname);
			else if (module_name)
				proc_info->module_name = strdup(module_name);
		}

		const char *symbol = dwfl_module_addrname(module, address);
		if (symbol) {
			free(proc_info->name);
			proc_info->name = strdup(symbol);
		}
		else if (proc_info->module_name != NULL) {
			__find_symbol_in_elf(proc_info, mapping_start);
		}
	}
}

/**
 * @brief Resolves procedure and module names using elfutils
 *
 * @remarks This function is used in case that symbol name is not available by libelf,
 *			e.g. when old libelf version does not take into account some modules.
 *
 * @param proc_info gathered call stack element
 * @param core ELF handler for the core dump file, NULL if live process analyzed
 * @param notes notes handler, NULL if live process analyzed
 */
static void __resolve_symbols_from_elf(ProcInfo *proc_info, Elf *core, Elf_Data *notes)
{
	GElf_Nhdr nhdr;
	size_t pos = 0;
	size_t new_pos = 0;
	size_t name_pos;
	size_t desc_pos;

	while ((new_pos = gelf_getnote(notes, pos, &nhdr, &name_pos, &desc_pos)) > 0) {
		if (nhdr.n_type == NT_FILE) {
			uint64_t values_cnt = 0, page_size = 0;
			const char *values;
			const char *filenames;
			size_t addr_size = 0;

			__parse_note_file(core, notes->d_buf + desc_pos, &values_cnt,
							  &page_size, &addr_size, &values, &filenames);

			int ii;
			for (ii = 0; ii < values_cnt; ii++) {
				uint64_t mapping_start = 0, mapping_end = 0, offset_in_pages = 0;
				const char *item = values + 3 * addr_size * ii;

				__get_mapping_item(core, addr_size, item, &mapping_start, &mapping_end,
								 &offset_in_pages);

				if (mapping_start <= proc_info->addr && proc_info->addr < mapping_end) {
					free(proc_info->module_name);
					proc_info->module_name = strdup(filenames);
					__find_symbol_in_elf(proc_info, mapping_start);
					return;
				}

				filenames += strlen(filenames)+1;
			}
		}
		pos = new_pos;
	}
}

/**
 * @brief Checks if symbol starts with '_Z' prefix
 *
 * @param symbol string to compare
 */
static int is_symbol_demanglable(const char *symbol)
{
	return symbol != 0 && (strlen(symbol) >= 2) &&
		symbol[0] == '_' && symbol[1] == 'Z';
}

/**
 * @brief Replaces symbols with demangled
 *
 * @param proc_info gathered call stack element
 */
static void __demangle_symbols(ProcInfo *proc_info)
{
	int status = -1;
	char *dem_buffer = NULL;
	char *demangled_symbol = __cxa_demangle(proc_info->name, dem_buffer, NULL, &status);
	if (status == 0) {
		free(proc_info->name);
		proc_info->name = demangled_symbol;
	}
}

/**
 * @brief Resolves procedure and module name
 *
 * @param proc_info gathered call stack element
 * @param dwfl dwfl handler
 * @param core ELF handler for the core dump file, NULL if live process analyzed
 * @param notes notes handler, NULL if live process analyzed
 */
static void __resolve_symbols(ProcInfo *proc_info, Dwfl *dwfl, Elf *core, Elf_Data *notes)
{
	__resolve_symbols_from_dwfl(proc_info, dwfl);

	if (core != NULL && (!proc_info->module_name || !proc_info->name))
		__resolve_symbols_from_elf(proc_info, core, notes);

	if (is_symbol_demanglable(proc_info->name))
		__demangle_symbols(proc_info);
}

/**
 * @brief Prints call stack element to the global outputfile.
 *
 * @param proc_info gathered call stack element
 */
static void __print_proc_info(ProcInfo *proc_info)
{
	if (proc_info->name) {
		fprintf(outputfile, "%s ", proc_info->name);
		if (proc_info->offset >= 0)
			fprintf(outputfile, "+ 0x%x ", proc_info->offset);
	}
	if (sizeof(proc_info->addr) > 4)
		fprintf(outputfile, "(0x%016llx)", (long long)proc_info->addr);
	else
		fprintf(outputfile, "(0x%08x)", (int32_t)proc_info->addr);

	if (proc_info->module_name != 0)
		fprintf(outputfile, " [%s]", proc_info->module_name);

	fprintf(outputfile, "\n");
}

/**
 * @brief Prints call stack to the global outputfile.
 *
 * @param callstack gathered call stack database
 * @param pid PID of the live process, 0 if core dump file analyzed
 */
static void __print_callstack(Callstack *callstack, pid_t pid)
{
	fprintf(outputfile, "\nCallstack Information");
	if (pid > 1)
		fprintf(outputfile, " (PID:%d)", pid);
	fprintf(outputfile, "\nCall Stack Count: %zu\n", callstack->elems);

	size_t it;
	for (it = 0; it != callstack->elems; ++it) {
		fprintf(outputfile, "%2zu: ", it);
		__print_proc_info(&callstack->proc[it]);
	}
	fprintf(outputfile, "End of Call Stack\n");
}

void callstack_constructor(Callstack *callstack)
{
	size_t it;
	callstack->elems = 0;
	for (it = 0; it < (int)sizeof(callstack->proc)/sizeof(callstack->proc[0]); ++it) {
		callstack->proc[it].offset = -1;
		callstack->proc[it].name = 0;
		callstack->proc[it].module_name = 0;
	}
}

void callstack_destructor(Callstack *callstack)
{
	size_t it;
	for (it = 0; it < callstack->elems; ++it) {
		free(callstack->proc[it].name);
		free(callstack->proc[it].module_name);
	}
	fprintf(outputfile, "End of Call Stack\n");
}

/**
 * @brief Print thread information
 *
 * @param outputfile File handle for printing report.
 * @param pid PID of the inspected process
 * @param tid TID of the inspected thread
 */
static void __crash_stack_print_threads(FILE* outputfile, pid_t pid, pid_t tid)
{
	int threadnum=1;
	DIR *dir;
	struct dirent entry;
	struct dirent *dentry=NULL;
	char task_path[PATH_MAX];
	struct stat sb;


	snprintf(task_path, PATH_MAX, "/proc/%d/task", pid);
	if (stat(task_path, &sb) == -1) {
		return;
	}

	threadnum = sb.st_nlink - 2;

	if (threadnum > 1) {
		fprintf(outputfile, "\nThreads Information\n");
		fprintf(outputfile,
			"Threads: %d\nPID = %d TID = %d\n",
			threadnum, pid, tid);
		/* print thread */
		dir = opendir(task_path);
		if (!dir) {
			fprintf(stderr, "[crash-stack] cannot open %s\n", task_path);
		} else {
			while (readdir_r(dir, &entry, &dentry) == 0 && dentry) {
				if (strcmp(dentry->d_name, ".") == 0 ||
				    strcmp(dentry->d_name, "..") == 0)
					continue;
				fprintf(outputfile, "%s ", dentry->d_name);
			}
			closedir(dir);
			fprintf(outputfile, "\n");
		}
	}

}

/**
 * @brief Main function.
 *
 * Main module accepts two forms of launching:
 *
 *     crash-stack core-dump-file
 *     crash-stack --pid pid
 *
 * The first form allows user to print call stack of a generated core dump file.
 * The second form allows connecting to a live process and displaying its call stack.
 * It might be also used for connecting to a process from system's core dump handler.
 */
int main(int argc, char **argv)
{
	int c;
	pid_t pid = 0;
	pid_t tid = 0;

	const char *core_file_name;

	prctl(PR_SET_DUMPABLE, 0);

	while ((c = getopt_long_only(argc, argv, "", opts, NULL)) != -1) {
		switch (c) {
		case OPT_PID:
			pid = atoi(optarg);
			break;
		case OPT_TID:
			tid = atoi(optarg);
			break;
		case OPT_OUTPUTFILE:
			outputfile = fopen(optarg, "w");
			break;
		case OPT_ERRFILE:
			errfile = fopen(optarg, "w");
			break;
		}
	}

	if (NULL == errfile) errfile = stderr;
	if (NULL == outputfile) outputfile = stdout;

	if (tid == 0) tid = pid;

	core_file_name = argv[optind];
	argc -= optind;

	elf_version(EV_CURRENT);

	/* First, prepare dwfl and modules */
	Elf *core = NULL;
	int core_fd = -1;
	Dwfl *dwfl = NULL;

	if (pid > 1)
		dwfl = __open_dwfl_with_pid(pid, tid);
	else {
		if (argc != 1) {
			fprintf(errfile,
					"Usage: %s [--output file] [--erroutput file] [--pid <pid> [--tid <tid>] | <core-file>]\n",
					argv[0]);
			return 1;
		}

		core_fd = open(core_file_name, O_RDONLY);
		if (core_fd < 0) {
			perror(core_file_name);
			return 2;
		}

		core = elf_begin(core_fd, ELF_C_READ_MMAP, NULL);
		if (core == NULL) {
			fprintf(errfile, "%s : Can't open ELF (%s)\n", core_file_name, elf_errmsg(-1));
			return 3;
		}

		dwfl = __open_dwfl_with_core(core, core_file_name);
	}

	if (NULL == dwfl)
		return 1111;

	Mappings mappings;
	mappings.elems = 0;

	dwfl_getmodules(dwfl, __module_callback, &mappings, 0);
	Elf_Data *notes = 0;

	/* Now, get registers */
	if (pid > 1) {
		if (-1 == __get_signal_ptrace(pid))
			return 4444;
		if (-1 == __get_registers_ptrace(pid))
			return 3333;
	} else {
		notes = __get_registers_core(core, core_file_name, &mappings);
		if (NULL == notes)
			return 2222;
	}

	/* Unwind call stack */
	Callstack callstack;
	callstack_constructor(&callstack);

	_create_crash_stack(dwfl, core, tid, &mappings, &callstack);
	size_t it;
	for (it = 0; it != callstack.elems; ++it)
		__resolve_symbols(&callstack.proc[it], dwfl, core, notes);

	/* Print registers */
	_crash_stack_print_regs(outputfile);

	/* Threads */
	__crash_stack_print_threads(outputfile, pid, tid);

	/* Print the results */
	__print_callstack(&callstack, tid);

	/* Clean up */
	callstack_destructor(&callstack);
	dwfl_report_end(dwfl, NULL, NULL);
	dwfl_end(dwfl);
	if (NULL != core) elf_end(core);
	if (-1 != core_fd) close(core_fd);

	return 0;
}