summaryrefslogtreecommitdiff
path: root/src/crash-manager/crash-manager.c
blob: 2627b06189d9b940d905d69347e56ea454ac727b (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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
/*
 * crash-manager
 *
 * 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.
 */

#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <unistd.h>
#include <libgen.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/procfs.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/prctl.h>
#include <sys/file.h>
#include <sys/vfs.h>
#include <gio/gio.h>
#include <iniparser.h>
#include <tzplatform_config.h>
#include <pkgmgr-info.h>
#include "crash-manager.h"
#include "shared/log.h"
#include "shared/util.h"
#include "dbus_notify.h"

#undef LOG_TAG
#define LOG_TAG "CRASH_MANAGER"

/* Parsing */
#define CRASH_CONF_FILE      tzplatform_mkpath(TZ_SYS_ETC, "crash-manager.conf")
#define KEY_MAX              255
#define CRASH_SECTION        "CrashManager"

/* Crash-popup dbus */
#define POPUP_BUS_NAME       "org.tizen.system.popup"
#define POPUP_OBJECT_PATH    "/Org/Tizen/System/Popup/Crash"
#define POPUP_INTERFACE_NAME POPUP_BUS_NAME".Crash"
#define POPUP_METHOD         "PopupLaunch"

/* Configuration default values */
/* note: 0 means unlimited */
#define SYSTEM_MAX_USE       0
#define SYSTEM_KEEP_FREE     0
#define MAX_RETENTION_SEC    0
#define MAX_CRASH_DUMP       0
#define ALLOW_ZIP            true

#define APPID_MAX                   128
#define PKGNAME_MAX                 128

#define CRASH_TEMP_SUBDIR    "/temp/"
#define CRASH_PATH_SUBDIR    "/dump/"


enum {
	RET_EXCEED = 1,
	NUM_EXCEED,
	USAGE_EXCEED
};

enum {
	REP_TYPE_INFO = 0,
	REP_TYPE_FULL
};

#define REP_DEFAULT_TYPE REP_TYPE_FULL

#define REP_TYPE_FULL_STR "FULL"
#define REP_TYPE_INFO_STR "INFO"

struct file_info {
	bool   isdir;
	int    size;
	time_t mtime;
	char   *path;
};

/* Configuration variables */
static int system_max_use;
static int system_keep_free;
static int max_retention_sec;
static int max_crash_dump;
static bool allow_zip;
static char* crash_root_path;
static char* crash_crash_path;
static char* crash_temp_path;
static int report_type;

/* Paths and variables */
static struct crash_info {
	char *pid_info;
	char *tid_info;
	char *sig_info;
	char cmd_line[PATH_MAX];
	char cmd_path[PATH_MAX];
	char time_info[80];
	char temp_dir[PATH_MAX];
	char name[FILENAME_MAX];
	char result_path[PATH_MAX];
	char pfx[PATH_MAX];
	char info_path[PATH_MAX];
	char core_path[PATH_MAX];
	char log_path[PATH_MAX];
	char appid[APPID_MAX];
	char pkgid[PKGNAME_MAX];
#ifdef SYS_ASSERT
	char sysassert_cs_path[PATH_MAX];
	bool have_sysassert_report;
#endif
	int prstatus_fd;
} crash_info;

/* pkgmgrinfo filter list function for getting application ID */
static int appinfo_get_appid_func(pkgmgrinfo_appinfo_h handle,
		void *user_data)
{
	char *str = NULL;
	int ret = PMINFO_R_ERROR;

	pkgmgrinfo_appinfo_get_appid(handle, &str);
	if (str) {
		(*(char **)user_data) = strdup(str);
		ret = PMINFO_R_OK;
	}
	return ret;
}

/* get application ID by pkgmgrinfo filter */
static int get_appid(char *exepath, char *appid, int len)
{
	pkgmgrinfo_appinfo_filter_h handle = NULL;
	int count, ret;
	char *aid = NULL;

	ret = pkgmgrinfo_appinfo_filter_create(&handle);
	if (ret != PMINFO_R_OK) {
		ret = -1;
		goto out;
	}

	ret = pkgmgrinfo_appinfo_filter_add_string(handle, PMINFO_APPINFO_PROP_APP_EXEC, exepath);
	if (ret != PMINFO_R_OK) {
		ret = -1;
		goto out_free;
	}

	ret = pkgmgrinfo_appinfo_filter_count(handle, &count);
	if (ret != PMINFO_R_OK) {
		ret = -1;
		goto out_free;
	}

	if (count < 1) {
		ret = -1;
		goto out_free;
	}

	ret = pkgmgrinfo_appinfo_filter_foreach_appinfo(handle, appinfo_get_appid_func, &aid);
	if (ret != PMINFO_R_OK) {
		ret = -1;
		goto out_free;
	}
	if (aid) {
		snprintf(appid, len, "%s", aid);
		ret = 0;
		free(aid);
	}

out_free:
	pkgmgrinfo_appinfo_filter_destroy(handle);
out:
	return ret;
}

/* get package ID by appid */
static int get_pkgid(char *appid, char *pkgid, int len)
{
	pkgmgrinfo_appinfo_h handle = NULL;
	int ret;
	char *pkid = NULL;

	ret = pkgmgrinfo_appinfo_get_appinfo(appid, &handle);
	if (ret != PMINFO_R_OK) {
		ret = -1;
		goto out;
	}
	ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkid);
	if (ret != PMINFO_R_OK) {
		ret = -1;
		goto out_free;
	}
	snprintf(pkgid, len, "%s", pkid);

out_free:
	pkgmgrinfo_appinfo_destroy_appinfo(handle);
out:
	return ret;
}

