Capability setting for gdbserver
[framework/appfw/debug-launchpad.git] / src / launchpad.c
1 /*
2  *  debug-launchpad
3  *
4  * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Contact: Jungmin Cho <chivalry.cho@samsung.com>, Gwangho Hwang <gwang.hwang@samsung.com>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21
22 /*
23  * simple AUL daemon - launchpad 
24  */
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <dlfcn.h>
29 #include <X11/Xlib.h>
30 #include <sys/types.h>
31 #include <signal.h>
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <stdlib.h>
35 #include <sys/wait.h>
36 #include <poll.h>
37 #include <sys/prctl.h>
38 #include <malloc.h>
39
40 #include "app_sock.h"
41 #include "aul.h"
42
43 #include "config.h"
44
45 #include "menu_db_util.h"
46 #include "simple_util.h"
47 #include "access_control.h"
48 #include "preload.h"
49 #include "preexec.h"
50 #include "perf.h"
51 #include "sigchild.h"
52 #include "aul_util.h"
53
54 #include "heap_dbg.h"
55
56 #include "gl.h"
57
58 #include <sqlite3.h>
59 #include <sys/smack.h>
60 #include "fileutils.h"
61 #include <sys/capability.h>
62
63 #define _static_ static inline
64 #define POLLFD_MAX 1
65 #define SQLITE_FLUSH_MAX        (1048576)       /* (1024*1024) */
66 #define AUL_POLL_CNT            15
67 #define AUL_PR_NAME                     16
68 #define APPID_LEN       10
69 #define PATH_TMP "/tmp"
70 #define PATH_DATA "/data"
71
72 #define SDK_CODE_COVERAGE "CODE_COVERAGE"
73 #define SDK_DEBUG "DEBUG"
74 #define SDK_DYNAMIC_ANALYSIS "DYNAMIC_ANALYSIS"
75 #define SDK_UNIT_TEST "UNIT_TEST"
76 #define SDK_VALGRIND "VALGRIND"
77
78 /* DLP is short for debug-launchpad */
79 #define DLP_K_DEBUG_ARG "__DLP_DEBUG_ARG__"
80 #define DLP_K_UNIT_TEST_ARG "__DLP_UNIT_TEST_ARG__"
81 #define DLP_K_VALGRIND_ARG "__DLP_VALGRIND_ARG__"
82
83 #define PATH_GDBSERVER  "/home/developer/sdk_tools/gdbserver/gdbserver"
84 #define PATH_VALGRIND   "/home/developer/sdk_tools/valgrind/usr/bin/valgrind"
85 #define PATH_DA_SO      "/usr/lib/da_probe_osp.so"
86 #define PATH_NATIVE_APP "/opt/apps/"
87
88 #define OPT_VALGRIND_LOGFILE            "--log-file="
89 #define OPT_VALGRIND_LOGFILE_FIXED      "--log-file=/tmp/valgrind_result.txt"
90 #define PATH_VALGRIND_LOGFILE           "/tmp/valgrind_result.txt"
91 #define OPT_VALGRIND_XMLFILE            "--xml-file="
92 #define OPT_VALGRIND_XMLFILE_FIXED      "--xml-file=/tmp/valgrind_result.xml"
93 #define PATH_VALGRIND_XMLFILE           "/tmp/valgrind_result.xml"
94
95 #if (ARCH==arm)
96 #define PATH_MEMCHECK   "/opt/home/developer/sdk_tools/valgrind/usr/lib/valgrind/memcheck-arm-linux"
97 #elif (ARCH==x86)
98 #define PATH_MEMCHECK   "/opt/home/developer/sdk_tools/valgrind/usr/lib/valgrind/memcheck-x86-linux"
99 #endif
100
101 #define POLL_VALGRIND_LOGFILE           0x00000001
102 #define POLL_VALGRIND_XMLFILE           0x00000002
103
104 #define CAPABILITY_SET_ORIGINAL         0
105 #define CAPABILITY_SET_INHERITABLE      1
106
107 static int need_to_set_inh_cap_after_fork = 0;
108 static char *launchpad_cmdline;
109 static int initialized = 0;
110
111 static int poll_outputfile = 0;
112
113 void __set_oom();
114 void __set_env(app_info_from_db * menu_info, bundle * kb);
115 int __prepare_exec(const char *pkg_name,
116                             const char *app_path, app_info_from_db * menu_info,
117                             bundle * kb);
118 int __fake_launch_app(int cmd, int pid, bundle * kb);
119 char **__create_argc_argv(bundle * kb, int *margc, const char *app_path);
120 int __normal_fork_exec(int argc, char **argv);
121 void __real_launch(const char *app_path, bundle * kb);
122 static inline int __parser(const char *arg, char *out, int out_size);
123 void __modify_bundle(bundle * kb, int caller_pid,
124                             app_info_from_db * menu_info, int cmd);
125 int __send_to_sigkill(int pid);
126 int __term_app(int pid);
127 void __real_send(int clifd, int ret);
128 void __send_result_to_caller(int clifd, int ret);
129 void __launchpad_main_loop(int main_fd);
130 int __launchpad_pre_init(int argc, char **argv);
131 int __launchpad_post_init();
132
133 extern ail_error_e ail_db_close(void);
134
135
136
137 void __set_oom()
138 {
139         char buf[MAX_LOCAL_BUFSZ];
140         FILE *fp;
141
142         /* we should reset oomadj value as default because child 
143         inherits from parent oom_adj*/
144         snprintf(buf, MAX_LOCAL_BUFSZ, "/proc/%d/oom_adj", getpid());
145         fp = fopen(buf, "w");
146         if (fp == NULL)
147                 return;
148         fprintf(fp, "%d", -16);
149         fclose(fp);
150 }
151
152 void __set_sdk_env(app_info_from_db* menu_info, char* str) {
153         char buf_pkgname[MAX_LOCAL_BUFSZ];
154         char buf[MAX_LOCAL_BUFSZ];
155         int ret;
156
157         _D("key : %s / value : %s", AUL_K_SDK, str);
158         /* http://gcc.gnu.org/onlinedocs/gcc/Cross_002dprofiling.html*/
159         /* GCOV_PREFIX contains the prefix to add to the absolute paths */
160         /*      in the object file. Prefix can be absolute, or relative.*/
161         /*      The default is no prefix.  */
162         /* GCOV_PREFIX_STRIP indicates the how many initial directory names */
163         /*      to stripoff the hardwired absolute paths. Default value is 0. */
164         if (strncmp(str, SDK_CODE_COVERAGE, strlen(str)) == 0) {
165                 strncpy(buf_pkgname,_get_pkgname(menu_info),MAX_LOCAL_BUFSZ-1);
166                 buf_pkgname[MAX_LOCAL_BUFSZ-1]='\0';
167                 snprintf(buf, MAX_LOCAL_BUFSZ, PATH_TMP"/%s"PATH_DATA
168                         , strtok(buf_pkgname,"."));
169                 ret = setenv("GCOV_PREFIX", buf, 1);
170                 _D("GCOV_PREFIX : %d", ret);
171                 ret = setenv("GCOV_PREFIX_STRIP", "0", 1);
172                 _D("GCOV_PREFIX_STRIP : %d", ret);
173         } else if (strncmp(str, SDK_DYNAMIC_ANALYSIS, strlen(str)) == 0) {
174                 ret = setenv("LD_PRELOAD", PATH_DA_SO, 1);
175                 _D("LD_PRELOAD : %d", ret);
176         }
177 }
178
179
180 void __set_env(app_info_from_db * menu_info, bundle * kb)
181 {
182         const char *str;
183         const char **str_array;
184         int len;
185         int i;
186
187         setenv("PKG_NAME", _get_pkgname(menu_info), 1);
188
189         USE_ENGINE("gl")
190
191         str = bundle_get_val(kb, AUL_K_STARTTIME);
192         if (str != NULL)
193                 setenv("APP_START_TIME", str, 1);
194
195         if(bundle_get_type(kb, AUL_K_SDK) & BUNDLE_TYPE_ARRAY) {
196                 str_array = bundle_get_str_array(kb, AUL_K_SDK, &len);
197                 if(str_array != NULL) {
198                         for (i = 0; i < len; i++) {
199                                 _D("index : [%d]", i);
200                                 __set_sdk_env(menu_info, (char *)str_array[i]);
201                         }
202                 }
203         } else {
204                 str = bundle_get_val(kb, AUL_K_SDK);
205                 if(str != NULL) {
206                         __set_sdk_env(menu_info, (char *)str);
207                 }
208         }
209         if (menu_info->hwacc != NULL)
210                 setenv("HWACC", menu_info->hwacc, 1);
211 }
212
213 int __prepare_exec(const char *pkg_name,
214                             const char *app_path, app_info_from_db * menu_info,
215                             bundle * kb)
216 {
217         char *file_name;
218         char process_name[AUL_PR_NAME];
219         int ret;
220
221         /* Set new session ID & new process group ID*/
222         /* In linux, child can set new session ID without check permission */
223         /* TODO : should be add to check permission in the kernel*/
224         setsid();
225
226         __preexec_run(menu_info->pkg_type, pkg_name, app_path);
227
228         /* SET OOM*/
229         __set_oom();
230
231         /* SET PRIVILEGES*/
232         if(bundle_get_val(kb, AUL_K_PRIVACY_APPID) == NULL) {
233                 _D("pkg_name : %s / pkg_type : %s / app_path : %s ", pkg_name
234                         , menu_info->pkg_type, app_path);
235                 if ((ret = __set_access(pkg_name, menu_info->pkg_type
236                         , app_path)) < 0) 
237                 {
238                          _D("fail to set privileges - check your package's credential : %d\n"
239                                 , ret);
240                         return -1;
241                 }
242         }
243         /* SET DUMPABLE - for coredump*/
244         prctl(PR_SET_DUMPABLE, 1);
245
246         /* SET PROCESS NAME*/
247         if (app_path == NULL) {
248                 _D("app_path should not be NULL - check menu db");
249                 return -1;
250         }
251         file_name = strrchr(app_path, '/') + 1;
252         if (file_name == NULL) {
253                 _D("can't locate file name to execute");
254                 return -1;
255         }
256         memset(process_name, '\0', AUL_PR_NAME);
257         snprintf(process_name, AUL_PR_NAME, "%s", file_name);
258         prctl(PR_SET_NAME, process_name);
259
260         /* SET ENVIROMENT*/
261         __set_env(menu_info, kb);
262
263         return 0;
264 }
265
266 int __fake_launch_app(int cmd, int pid, bundle * kb)
267 {
268         int datalen;
269         int ret;
270         bundle_raw *kb_data;
271
272         bundle_encode(kb, &kb_data, &datalen);
273         if ((ret = __app_send_raw(pid, cmd, kb_data, datalen)) < 0)
274                 _E("error request fake launch - error code = %d", ret);
275         free(kb_data);
276         return ret;
277 }
278
279 char** __add_arg(bundle * kb, char **argv, int *margc, const char *key)
280 {
281         const char *str = NULL;
282         const char **str_array = NULL;
283         int len = 0;
284         int i;
285         char ** new_argv = NULL;
286
287         if(bundle_get_type(kb, key) & BUNDLE_TYPE_ARRAY) {
288                 str_array = bundle_get_str_array(kb, key, &len);
289         } else {
290                 str = bundle_get_val(kb, key);
291                 if(str) {
292                         str_array = &str;
293                         len = 1;
294                 }
295         }
296         if(str_array != NULL) {
297                 if(strncmp(key, DLP_K_DEBUG_ARG, strlen(key)) == 0
298                         || strncmp(key, DLP_K_VALGRIND_ARG, strlen(key)) == 0)
299                 {
300                         new_argv = (char **) realloc(argv
301                                 , sizeof(char *) * (*margc+len+2));
302                         if(!new_argv) {
303                                 _E("realloc fail (key = %s)", key);
304                                 exit(-1);
305                         }
306                         for(i=*margc+len+1; i-(len+1)>=0; i--) {
307                                 new_argv[i] = new_argv[i-(len+1)];
308                         }
309                         // need to add new_argv[0]
310                         for(i=0; i<len; i++) {
311                                 new_argv[1+i] = strdup(str_array[i]);
312                         }
313                         len++;  /* gdbserver or valgrind */
314                         _D("uid : %d", getuid());
315                         _D("euid : %d", geteuid());
316                         _D("gid : %d", getgid());
317                         _D("egid : %d", getegid());
318                 } else {
319                         new_argv = (char **) realloc(argv
320                                 , sizeof(char *) * (*margc+len+1));
321                         if(!new_argv) {
322                                 _E("realloc fail (key = %s)", key);
323                                 exit(-1);
324                         }
325                         for(i=0; i<len; i++) {
326                                 new_argv[*margc+i] = strdup(str_array[i]);
327                         }
328                 }
329                 new_argv[*margc+len] = NULL;
330                 *margc += len;
331         } else {
332                 if(strncmp(key, DLP_K_DEBUG_ARG, strlen(key)) == 0
333                         || strncmp(key, DLP_K_VALGRIND_ARG, strlen(key)) == 0)
334                 {
335                         new_argv = (char **) realloc(argv
336                                 , sizeof(char *) * (*margc+2));
337                         if(!new_argv) {
338                                 _E("realloc fail (key = %s)", key);
339                                 exit(-1);
340                         }
341                         for(i=*margc+1; i-1>=0; i--) {
342                                 new_argv[i] = new_argv[i-1];
343                         }
344                         // need to add new_argv[0]
345                         *margc++;
346                 }
347         }
348
349         if(new_argv==NULL) return argv;
350         return new_argv;
351 }
352
353 char **__create_argc_argv(bundle * kb, int *margc, const char *app_path)
354 {
355         char **argv = NULL;
356         char **new_argv = NULL;
357         int argc;
358
359         const char *str = NULL;
360         const char **str_array = NULL;
361         int len = 0;
362         int i;
363
364         argc = bundle_export_to_argv(kb, &argv);
365         if (argv) {
366                 for(i=1; i<argc; i++) {
367                         argv[i] = strdup(argv[i]);
368                 }
369                 argv[0] = strdup(app_path);
370         } else {
371                 _E("bundle_export_to_argv error");
372                 exit(-1);
373         }
374
375         if(bundle_get_type(kb, AUL_K_SDK) & BUNDLE_TYPE_ARRAY) {
376                 str_array = bundle_get_str_array(kb, AUL_K_SDK, &len);
377         } else {
378                 str = bundle_get_val(kb, AUL_K_SDK);
379                 if(str) {
380                         str_array = &str;
381                         len = 1;
382                 }
383         }
384         if(str_array == NULL) {
385                 *margc = argc;
386                 return argv;
387         }
388
389         for (i = 0; i < len; i++) {
390                 if(str_array[i] == NULL) break;
391                 _D("index : [%d]", i);
392                 /* gdbserver */
393                 if (strncmp(str_array[i], SDK_DEBUG, strlen(str_array[i])) == 0)
394                 {
395                         char buf[MAX_LOCAL_BUFSZ];
396                         if (argv[0]) free(argv[0]);
397                         snprintf(buf,MAX_LOCAL_BUFSZ,"%s.exe",app_path);
398                         argv[0] = strdup(buf);
399                         new_argv = __add_arg(kb, argv, &argc, DLP_K_DEBUG_ARG);
400                         new_argv[0] = strdup(PATH_GDBSERVER);
401                 }
402                 /* valgrind */
403                 else if (strncmp(str_array[i], SDK_VALGRIND
404                         , strlen(str_array[i])) == 0)
405                 {
406                         new_argv = __add_arg(kb, argv, &argc
407                                 , DLP_K_VALGRIND_ARG);
408                         new_argv[0] = strdup(PATH_VALGRIND);
409                 }
410                 /* unit test */
411                 else if (strncmp(str_array[i], SDK_UNIT_TEST
412                         , strlen(str_array[i])) == 0)
413                 {
414                         new_argv = __add_arg(kb, argv, &argc
415                                 , DLP_K_UNIT_TEST_ARG);
416                 }
417         }
418
419         *margc = argc;
420         if(new_argv==NULL) return argv;
421         return new_argv;
422 }
423
424 int __normal_fork_exec(int argc, char **argv)
425 {
426         _D("start real fork and exec\n");
427
428         if (execv(argv[0], argv) < 0) { /* Flawfinder: ignore */
429                 if (errno == EACCES) {
430                         _E("such a file is no executable - %s", argv[0]);
431                 } else {
432                         _E("unknown executable error - %s", argv[0]);
433                 }
434                 return -1;
435         }
436         /* never reach */
437         return 0;
438 }
439
440 void __real_launch(const char *app_path, bundle * kb)
441 {
442         int app_argc;
443         char **app_argv;
444         int i;
445
446         app_argv = __create_argc_argv(kb, &app_argc, app_path);
447
448         for (i = 0; i < app_argc; i++)
449                 _D("input argument %d : %s##", i, app_argv[i]);
450
451         PERF("setup argument done");
452         _D("lock up test log(no error) : setup argument done");
453
454         /* Temporary log: launch time checking */
455         LOG(LOG_DEBUG, "LAUNCH", "[%s:Platform:launchpad:done]", app_path);
456
457         __normal_fork_exec(app_argc, app_argv);
458
459         for(i=0; i<app_argc; i++) {
460                 if(app_argv[i]) free(app_argv[i]);
461         }
462         free(app_argv);
463 }
464
465
466 /*
467  * Parsing original app path to retrieve default bundle
468  *
469  * -1 : Invalid sequence
470  * -2 : Buffer overflow
471  *
472  */
473 static inline int __parser(const char *arg, char *out, int out_size)
474 {
475         register int i;
476         int state = 1;
477         char *start_out = out;
478
479         if (arg == NULL || out == NULL) {
480                 /* Handles null buffer*/
481                 return 0;
482         }
483
484         for (i = 0; out_size > 1; i++) {
485                 switch (state) {
486                 case 1:
487                         switch (arg[i]) {
488                         case ' ':
489                         case '\t':
490                                 state = 5;
491                                 break;
492                         case '\0':
493                                 state = 7;
494                                 break;
495                         case '\"':
496                                 state = 2;
497                                 break;
498                         case '\\':
499                                 state = 4;
500                                 break;
501                         default:
502                                 *out = arg[i];
503                                 out++;
504                                 out_size--;
505                                 break;
506                         }
507                         break;
508                 case 2: /* escape start*/
509                         switch (arg[i]) {
510                         case '\0':
511                                 state = 6;
512                                 break;
513                         case '\"':
514                                 state = 1;
515                                 break;
516                         default:
517                                 *out = arg[i];
518                                 out++;
519                                 out_size--;
520                                 break;
521                         }
522                         break;
523                 case 4: /* character escape*/
524                         if (arg[i] == '\0') {
525                                 state = 6;
526                         } else {
527                                 *out = arg[i];
528                                 out++;
529                                 out_size--;
530                                 state = 1;
531                         }
532                         break;
533                 case 5: /* token*/
534                         if (out != start_out) {
535                                 *out = '\0';
536                                 out_size--;
537                                 return i;
538                         }
539                         i--;
540                         state = 1;
541                         break;
542                 case 6:
543                         return -1;      /* error*/
544                 case 7: /* terminate*/
545                         *out = '\0';
546                         out_size--;
547                         return 0;
548                 default:
549                         state = 6;
550                         break;  /* error*/
551                 }
552         }
553
554         if (out_size == 1) {
555                 *out = '\0';
556         }
557         /* Buffer overflow*/
558         return -2;
559 }
560
561 void __modify_bundle(bundle * kb, int caller_pid,
562                             app_info_from_db * menu_info, int cmd)
563 {
564         bundle_del(kb, AUL_K_PKG_NAME);
565         bundle_del(kb, AUL_K_EXEC);
566         bundle_del(kb, AUL_K_PACKAGETYPE);
567         bundle_del(kb, AUL_K_HWACC);
568
569         /* Parse app_path to retrieve default bundle*/
570         if (cmd == APP_START || cmd == APP_START_RES || cmd == APP_OPEN
571                 || cmd == APP_RESUME)
572         {
573                 char *ptr;
574                 char exe[MAX_PATH_LEN];
575                 int flag;
576
577                 ptr = _get_original_app_path(menu_info);
578
579                 flag = __parser(ptr, exe, sizeof(exe));
580                 if (flag > 0) {
581                         char key[256];
582                         char value[256];
583
584                         ptr += flag;
585                         _D("parsing app_path: EXEC - %s\n", exe);
586
587                         do {
588                                 flag = __parser(ptr, key, sizeof(key));
589                                 if (flag <= 0)
590                                         break;
591                                 ptr += flag;
592
593                                 flag = __parser(ptr, value, sizeof(value));
594                                 if (flag < 0)
595                                         break;
596                                 ptr += flag;
597
598                                 /*bundle_del(kb, key);*/
599                                 bundle_add(kb, key, value);
600                         } while (flag > 0);
601                 } else if (flag == 0) {
602                         _D("parsing app_path: No arguments\n");
603                 } else {
604                         _D("parsing app_path: Invalid argument\n");
605                 }
606         }
607 }
608
609 int __send_to_sigkill(int pid)
610 {
611         int pgid;
612
613         pgid = getpgid(pid);
614         if (pgid <= 1)
615                 return -1;
616
617         if (killpg(pgid, SIGKILL) < 0)
618                 return -1;
619
620         return 0;
621 }
622
623 int __term_app(int pid)
624 {
625         int dummy;
626         if (__app_send_raw
627             (pid, APP_TERM_BY_PID, (unsigned char *)&dummy, sizeof(int)) < 0) {
628                 _D("terminate packet send error - use SIGKILL");
629                 if (__send_to_sigkill(pid) < 0) {
630                         _E("fail to killing - %d\n", pid);
631                         return -1;
632                 }
633         }
634         _D("term done\n");
635         return 0;
636 }
637
638 static int __get_caller_pid(bundle *kb)
639 {
640         const char *pid_str;
641         int pid;
642
643         pid_str = bundle_get_val(kb, AUL_K_ORG_CALLER_PID);
644         if(pid_str)
645                 goto end;
646
647         pid_str = bundle_get_val(kb, AUL_K_CALLER_PID);
648         if (pid_str == NULL)
649                 return -1;
650
651 end:
652         pid = atoi(pid_str);
653         if (pid <= 1)
654                 return -1;
655
656         return pid;
657 }
658
659 int __foward_cmd(int cmd, bundle *kb, int cr_pid)
660 {
661         int pid;
662         char tmp_pid[MAX_PID_STR_BUFSZ];
663         int datalen;
664         bundle_raw *kb_data;
665         int res;
666
667         if ((pid = __get_caller_pid(kb)) < 0)
668                         return AUL_R_ERROR;
669
670         snprintf(tmp_pid, MAX_PID_STR_BUFSZ, "%d", cr_pid);
671
672         bundle_add(kb, AUL_K_CALLEE_PID, tmp_pid);
673
674         bundle_encode(kb, &kb_data, &datalen);
675         if ((res = __app_send_raw_with_noreply(pid, cmd, kb_data, datalen)) < 0)
676                 res = AUL_R_ERROR;
677
678         free(kb_data);
679
680         return res;
681 }
682
683 void __real_send(int clifd, int ret)
684 {
685         if (send(clifd, &ret, sizeof(int), MSG_NOSIGNAL) < 0) {
686                 if (errno == EPIPE) {
687                         _E("send failed due to EPIPE.\n");
688                 }
689                 _E("send fail to client");
690         }
691
692         close(clifd);
693 }
694
695 void __send_result_to_caller(int clifd, int ret)
696 {
697         char *cmdline;
698         int wait_count;
699         int cmdline_changed = 0;
700         int cmdline_exist = 0;
701
702         if (clifd == -1)
703                 return;
704
705         if (ret <= 1) {
706                 __real_send(clifd, ret);
707                 return;
708         }
709         /* check normally was launched?*/
710         wait_count = 1;
711         do {
712                 cmdline = __proc_get_cmdline_bypid(ret);
713                 if (cmdline == NULL) {
714                         _E("error founded when being launched with %d", ret);
715
716                 } else if (strcmp(cmdline, launchpad_cmdline)) {
717                         free(cmdline);
718                         cmdline_changed = 1;
719                         break;
720                 } else {
721                         cmdline_exist = 1;
722                         free(cmdline);
723                 }
724
725                 _D("-- now wait to change cmdline --");
726                 usleep(50 * 1000);      /* 50ms sleep*/
727                 wait_count++;
728         } while (wait_count <= 20);     /* max 50*20ms will be sleep*/
729
730         if ((!cmdline_exist) && (!cmdline_changed)) {
731                 _E("abnormally launched");
732                 __real_send(clifd, -1); /* abnormally launched*/
733                 return;
734         }
735
736         if (!cmdline_changed)
737                 _E("process launched, but cmdline not changed");
738
739         __real_send(clifd, ret);
740         return;
741 }
742
743 static app_info_from_db *_get_app_info_from_bundle_by_pkgname(
744         const char *pkgname, bundle *kb)
745 {
746         app_info_from_db *menu_info;
747
748         menu_info = calloc(1, sizeof(app_info_from_db));
749         if (menu_info == NULL) {
750                 return NULL;
751         }
752
753         menu_info->pkg_name = strdup(pkgname);
754         menu_info->app_path = strdup(bundle_get_val(kb, AUL_K_EXEC));
755         if (menu_info->app_path != NULL)
756                 menu_info->original_app_path = strdup(menu_info->app_path);
757         menu_info->pkg_type = strdup(bundle_get_val(kb, AUL_K_PACKAGETYPE));
758         menu_info->hwacc = strdup(bundle_get_val(kb, AUL_K_HWACC));
759
760         if (!_get_app_path(menu_info)) {
761                 _free_app_info_from_db(menu_info);
762                 return NULL;
763         }
764
765         return menu_info;
766 }
767
768 /**
769  * free after use it
770  */
771 int get_native_appid(const char* app_path, char** appid) {
772         int rc = smack_lgetlabel(app_path, appid, SMACK_LABEL_ACCESS);
773
774         if (rc != 0 || *appid == NULL) {
775                 _E("smack_lgetlabel fail");
776                 return -1;
777         }
778
779         if (strlen(*appid) != APPID_LEN) {
780                 _E("wrong native appid : %s", *appid);
781                 return -1;
782         }
783
784         if (strlen(app_path) < sizeof(PATH_NATIVE_APP)+APPID_LEN-1) {
785                 _E("wrong native app_path : %s", app_path);
786                 return -1;
787         }
788         else if ( strncmp(app_path, PATH_NATIVE_APP, sizeof(PATH_NATIVE_APP)-1)
789                 || strncmp(&app_path[sizeof(PATH_NATIVE_APP)-1]
790                 , *appid,APPID_LEN) )
791         {
792                 _E("wrong native app_path : %s", app_path);
793                 return -1;
794         }
795         
796         _D("get_appid return : %s", *appid);
797         return 0;
798 }
799
800 int apply_smack_rules(const char* subject, const char* object
801         , const char* access_type)
802 {
803         struct smack_accesses *rules = NULL;
804
805         _D("apply_smack_rules : %s %s %s", subject, object, access_type);
806
807         if (smack_accesses_new(&rules)) {
808                 _E("smack_accesses_new fail");
809                 return -1;
810         }
811
812         if (smack_accesses_add(rules, subject, object, access_type)) {
813                 smack_accesses_free(rules);
814                 _E("smack_accesses_add fail");
815                 return -1;
816         }
817
818         if (smack_accesses_apply(rules)) {
819                 smack_accesses_free(rules);
820                 _E("smack_accesses_apply fail");
821                 return -1;
822         }
823
824         smack_accesses_free(rules);
825
826         return 0;
827 }
828
829 int __prepare_valgrind_outputfile(bundle *kb)
830 {
831         const char *str = NULL;
832         const char **str_array = NULL;
833         int len = 0;
834         int i;
835
836         if(bundle_get_type(kb, DLP_K_VALGRIND_ARG) & BUNDLE_TYPE_ARRAY) {
837                 str_array = bundle_get_str_array(kb, DLP_K_VALGRIND_ARG, &len);
838         } else {
839                 str = bundle_get_val(kb, DLP_K_VALGRIND_ARG);
840                 if(str) {
841                         str_array = &str;
842                         len = 1;
843                 }
844         }
845         if(str_array == NULL) return 0;
846
847         for (i = 0; i < len; i++) {
848                 if(str_array[i] == NULL) break;
849                 /* valgrind log file option */
850                 if (strncmp(str_array[i], OPT_VALGRIND_LOGFILE
851                         , strlen(OPT_VALGRIND_LOGFILE)) == 0)
852                 {
853                         if(strncmp(str_array[i], OPT_VALGRIND_LOGFILE_FIXED
854                                 , strlen(str_array[i])))
855                         {
856                                 _E("wrong valgrind option(%s). It should be %s"
857                                         , str_array[i]
858                                         , OPT_VALGRIND_LOGFILE_FIXED);
859                                 return 1;
860                         }else{
861                                 poll_outputfile |= POLL_VALGRIND_LOGFILE;
862                                 if(remove(PATH_VALGRIND_LOGFILE)){
863                                         _D("cannot remove %s"
864                                                 , PATH_VALGRIND_LOGFILE);
865                                 }
866                         }
867                 }
868                 /* valgrind xml file option */
869                 else if (strncmp(str_array[i], OPT_VALGRIND_XMLFILE
870                         , strlen(OPT_VALGRIND_XMLFILE)) == 0)
871                 {
872                         if(strncmp(str_array[i], OPT_VALGRIND_XMLFILE_FIXED
873                                 , strlen(str_array[i])))
874                         {
875                                 _E("wrong valgrind option(%s). It should be %s"
876                                         , str_array[i]
877                                         , OPT_VALGRIND_XMLFILE_FIXED);
878                                 return 1;
879                         }else{
880                                 poll_outputfile |= POLL_VALGRIND_XMLFILE;
881                                 if(remove(PATH_VALGRIND_XMLFILE)){
882                                         _D("cannot remove %s"
883                                                 , PATH_VALGRIND_XMLFILE);
884                                 }
885                         }
886                 }
887         }
888         return 0;
889 }
890
891 extern int capset(cap_user_header_t hdrp, const cap_user_data_t datap);
892
893 int __adjust_process_capability(int sv)
894 {
895         static struct __user_cap_header_struct h;
896         static struct __user_cap_data_struct ori_d[_LINUX_CAPABILITY_U32S_2];
897         static struct __user_cap_data_struct inh_d[_LINUX_CAPABILITY_U32S_2];
898         static int isinit = 0;
899
900         if(isinit==0) {
901                 h.version = _LINUX_CAPABILITY_VERSION_2;
902                 h.pid = getpid();
903
904                 capget(&h, ori_d);
905                 capget(&h, inh_d);
906
907                 inh_d[CAP_TO_INDEX(CAP_NET_RAW)].inheritable |=
908                         CAP_TO_MASK(CAP_NET_RAW);
909                 inh_d[CAP_TO_INDEX(CAP_SYS_CHROOT)].inheritable |=
910                         CAP_TO_MASK(CAP_SYS_CHROOT);
911
912                 isinit++;
913
914                 if(sv == CAPABILITY_SET_ORIGINAL) return 0;
915         }
916
917         if(isinit==0) {
918                 _E("__adjust_process_capability init failed");
919                 return -1;
920         }
921
922         if(sv == CAPABILITY_SET_ORIGINAL) {
923                 h.pid = getpid();
924                 if (capset(&h, ori_d) < 0) {
925                         _E("Capability setting error");
926                         return -1;
927                 }
928         }
929         else if (sv == CAPABILITY_SET_INHERITABLE) {
930                 h.pid = getpid();
931                 if (capset(&h, inh_d) < 0) {
932                         _E("Capability setting error");
933                         return -1;
934                 }
935         }
936
937         return 0;
938 }
939
940 int __adjust_file_capability(const char * path)
941 {
942         if(cap_set_file(path,cap_from_text("CAP_NET_RAW,CAP_SYS_CHROOT+i"))) {
943                 _E("cap_set_file failed : %s", path);
944                 return -1;
945         }
946         return 0;
947 }
948
949 int __prepare_fork(bundle *kb, char *appid)
950 {
951         const char *str = NULL;
952         const char **str_array = NULL;
953         int len = 0;
954         int i;
955
956         poll_outputfile = 0;
957         if(bundle_get_type(kb, AUL_K_SDK) & BUNDLE_TYPE_ARRAY) {
958                 str_array = bundle_get_str_array(kb, AUL_K_SDK, &len);
959         } else {
960                 str = bundle_get_val(kb, AUL_K_SDK);
961                 if(str) {
962                         str_array = &str;
963                         len = 1;
964                 }
965         }
966         if(str_array == NULL) return 0;
967
968         for (i = 0; i < len; i++) {
969                 if(str_array[i] == NULL) break;
970                 /* gdbserver */
971                 if (strncmp(str_array[i], SDK_DEBUG, strlen(str_array[i])) == 0)
972                 {
973                         if(apply_smack_rules("sdbd",appid,"w")) {
974                                 _E("unable to set sdbd rules");
975                                 return 1;
976                         }
977
978                         // FIXME: set gdbfolder to 755 also
979                         if(dlp_chmod(PATH_GDBSERVER
980                                 , S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP
981                                 |S_IROTH|S_IXOTH
982                                 , 1))
983                         {
984                                 _D("unable to set 755 to %s", PATH_GDBSERVER);
985                         }
986                         __adjust_file_capability(PATH_GDBSERVER);
987                         need_to_set_inh_cap_after_fork++;
988                 }
989                 /* valgrind */
990                 else if (strncmp(str_array[i], SDK_VALGRIND
991                         , strlen(str_array[i])) == 0)
992                 {
993                         if (__prepare_valgrind_outputfile(kb)) return 1;
994                         __adjust_file_capability(PATH_MEMCHECK);
995                 }
996         }
997         return 0;
998 }
999
1000 /* chmod and chsmack to read file without root privilege */
1001 void __chmod_chsmack_toread(const char * path)
1002 {
1003         /* chmod */
1004         if(dlp_chmod(path, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, 0))
1005         {
1006                 _E("unable to set 644 to %s", path);
1007         }else{
1008                 _D("set 644 to %s", path);
1009         }
1010
1011         /* chsmack */
1012         if(smack_setlabel(path, "*", SMACK_LABEL_ACCESS))
1013         {
1014                 _E("failed chsmack -a \"*\" %s", path);
1015         }else{
1016                 _D("chsmack -a \"*\" %s", path);
1017         }
1018
1019         return;
1020 }
1021
1022 /* waiting for creating outputfile by child process */
1023 void __waiting_outputfile()
1024 {
1025         int wait_count = 0;
1026         while(poll_outputfile && wait_count<10) {
1027                 /* valgrind log file */
1028                 if( (poll_outputfile & POLL_VALGRIND_LOGFILE) 
1029                         && (access(PATH_VALGRIND_LOGFILE,F_OK)==0) )
1030                 {
1031                         __chmod_chsmack_toread(PATH_VALGRIND_LOGFILE);
1032                         poll_outputfile &= ~POLL_VALGRIND_LOGFILE;
1033                 }
1034
1035                 /* valgrind xml file */
1036                 if( (poll_outputfile & POLL_VALGRIND_XMLFILE)
1037                         && (access(PATH_VALGRIND_XMLFILE,F_OK)==0) )
1038                 {
1039                         __chmod_chsmack_toread(PATH_VALGRIND_XMLFILE);
1040                         poll_outputfile &= ~POLL_VALGRIND_XMLFILE;
1041                 }
1042                 
1043                 if(poll_outputfile) {
1044                         _D("-- now wait for creating the file --");
1045                         usleep(50 * 1000);      /* 50ms sleep*/
1046                         wait_count++;
1047                 }
1048         }
1049
1050         if(wait_count==10) _E("faild to waiting");
1051         return;
1052 }
1053
1054 int __stdout_stderr_redirection(int defpid)
1055 {
1056         char defpath[UNIX_PATH_MAX];
1057         int deffd, result=0; 
1058
1059         /* stdout */
1060         snprintf(defpath, UNIX_PATH_MAX, "/proc/%d/fd/1", defpid);
1061         deffd = open(defpath,O_WRONLY);
1062         if(deffd < 0) {
1063                 _E("opening caller(%d) stdout failed due to %s"
1064                         , defpid, strerror(errno));
1065                 result++;
1066         }else{
1067                 dup2(deffd, 1);
1068                 close(deffd);
1069         }
1070
1071         /* stderr */
1072         snprintf(defpath, UNIX_PATH_MAX, "/proc/%d/fd/2", defpid);
1073         deffd = open(defpath,O_WRONLY);
1074         if(deffd < 0) {
1075                 _E("opening caller(%d) stderr failed due to %s"
1076                         , defpid,strerror(errno));
1077                 result+=2;
1078         }else{
1079                 dup2(deffd, 2);
1080                 close(deffd);
1081         }
1082
1083         return result;
1084 }
1085
1086 void __launchpad_main_loop(int main_fd)
1087 {
1088         bundle *kb = NULL;
1089         app_pkt_t *pkt = NULL;
1090         app_info_from_db *menu_info = NULL;
1091
1092         const char *pkg_name = NULL;
1093         const char *app_path = NULL;
1094         int pid = -1;
1095         int clifd = -1;
1096         struct ucred cr;
1097         int is_real_launch = 0;
1098
1099         char sock_path[UNIX_PATH_MAX] = {0,};
1100         char * appid = NULL;
1101
1102         pkt = __app_recv_raw(main_fd, &clifd, &cr);
1103         if (!pkt) {
1104                 _D("packet is NULL");
1105                 goto end;
1106         }
1107
1108         kb = bundle_decode(pkt->data, pkt->len);
1109         if (!kb) {
1110                 _D("bundle decode error");
1111                 goto end;
1112         }
1113
1114         INIT_PERF(kb);
1115         PERF("packet processing start");
1116
1117         pkg_name = bundle_get_val(kb, AUL_K_PKG_NAME);
1118         _D("pkg name : %s\n", pkg_name);
1119
1120         menu_info = _get_app_info_from_bundle_by_pkgname(pkg_name, kb);
1121         if (menu_info == NULL) {
1122                 _D("such pkg no found");
1123                 goto end;
1124         }
1125
1126         app_path = _get_app_path(menu_info);
1127         if(app_path == NULL) {
1128                 _E("app_path is NULL");
1129                 goto end;
1130         }
1131         if (app_path[0] != '/') {
1132                 _D("app_path is not absolute path");
1133                 goto end;
1134         }
1135
1136         {
1137                 int rc = get_native_appid(app_path,&appid);
1138                 if(rc!=0 || appid==NULL) {
1139                         _E("unable to get native appid");
1140                         if(appid) free(appid);
1141                         goto end;
1142                 }
1143         }
1144
1145         __modify_bundle(kb, cr.pid, menu_info, pkt->cmd);
1146         pkg_name = _get_pkgname(menu_info);
1147
1148         PERF("get package information & modify bundle done");
1149
1150         if(__prepare_fork(kb,appid)) goto end;
1151
1152         pid = fork();
1153         if (pid == 0) {
1154                 if(need_to_set_inh_cap_after_fork) {
1155                         __adjust_process_capability(CAPABILITY_SET_INHERITABLE);
1156                         need_to_set_inh_cap_after_fork = 0;
1157                 }
1158                 PERF("fork done");
1159                 _D("lock up test log(no error) : fork done");
1160
1161                 close(clifd);
1162                 close(main_fd);
1163                 __signal_unset_sigchld();
1164                 __signal_fini();
1165
1166                 snprintf(sock_path, UNIX_PATH_MAX, "%s/%d", AUL_SOCK_PREFIX
1167                         , getpid());
1168                 unlink(sock_path);
1169
1170                 if(__stdout_stderr_redirection(__get_caller_pid(kb))) {
1171                         _E("__stdout_stderr_redirection fail");
1172                 }
1173
1174                 PERF("prepare exec - first done");
1175                 _D("lock up test log(no error) : prepare exec - first done");
1176
1177                 if (__prepare_exec(pkg_name, app_path,
1178                                    menu_info, kb) < 0) {
1179                         _E("preparing work fail to launch - "
1180                            "can not launch %s\n", pkg_name);
1181                         exit(-1);
1182                 }
1183
1184                 PERF("prepare exec - second done");
1185                 _D("lock up test log(no error) : prepare exec - second done");
1186
1187                 __real_launch(app_path, kb);
1188
1189                 exit(-1);
1190         }
1191
1192         _D("==> real launch pid : %d %s\n", pid, app_path);
1193         is_real_launch = 1;
1194
1195  end:
1196         __send_result_to_caller(clifd, pid);
1197
1198         if (pid > 0) {
1199                 if (is_real_launch) {
1200                         /*TODO: retry*/
1201                         __signal_block_sigchld();
1202                         __send_app_launch_signal(pid);
1203                         __signal_unblock_sigchld();
1204                 }
1205         }
1206
1207         if (menu_info != NULL)
1208                 _free_app_info_from_db(menu_info);
1209
1210         if (kb != NULL)
1211                 bundle_free(kb);
1212         if (pkt != NULL)
1213                 free(pkt);
1214         if (appid != NULL) 
1215                 free(appid);
1216
1217         /* Active Flusing for Daemon */
1218         if (initialized > AUL_POLL_CNT) {
1219                 sqlite3_release_memory(SQLITE_FLUSH_MAX);
1220                 malloc_trim(0);
1221                 initialized = 1;
1222         }
1223
1224         if(poll_outputfile) __waiting_outputfile();
1225 }
1226
1227 int __launchpad_pre_init(int argc, char **argv)
1228 {
1229         int fd;
1230
1231         /* signal init*/
1232         __signal_init();
1233
1234         /* get my(launchpad) command line*/
1235         launchpad_cmdline = __proc_get_cmdline_bypid(getpid());
1236         if (launchpad_cmdline == NULL) {
1237                 _E("launchpad cmdline fail to get");
1238                 return -1;
1239         }
1240         _D("launchpad cmdline = %s", launchpad_cmdline);
1241
1242         /* create launchpad sock        */
1243         fd = __create_server_sock(DEBUG_LAUNCHPAD_PID);
1244         if (fd < 0) {
1245                 _E("server sock error");
1246                 return -1;
1247         }
1248
1249         __preload_init(argc, argv);
1250
1251         __preexec_init(argc, argv);
1252
1253         return fd;
1254 }
1255
1256 int __launchpad_post_init()
1257 {
1258         /* Setting this as a global variable to keep track 
1259         of launchpad poll cnt */
1260         /* static int initialized = 0;*/
1261
1262         if (initialized) {
1263                 initialized++;
1264                 return 0;
1265         }
1266
1267         if (__signal_set_sigchld() < 0)
1268                 return -1;
1269
1270         initialized++;
1271
1272         return 0;
1273 }
1274
1275 int main(int argc, char **argv)
1276 {
1277         int main_fd;
1278         struct pollfd pfds[POLLFD_MAX];
1279         int i;
1280
1281         __adjust_process_capability(CAPABILITY_SET_ORIGINAL);
1282
1283         /* init without concerning X & EFL*/
1284         main_fd = __launchpad_pre_init(argc, argv);
1285         if (main_fd < 0) {
1286                 _E("launchpad pre init failed");
1287                 exit(-1);
1288         }
1289
1290         pfds[0].fd = main_fd;
1291         pfds[0].events = POLLIN;
1292         pfds[0].revents = 0;
1293
1294         while (1) {
1295                 if (poll(pfds, POLLFD_MAX, -1) < 0)
1296                         continue;
1297
1298                 /* init with concerning X & EFL (because of booting 
1299                 sequence problem)*/
1300                 if (__launchpad_post_init() < 0) {
1301                         _E("launcpad post init failed");
1302                         exit(-1);
1303                 }
1304
1305                 for (i = 0; i < POLLFD_MAX; i++) {
1306                         if ((pfds[i].revents & POLLIN) != 0) {
1307                                 __launchpad_main_loop(pfds[i].fd);
1308                         }
1309                 }
1310         }
1311 }
1312