static int prepare_paths(void)
{
	if (asprintf(&crash_crash_path, "%s%s", crash_root_path, CRASH_PATH_SUBDIR) < 0) {
		_E("Couldn't write crash_crash_path: %m\n");
		crash_crash_path = NULL;
		return 0;
	}

	if (asprintf(&crash_temp_path, "%s%s", crash_root_path, CRASH_TEMP_SUBDIR) < 0) {
		_E("Couldn't write crash_temp_path: %m\n");
		crash_temp_path = NULL;
		return 0;
	}

	return 1;
}

static const char* report_type_to_str(const int report_type)
{
	switch (report_type) {
	case REP_TYPE_INFO:
		return REP_TYPE_INFO_STR;
		break;
	case REP_TYPE_FULL:
		return REP_TYPE_FULL_STR;
	default:
		return NULL;
		break;
	}
}

static int report_type_from_str(const char* report_type_str)
{
	if (report_type_str == NULL)
		return -1;

	if (strncmp(report_type_str, REP_TYPE_FULL_STR, strlen(REP_TYPE_FULL_STR)) == 0)
		return REP_TYPE_FULL;
	else if (strncmp(report_type_str, REP_TYPE_INFO_STR, strlen(REP_TYPE_INFO_STR)) == 0)
		return REP_TYPE_INFO;

	return -1;
}

static int get_config(void)
{
	dictionary *ini = NULL;
	char key[KEY_MAX];
	int value;
	int result = 1;
	char *value_str;

	system_max_use = SYSTEM_MAX_USE;
	system_keep_free = SYSTEM_KEEP_FREE;
	max_retention_sec = MAX_RETENTION_SEC;
	max_crash_dump = MAX_CRASH_DUMP;
	allow_zip = ALLOW_ZIP;
	crash_root_path = strdup(CRASH_ROOT_PATH);
	if (crash_root_path == NULL) {
		_E("strdup error: %m\n");
		return -1;
	}
	report_type = REP_DEFAULT_TYPE;

	ini = iniparser_load(CRASH_CONF_FILE);
	if (!ini) {
		_E("Failed to load conf file %s", CRASH_CONF_FILE);
		return 0;
	}

	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "SystemMaxUse");
	value = iniparser_getint(ini, key, -1);
	if (value < 0) {
		_D("Invalid value for SystemMaxUse. Use default value [ %d kbyte]",
				SYSTEM_MAX_USE);
	} else {
		_D("SystemMaxUse [ %d kbyte]", value);
		system_max_use = value;
	}

	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "SystemKeepFree");
	value = iniparser_getint(ini, key, -1);
	if (value < 0) {
		_D("Invalid value for SystemKeepFree. Use default value [ %d kbyte]",
				SYSTEM_KEEP_FREE);
	} else {
		_D("SystemKeepFree [ %d kbyte]", value);
		system_keep_free = value;
	}


	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "MaxRetentionSec");
	value = iniparser_getint(ini, key, -1);
	if (value < 0) {
		_D("Invalid value for MaxRetentionSec. Use default value [ %d ]",
				MAX_RETENTION_SEC);
	} else {
		_D("MaxRetentionSec [ %d ]", value);
		max_retention_sec = value;
	}

	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "MaxCrashDump");
	value = iniparser_getint(ini, key, -1);
	if (value < 0) {
		_D("Invalid value for MaxCrashDump. Use default value [ %d ]",
				MAX_CRASH_DUMP);
	} else {
		_D("MaxCrashDump [ %d ]", value);
		max_crash_dump = value;
	}

	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "AllowZip");
	value = iniparser_getboolean(ini, key, -1);
	if (value < 0) {
		_D("Invalid value for AllowZip. Use default value [ %s ]",
				ALLOW_ZIP ? "true" : "false");
	} else {
		_D("AllowZip [ %s ]", value ? "true" : "false");
		allow_zip = value;
	}

	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "CrashRootPath");
	value_str = iniparser_getstring(ini, key, NULL);
	if (value_str == NULL) {
		_D("Invalid value for CrashRootPath. Use default value [ %s ]",
				CRASH_ROOT_PATH);
	} else {
		_D("CrashRootPath [ %s ]", value_str);
		free(crash_root_path);
		crash_root_path = strdup(value_str);
		if (crash_root_path == NULL) {
			_E("strdup error: %m\n");
			result = -1;
			goto out;
		}
	}

	snprintf(key, sizeof(key), "%s:%s", CRASH_SECTION, "ReportType");
	value_str = iniparser_getstring(ini, key, NULL);
	if (value_str == NULL) {
		_D("Invalid value for ReportType. Use default value [ %s ]",
				report_type_to_str(report_type));
	} else {
		_D("ReportType [ %s ]", value_str);
		report_type = report_type_from_str(value_str);

		if (report_type < 0) {
			_E("Unknown ReportType %s. Fallback to default: %s",
			   value_str, report_type_to_str(REP_DEFAULT_TYPE));
			report_type = REP_DEFAULT_TYPE;
		}
	}

out:
	iniparser_freedict(ini);
	return result;
}

static int make_dump_dir(void)
{
	struct stat st;

	if (!stat(crash_crash_path, &st)) {
		if (!(st.st_mode & S_IFDIR)) {
			_E("%s (not DIR) is already exist", crash_crash_path);
			return -1;
		}
	} else {
		if (mkdir(crash_crash_path, 0775) < 0) {
			_E("Failed to mkdir for %s", crash_crash_path);
			return -1;
		}
	}

	if (!stat(crash_temp_path, &st)) {
		if (!(st.st_mode & S_IFDIR)) {
			_E("%s (not DIR) is already exist", crash_temp_path);
			return -1;
		}
	} else {
		if (mkdir(crash_temp_path, 0775) < 0) {
			_E("Failed to mkdir for %s", crash_temp_path);
			return -1;
		}
	}

	return 0;
}

static int get_cmd_info(struct crash_info *cinfo)
{
	return get_cmd_line(cinfo->pid_info, cinfo->cmd_line, sizeof(cinfo->cmd_path)) &&
						get_exe_path(cinfo->pid_info, cinfo->cmd_path, sizeof(cinfo->cmd_path));
}

static int set_prstatus()
{
	int ret;
	char prstatus_name[NAME_MAX+1];

	ret = snprintf(prstatus_name, NAME_MAX, "/%s.prstatus", crash_info.pid_info);
	if (ret < 0) {
		_E("Failed to snprintf for prstatus path");
		goto close_fd;
	}

	crash_info.prstatus_fd = shm_open(prstatus_name, O_RDWR | O_CREAT, 0600);
	if (crash_info.prstatus_fd < 0) {
		_E("shm_open: %m");
		goto close_fd;
	}

	ret = shm_unlink(prstatus_name);
	if (ret < 0) {
		_E("shm_unlink: %m");
		goto close_fd;
	}

	ret = fcntl(crash_info.prstatus_fd, F_GETFD);
	if (ret < 0) {
		_E("fcntl(): %m");
		goto close_fd;
	}

	ret = fcntl(crash_info.prstatus_fd, F_SETFD, ret & ~FD_CLOEXEC);
	if (ret < 0) {
		_E("fcntl(): %m");
		goto close_fd;
	}

	ret = ftruncate(crash_info.prstatus_fd, sizeof(struct elf_prstatus));
	if (ret < 0) {
		_E("ftruncate(): %m");
		goto close_fd;
	}

	return 0;

close_fd:
	if (crash_info.prstatus_fd >= 0)
		close(crash_info.prstatus_fd);
	return -1;
}

static int set_crash_info(int argc, char *argv[])
{
	int ret;
	char *temp_dir_ret = NULL;
	time_t time_val;
	struct tm loc_tm;

	crash_info.pid_info = argv[1];
	crash_info.sig_info = argv[4];
	if (argc > 6) {
		crash_info.tid_info = strdup(argv[6]);
		if (crash_info.tid_info == NULL) {
			_E("strdup error: %m");
			return -1;
		}
	} else {
		crash_info.tid_info = NULL;
		int pid = atoi(crash_info.pid_info);
		int tid = find_crash_tid(pid);
		if (tid < 0) {
			_I("TID not found");
			tid = pid;
		}

		if (asprintf(&crash_info.tid_info, "%d", tid) == -1) {
			_E("asprintf error: %m");
			return -1;
		}
	}

	ret = get_cmd_info(&crash_info);
	if (ret <= 0) {
		_E("Failed to get command info");
		return -1;
	}

	time_val = atoll(argv[5]);
	localtime_r(&time_val, &loc_tm);
	strftime(crash_info.time_info, sizeof(crash_info.time_info),
			"%Y%m%d%H%M%S", &loc_tm);

	ret = snprintf(crash_info.temp_dir, sizeof(crash_info.temp_dir),
			"%s/crash.XXXXXX", crash_temp_path);
	if (ret < 0) {
		_E("Failed to snprintf for temp_dir");
		return -1;
	}
	temp_dir_ret = mkdtemp(crash_info.temp_dir);
	if (!temp_dir_ret || access(temp_dir_ret, F_OK)) {
		_E("Failed to mkdtemp for temp_dir");
		return -1;
	}

	ret = snprintf(crash_info.name, sizeof(crash_info.name), "%s_%s_%s",
			basename(crash_info.cmd_line),
			crash_info.pid_info,
			crash_info.time_info);
	if (ret < 0) {
		_E("Failed to snprintf for name");
		goto rm_temp;
	}

	if (allow_zip)
		ret = snprintf(crash_info.result_path,
				sizeof(crash_info.result_path),
				"%s/%s.zip", crash_crash_path, crash_info.name);
	else
		ret = snprintf(crash_info.result_path,
				sizeof(crash_info.result_path),
				"%s/%s", crash_crash_path, crash_info.name);
	if (ret < 0) {
		_E("Failed to snprintf for result path");
		goto rm_temp;
	}

	ret = snprintf(crash_info.pfx, sizeof(crash_info.pfx), "%s/%s",
			crash_info.temp_dir, crash_info.name);
	if (ret < 0) {
		_E("Failed to snprintf for pfx");
		goto rm_temp;
	}
	ret = mkdir(crash_info.pfx, 0775);
	if (ret < 0) {
		_E("Failed to mkdir for %s", crash_info.pfx);
		goto rm_temp;
	}

	ret = snprintf(crash_info.info_path, sizeof(crash_info.info_path),
			"%s/%s.info", crash_info.pfx, crash_info.name);
	if (ret < 0) {
		_E("Failed to snprintf for info path");
		goto rm_temp;
	}

	ret = snprintf(crash_info.core_path, sizeof(crash_info.core_path),
			"%s/%s.coredump", crash_info.pfx, crash_info.name);
	if (ret < 0) {
		_E("Failed to snprintf for core path");
		goto rm_temp;
	}

	ret = snprintf(crash_info.log_path, sizeof(crash_info.log_path),
			"%s/%s.log", crash_info.pfx, crash_info.name);
	if (ret < 0) {
		_E("Failed to snprintf for log path");
		goto rm_temp;
	}

#ifdef SYS_ASSERT
	ret = snprintf(crash_info.sysassert_cs_path,
			sizeof(crash_info.sysassert_cs_path),
		       "/tmp/crash_stack/%s_%s.info",
		       basename(crash_info.cmd_line), crash_info.pid_info);
	if (ret < 0) {
		_E("Failed to snprintf for sys-assert callstack path");
		goto rm_temp;
	}
#endif

	if (set_prstatus() < 0)
		goto rm_temp;

	if (get_appid(crash_info.cmd_line, crash_info.appid, sizeof(crash_info.appid)) < 0) {
		snprintf(crash_info.appid, sizeof(crash_info.appid), "%s", basename(crash_info.cmd_line));
		snprintf(crash_info.pkgid, sizeof(crash_info.pkgid), "%s", basename(crash_info.cmd_line));
	} else {
		if (get_pkgid(crash_info.appid, crash_info.pkgid, sizeof(crash_info.pkgid)) < 0)
			snprintf(crash_info.pkgid, sizeof(crash_info.pkgid), "%s", crash_info.appid);
	}

	return 0;

rm_temp:
	remove_dir(crash_info.temp_dir, 1);
	return -1;
}

#ifdef SYS_ASSERT
static int get_sysassert_cs(void)
{
	int ret;
	char move_path[PATH_MAX];

	if (access(crash_info.sysassert_cs_path, F_OK)) {
		_E("The sys-assert cs file not found: %s",
			crash_info.sysassert_cs_path);
		crash_info.have_sysassert_report = 0;
		return -1;
	} else
		crash_info.have_sysassert_report = 1;

	ret = snprintf(move_path, sizeof(move_path), "%s/%s",
			crash_info.pfx, basename(crash_info.sysassert_cs_path));
	if (ret < 0) {
		_E("Failed to snprintf for move path");
		return -1;
	}

	if (move_file(crash_info.sysassert_cs_path, move_path) < 0) {
		_E("Failed to move %s to %s",
				crash_info.sysassert_cs_path, move_path);
		return -1;
	}

	return 0;
}
#endif

#ifdef TIZEN_ENABLE_COREDUMP
static void launch_crash_popup(void)
{
	GDBusConnection *conn;
	GVariantBuilder *builder;
	GVariant *parameters = NULL;
	GVariant *reply = NULL;
	GError *error = NULL;
	int ret;

	conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
	if (error) {
		_E("Failed to get dbus: %s", error->message);
		g_error_free(error);
		return;
	}

	builder = g_variant_builder_new(G_VARIANT_TYPE("a{ss}"));
	g_variant_builder_add(builder, "{ss}", "_SYSPOPUP_CONTENT_", "crash");
	g_variant_builder_add(builder, "{ss}", "_PROCESS_NAME_",
			basename(crash_info.cmd_line));
	g_variant_builder_add(builder, "{ss}", "_EXEPATH_", crash_info.cmd_path);
	parameters = g_variant_new("(a{ss})", builder);
	g_variant_builder_unref(builder);

	reply = g_dbus_connection_call_sync(conn,
					    POPUP_BUS_NAME,
					    POPUP_OBJECT_PATH,
					    POPUP_INTERFACE_NAME,
					    POPUP_METHOD,
					    parameters,
					    G_VARIANT_TYPE("(i)"),
					    G_DBUS_CALL_FLAGS_NONE,
					    120000,
					    NULL,
					    &error);
	if (error) {
		_E("Failed to get reply: %s", error->message);
		g_error_free(error);
		goto exit;
	}

	g_variant_get(reply, "(i)", &ret);
	_I("Crash_popup is launched: (%d)", ret);

exit:
	if (reply)
		g_variant_unref(reply);
	if (parameters)
		g_variant_unref(parameters);
}
#endif

static int dump_system_state(void)
{
	int ret;
	char command[PATH_MAX];

	ret = snprintf(command, sizeof(command),
			"/usr/bin/dump_systemstate -d -k -f %s",
			crash_info.log_path);
	if (ret < 0) {
		_E("Failed to snprintf for dump_systemstate command");
		return -1;
	}

	return system_command_parallel(command);
}
#ifdef TIZEN_ENABLE_COREDUMP
static void execute_crash_pipe(int argc, char *argv[])
{
	int ret;
	char command[PATH_MAX];

	/* Execute crash-pipe */
	ret = snprintf(command, sizeof(command),
			"%s --save-core %s",
			CRASH_PIPE_PATH,
			crash_info.core_path);
	if (ret < 0) {
		_E("Failed to snprintf for crash-pipe command");
		return;
	}
	system_command(command);
}
#endif /* TIZEN_ENABLE_COREDUMP */

#ifdef TIZEN_FEATURE_PTRACE_CALLSTACK
static void execute_crash_stack(int argc, char *argv[])
{
	int ret;
	char command[PATH_MAX];

	char prstatus_fd_str[11];

	if (snprintf(prstatus_fd_str, sizeof(prstatus_fd_str), "%d", crash_info.prstatus_fd) == -1)
		snprintf(prstatus_fd_str, sizeof(prstatus_fd_str), "-1");

	/* Execute crash-stack */
	if (argc > 8)
		ret = snprintf(command, sizeof(command),
				"%s --pid %s --tid %s --sig %s --prstatus_fd %d > %s",
				CRASH_STACK_PATH,
				crash_info.pid_info,
				crash_info.tid_info,
				crash_info.sig_info,
				crash_info.prstatus_fd,
				crash_info.info_path);
	else
		ret = snprintf(command, sizeof(command),
				"%s --pid %s --tid %s --sig %s --prstatus_fd %d > %s",
				CRASH_STACK_PATH,
				crash_info.pid_info,
				crash_info.tid_info,
				crash_info.sig_info,
				crash_info.prstatus_fd,
				crash_info.info_path);
	if (ret < 0) {
		_E("Failed to snprintf for crash-stack command");
		return;
	}
	system_command(command);
}
#endif /* TIZEN_FEATURE_PTRACE_CALLSTACK */

static void execute_crash_modules(int argc, char *argv[])
{
	_D("Execute crash module: ");

#ifdef TIZEN_ENABLE_COREDUMP
	if (report_type >= REP_TYPE_FULL)
		execute_crash_pipe(argc, argv);
#endif

#ifdef TIZEN_FEATURE_PTRACE_CALLSTACK

# ifdef SYS_ASSERT
	/* Use process_vm_readv() version as fallback if sys-assert
	 * failed to generate report */
	if (crash_info.have_sysassert_report)
		return;
# endif
	execute_crash_stack(argc, argv);
#endif /* TIZEN_FEATURE_PTRACE_CALLSTACK */
}

static int lock_dumpdir(void)
{
	int fd;

	if ((fd = open(crash_crash_path, O_RDONLY | O_DIRECTORY)) < 0) {
		_E("Failed to open %s", crash_crash_path);
		return -1;
	}

	if (flock(fd, LOCK_EX) < 0) {
		_E("Failed to flock (LOCK)");
		return -1;
	}

	return fd;
}

static void unlock_dumpdir(int fd)
{
	if (flock(fd, LOCK_UN) < 0)
		_E("Failed to unlink (UNLOCK)");
	close(fd);
}

static int dump_filter(const struct dirent *de)
{
	if (de->d_name[0] == '.')
		return 0;
	return 1;
}

static int mtime_cmp(const void *_a, const void *_b)
{
	const struct file_info *a = _a;
	const struct file_info *b = _b;

	if (a->mtime < b->mtime)
		return -1;
	if (a->mtime > b->mtime)
		return 1;
	return 0;
}

static int scan_dump(struct file_info **dump_list, size_t *usage)
{
	struct file_info *temp_list;
	struct dirent **scan_list = NULL;
	struct stat st;
	int i, scan_num, dump_num = 0;
	int fd;

	if ((fd = open(crash_crash_path, O_DIRECTORY)) < 0) {
		_E("Failed to open %s", crash_crash_path);
		return -1;
	}

	scan_num = scandir(crash_crash_path, &scan_list, &dump_filter, NULL);
	if (scan_num < 0) {
		close(fd);
		return -1;
	}

	temp_list = (struct file_info *)calloc(scan_num,
			sizeof(struct file_info));
	if (!temp_list) {
		_E("Failed to calloc for dump list");
		goto exit;
	}

	for (i = 0; i < scan_num; i++) {
		if (fstatat(fd, scan_list[i]->d_name, &st, 0) < 0) {
			_E("Failed to fstatat");
			continue;
		}

		if (asprintf(&(temp_list[dump_num].path), "%s/%s",
					crash_crash_path, scan_list[i]->d_name) < 0) {
			_E("Failed to asprintf");
			continue;
		}

		if (scan_list[i]->d_type == DT_DIR) {
			temp_list[dump_num].isdir = 1;
			temp_list[dump_num].size =
				get_directory_usage(temp_list[dump_num].path);
		} else {
			temp_list[dump_num].isdir = 0;
			temp_list[dump_num].size = st.st_size;
		}
		temp_list[dump_num].mtime = st.st_mtime;
		dump_num++;
	}

	if (dump_num <= 0) {
		free(temp_list);
		goto exit;
	}

	if (dump_num != scan_num)
		temp_list = (struct file_info *)realloc(temp_list,
				dump_num * sizeof(struct file_info));

	qsort(temp_list, dump_num, sizeof(struct file_info), mtime_cmp);

	*usage = 0;
	for (i = 0; i < dump_num; i++) {
		_D("[%d] path: %s(%s), size: %d kb, mtime: %s",
				i,
				temp_list[i].path,
				temp_list[i].isdir ? "DIR" : "FILE",
				temp_list[i].size / 1024,
				ctime(&(temp_list[i].mtime)));
		*usage += temp_list[i].size;
	}
	*dump_list = temp_list;
exit:
	for (i = 0; i < scan_num; i++)
		free(scan_list[i]);
	free(scan_list);
	close(fd);

	return dump_num;
}

static int check_disk_available(const char *path, int check_size)
{
	struct statfs lstatfs;
	int avail_size = 0;

	if (!path)
		return -1;

	if (statfs(path, &lstatfs) < 0)
		return -1;
	avail_size = (int)(lstatfs.f_bavail * (lstatfs.f_bsize / 1024));

	if (check_size > avail_size) {
		_I("avail_size is (%d)", avail_size);
		return -1;
	}

	return 0;
}

static int remove_file(struct file_info file)
{
	if (file.isdir)
		return remove_dir(file.path, 1);
	else
		return unlink(file.path);
}

static void clean_dump(void)
{
	struct file_info *dump_list = NULL;
	int i, scan_num, dump_num, remove_flag;
	size_t usage = 0;
	time_t cur_time;

	scan_num = scan_dump(&dump_list, &usage);
	if (scan_num <= 0)
		return;

	dump_num = scan_num;

	cur_time = time(NULL);

	for (i = 0; i < scan_num; i++) {
		remove_flag = 0;

		/* Retention time check */
		if (max_retention_sec &&
			dump_list[i].mtime > 0 &&
			dump_list[i].mtime + max_retention_sec < cur_time)
			remove_flag = RET_EXCEED;
		/* Check the number of dumps */
		else if (max_crash_dump &&
			0 < dump_num && max_crash_dump < dump_num)
			remove_flag = NUM_EXCEED;
		/* Check the max system use size */
		else if (system_max_use &&
			0 < dump_num && system_max_use < usage / 1024)
			remove_flag = USAGE_EXCEED;

		switch (remove_flag) {
		case RET_EXCEED:
			_I("Reached the maximum retention time %d, so remove (%s)",
					max_retention_sec, dump_list[i].path);
			break;
		case NUM_EXCEED:
			_I("Reached the maximum number of dump %d/%d, so remove (%s)",
					dump_num, max_crash_dump,
					dump_list[i].path);
			break;
		case USAGE_EXCEED:
			_I("Reached the maximum disk usage %d/%d kb, so remove (%s)",
					usage / 1024, system_max_use,
					dump_list[i].path);
			break;
		default:
			break;
		}

		if (!remove_flag)
			continue;

		if (remove_file(dump_list[i]) < 0) {
			_E("Failed to remove %s", dump_list[i].path);
			continue;
		}
		dump_num--;
		usage -= dump_list[i].size;
	}

	/* Check disk free space to keep */
	if (system_keep_free &&
			check_disk_available(crash_root_path,
					     system_keep_free) < 0) {
		_I("Disk is not available! so set the maximum number of dump to 1");
		max_crash_dump = 1;
	}

	for (i = 0; i < dump_num; i++)
		free(dump_list[i].path);
	free(dump_list);
}

static void compress(void)
{
	int ret, lock_fd;
	char zip_path[PATH_MAX];
	char command[PATH_MAX];

	ret = snprintf(zip_path, sizeof(zip_path), "%s/report.zip",
			crash_info.temp_dir);
	if (ret < 0) {
		_E("Failed to snprintf for zip path");
		return;
	}

	ret = snprintf(command, sizeof(command), "cd %s && /bin/zip -r %s %s > /dev/null 2>&1",
			crash_info.temp_dir, zip_path, crash_info.name);
	if (ret < 0) {
		_E("Failed to snprintf for zip command");
		return;
	}
	system_command(command);

	if ((lock_fd = lock_dumpdir()) < 0)
		return;
	if (!rename(zip_path, crash_info.result_path))
		clean_dump();
	else
		_E("Failed to move %s to %s", zip_path, crash_info.result_path);
	unlock_dumpdir(lock_fd);

	if (remove_dir(crash_info.temp_dir, 1) < 0)
		_E("Failed to delete temp directory");
}

static void move_dump_dir(void)
{
	int lock_fd;

	if ((lock_fd = lock_dumpdir()) < 0)
		return;
	if (!rename(crash_info.pfx, crash_info.result_path))
		clean_dump();
	else
		_E("Failed to move %s to %s",
				crash_info.pfx, crash_info.result_path);
	unlock_dumpdir(lock_fd);

	if (remove_dir(crash_info.temp_dir, 1) < 0)
		_E("Failed to delete temp directory");
}

static void move_info_file(void)
{
	int lock_fd;

	if ((lock_fd = lock_dumpdir()) < 0)
		return;

	snprintf(crash_info.result_path, sizeof(crash_info.result_path), "%s/%s.info",
			 crash_crash_path, crash_info.name);
	if (!rename(crash_info.info_path, crash_info.result_path))
		clean_dump();
	else
		_E("Failed to move %s to %s",
		   crash_info.info_path, crash_info.result_path);

	unlock_dumpdir(lock_fd);
	if (remove_dir(crash_info.temp_dir, 1) < 0)
		_E("Failed to delete temp directory");
}

int main(int argc, char *argv[])
{
	/* Execute dump_systemstate in parallel */
	static int dump_state_pid;
#ifdef TIZEN_ENABLE_COREDUMP
	int debug_mode = access(DEBUGMODE_PATH, F_OK) == 0;
#endif
	int res = 0;

	prctl(PR_SET_DUMPABLE, 0);
	/* Get Configuration */
	if (get_config() < 0) {
		res = EXIT_FAILURE;
		goto exit;
	}

	/* Prepare paths */
	if (!prepare_paths()) {
		res = EXIT_FAILURE;
		goto exit;
	}

	/* Create crash directories */
	if (make_dump_dir() < 0) {
		res = EXIT_FAILURE;
		goto exit;
	}

	/* Set crash info */
	if (set_crash_info(argc, argv) < 0) {
		res = EXIT_FAILURE;
		goto exit;
	}

#ifdef SYS_ASSERT
	/* Fetch callstack of sys-assert */
	get_sysassert_cs();
#endif

	if (report_type >= REP_TYPE_FULL) {
		/* Exec dump_systemstate */
		dump_state_pid = dump_system_state();
	}
	/* Exec crash modules */
	execute_crash_modules(argc, argv);

	if (report_type >= REP_TYPE_FULL) {
		/* Wait dump_system_state */
		wait_system_command(dump_state_pid);

		/* Tar compression */
		if (allow_zip)
			compress();
		else
			move_dump_dir();
	} else {
		move_info_file();
	}
#ifdef TIZEN_ENABLE_COREDUMP
	/* launch crash-popup only if the .debugmode file is exist*/
	if (debug_mode)
		launch_crash_popup();
#endif

	struct NotifyParams notify_params = {
		.prstatus_fd = crash_info.prstatus_fd,
		.pid = strtol(crash_info.pid_info, NULL, 10),
		.tid = strtol(crash_info.tid_info, NULL, 10),
		.cmd_name = basename(crash_info.cmd_line),
		.cmd_path = crash_info.cmd_path,
		.report_path = crash_info.result_path,
		.appid = crash_info.appid,
		.pkgid = crash_info.pkgid
	};

	send_notify(&notify_params);

exit:
	close(crash_info.prstatus_fd);
	free(crash_info.tid_info);
	free(crash_temp_path);
	free(crash_root_path);
	free(crash_crash_path);

	return res;
}