4 * Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
8 * Jaewon Lim <jaewon81.lim@samsung.com>
9 * Woojin Jung <woojin2.jung@samsung.com>
10 * Juyoung Kim <j0.kim@samsung.com>
11 * Nikita Kalyazin <n.kalyazin@samsung.com>
12 * Anastasia Lyupa <a.lyupa@samsung.com>
14 * This library is free software; you can redistribute it and/or modify it under
15 * the terms of the GNU Lesser General Public License as published by the
16 * Free Software Foundation; either version 2.1 of the License, or (at your option)
19 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
20 * WARRANTY; without even the implied warranty of MERCHANTABILITY or
21 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
22 * License for more details.
24 * You should have received a copy of the GNU Lesser General Public License
25 * along with this library; if not, write to the Free Software Foundation, Inc., 51
26 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 * - Samsung RnD Institute Russia
34 #include <stdio.h> // for sprintf
35 #include <stdlib.h> // for getenv
36 #include <string.h> // for strstr
37 #include <stdbool.h> // for bool
38 #include <stdint.h> // fot uint32_t,uint64_t
39 #include <stdarg.h> // for va_list, va_arg(__appendTypeLog)
40 #include <execinfo.h> // for backtrace, backtrace_symbols
41 #include <unistd.h> // for write, alarm function, syscall
42 #include <pthread.h> // for pthread_mutex_lock
46 #include <sys/syscall.h> // for syscall
47 #include <sys/time.h> // for gettimeofday
48 #include <sys/socket.h> // for socket, connect
49 #include <sys/un.h> // for sockaddr_un
50 #include <sys/timerfd.h> // for timerfd
53 #include "probeinfo.h"
56 #include "dacollection.h"
62 #define APP_INSTALL_PATH "/opt/apps"
63 #define TISEN_APP_POSTFIX ".exe"
64 #define UDS_NAME "/tmp/da.socket"
65 #define TIMERFD_INTERVAL 100000000 // 0.1 sec
67 __thread int gProbeBlockCount = 0;
68 __thread int gProbeDepth = 0;
69 __thread pid_t gTid = -1;
72 long g_total_alloc_size = 0;
73 pthread_t g_recvthread_id;
77 int getExecutableMappingAddress();
79 bool printLog(log_t* log, int msgType);
80 /******************************************************************************
82 (this means that these functions do not need to set enter/exit flag)
83 ******************************************************************************/
85 // runtime configure the probe option
86 static void _configure(char* configstr)
89 gTraceInfo.optionflag = atoll(configstr);
91 sprintf(buf, "configure in probe : %s, %lx\n", configstr, gTraceInfo.optionflag);
95 // create socket to daemon and connect
96 static int createSocket(void)
99 int clientLen, ret = 0;
100 struct sockaddr_un clientAddr;
104 if((gTraceInfo.socket.daemonSock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) != -1)
106 bzero(&clientAddr, sizeof(clientAddr));
107 clientAddr.sun_family = AF_UNIX;
108 sprintf(clientAddr.sun_path, "%s", UDS_NAME);
110 clientLen = sizeof(clientAddr);
111 if(connect(gTraceInfo.socket.daemonSock, (struct sockaddr *)&clientAddr, clientLen) >= 0)
113 // recv initial configuration value
114 recvlen = recv(gTraceInfo.socket.daemonSock, &log,
115 sizeof(log.type) + sizeof(log.length), MSG_WAITALL);
117 if(recvlen > 0) // recv succeed
121 if(log.length >= DA_LOG_MAX)
122 log.length = DA_LOG_MAX - 1;
123 recvlen = recv(gTraceInfo.socket.daemonSock, log.data,
124 log.length, MSG_WAITALL);
131 log.data[log.length] = '\0';
133 if(log.type == MSG_CONFIG)
135 _configure(log.data);
145 sprintf(buf, "recv failed in socket creation with error(%d)\n", recvlen);
147 else // closed by other peer
151 sprintf(buf, "%d|%llu", getpid(), gTraceInfo.app.startTime);
152 printLogStr(buf, MSG_PID);
153 PRINTMSG("createSocket connect() success\n");
157 close(gTraceInfo.socket.daemonSock);
158 gTraceInfo.socket.daemonSock = -1;
171 // parse backtrace string and find out the caller of probed api function
172 // return 0 if caller is user binary, otherwise return 1
173 static int determineCaller(char* tracestring)
177 // determine whether saveptr (caller binary name) is user binary or not
178 substr = strstr(tracestring, APP_INSTALL_PATH);
180 if(substr == NULL) // not user binary
187 substr = strstr(tracestring, TISEN_APP_POSTFIX);
195 // return current thread id
196 static pid_t _gettid()
199 gTid = syscall(__NR_gettid); // syscall is very expensive
203 static void* recvThread(void* data)
205 fd_set readfds, workfds;
210 sigset_t profsigmask;
212 if(gTraceInfo.socket.daemonSock == -1)
217 sigemptyset(&profsigmask);
218 sigaddset(&profsigmask, SIGPROF);
219 pthread_sigmask(SIG_BLOCK, &profsigmask, NULL);
225 FD_SET(g_timerfd, &readfds);
227 if(maxfd < gTraceInfo.socket.daemonSock)
228 maxfd = gTraceInfo.socket.daemonSock;
229 FD_SET(gTraceInfo.socket.daemonSock, &readfds);
234 rc = select(maxfd + 1, &workfds, NULL, NULL, NULL);
240 if(g_timerfd > 0 && FD_ISSET(g_timerfd, &workfds))
242 recvlen = read(g_timerfd, &xtime, sizeof(xtime));
245 log.length = sprintf(log.data, "%ld", g_total_alloc_size);
246 printLog(&log, MSG_ALLOC);
254 else if(FD_ISSET(gTraceInfo.socket.daemonSock, &workfds))
256 recvlen = recv(gTraceInfo.socket.daemonSock, &log,
257 sizeof(log.type) + sizeof(log.length), MSG_WAITALL);
259 if(recvlen > 0) // recv succeed
263 if(log.length >= DA_LOG_MAX)
264 log.length = DA_LOG_MAX - 1;
265 recvlen = recv(gTraceInfo.socket.daemonSock, log.data,
266 log.length, MSG_WAITALL);
273 log.data[log.length] = '\0';
275 if(log.type == MSG_CONFIG)
277 _configure(log.data);
279 else if(log.type == MSG_STOP)
286 sprintf(buf, "recv unknown message(%d)\n", log.type);
290 else if(recvlen == 0) // closed by other peer
292 close(gTraceInfo.socket.daemonSock);
293 gTraceInfo.socket.daemonSock = -1;
299 sprintf(buf, "recv failed in recv thread with error(%d)\n", recvlen);
313 /*****************************************************************************
314 * initialize / finalize function
315 *****************************************************************************/
317 void __attribute__((constructor)) _init_probe()
319 struct timeval ttime;
320 struct itimerspec ctime;
324 initialize_hash_table();
326 initialize_screencapture();
330 getExecutableMappingAddress();
332 // get app start time
333 gettimeofday(&ttime, NULL);
334 gTraceInfo.app.startTime = (uint64_t)ttime.tv_sec * 1000 * 1000
337 // create socket for communication with da_daemon
338 if(createSocket() == 0)
341 g_timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC);
344 ctime.it_value.tv_sec = 0;
345 ctime.it_value.tv_nsec = TIMERFD_INTERVAL;
346 ctime.it_interval.tv_sec = 0;
347 ctime.it_interval.tv_nsec = TIMERFD_INTERVAL;
348 if(0 > timerfd_settime(g_timerfd, 0, &ctime, NULL))
350 PRINTMSG("failed to set timerfd\n");
357 PRINTMSG("failed to create timerdf\n");
360 // create recv Thread
361 if(pthread_create(&g_recvthread_id, NULL, recvThread, NULL) < 0) // thread creation failed
363 PRINTMSG("failed to crate recv thread\n");
365 update_heap_memory_size(true, 0);
372 PRINTMSG("dynamic analyzer probe helper so loading...\n");
374 gTraceInfo.init_complete = 1;
378 void __attribute__((destructor)) _fini_probe()
383 gTraceInfo.init_complete = -1;
384 PRINTMSG("dynamic analyzer probe helper so unloading...\n");
393 if(gTraceInfo.socket.daemonSock != -1)
395 printLogStr(NULL, MSG_TERMINATE);
396 close(gTraceInfo.socket.daemonSock);
397 gTraceInfo.socket.daemonSock = -1;
402 finalize_screencapture();
404 finalize_hash_table();
406 for(i = 0; i < NUM_ORIGINAL_LIBRARY; i++)
408 if(lib_handle[i] != NULL)
410 dlclose(lib_handle[i]);
418 /**************************************************************************
420 **************************************************************************/
422 /************************************************************************
423 * manipulate and print log functions
424 ************************************************************************/
425 bool printLog(log_t *log, int msgType)
428 if(unlikely(gTraceInfo.socket.daemonSock == -1))
431 if(unlikely(log == NULL))
436 real_pthread_mutex_lock(&(gTraceInfo.socket.sockMutex));
437 res = send(gTraceInfo.socket.daemonSock, log, sizeof(log->type) + sizeof(log->length) + log->length, 0);
438 real_pthread_mutex_unlock(&(gTraceInfo.socket.sockMutex));
444 bool printLogStr(const char* str, int msgType)
449 if(unlikely(gTraceInfo.socket.daemonSock == -1))
457 sprintf(log.data, "%s", str);
458 log.length = strlen(str);
465 real_pthread_mutex_lock(&(gTraceInfo.socket.sockMutex));
466 res = send(gTraceInfo.socket.daemonSock, &log, sizeof(log.type) + sizeof(log.length) + log.length, MSG_DONTWAIT);
467 real_pthread_mutex_unlock(&(gTraceInfo.socket.sockMutex));
474 // return 0 for successful case
475 // return non-zero for error
476 // if token is NULL then use DEFAULT TOKEN "`,"
477 // if token is not NULL then insert DEFAULT TOKEN before append input
478 int __appendTypeLog(log_t* log, int nInput, char* token, ...)
480 static char* default_token = DEFAULT_TOKEN;
483 char* seperator = default_token;
485 if(nInput <= 0 || log == NULL)
490 va_start(p_arg, token);
495 for(i = 0; i < nInput; i++)
497 type = va_arg(p_arg, int);
499 if(likely(log->length > 0)) // append token or default token
502 log->length += sprintf(log->data + log->length, "%s", default_token);
504 log->length += sprintf(log->data + log->length, "%s", seperator);
510 log->length += sprintf(log->data + log->length, "%d", va_arg(p_arg, int));
513 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, unsigned int));
516 log->length += sprintf(log->data + log->length, "%ld", va_arg(p_arg, long));
519 log->length += sprintf(log->data + log->length, "%lu", va_arg(p_arg, unsigned long));
522 log->length += sprintf(log->data + log->length, "%s", va_arg(p_arg, char*));
524 case VT_CHAR: // 'char' is promoted to 'int' when passed through '...'
525 log->length += sprintf(log->data + log->length, "%c", va_arg(p_arg, int));
528 log->length += sprintf(log->data + log->length, "%p", va_arg(p_arg, void*));
531 va_arg(p_arg, unsigned int);
534 log->length += sprintf(log->data + log->length, "%ld", va_arg(p_arg, off_t));
537 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, size_t));
540 log->length += sprintf(log->data + log->length, "%d", va_arg(p_arg, ssize_t));
543 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, socklen_t));
545 case VT_UINT16_T: // 'uint16_t' is promoted to 'int' when passed through '...'
546 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, int));
549 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, uint32_t));
552 log->length += sprintf(log->data + log->length, "%llu", va_arg(p_arg, uint64_t));
555 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, mode_t));
558 log->length += sprintf(log->data + log->length, "%lu", va_arg(p_arg, dev_t));
561 log->length += sprintf(log->data + log->length, "%lu", va_arg(p_arg, nfds_t));
576 // get backtrace string
577 // return stack depth if succeed, otherwise return 0
578 // parameter 'log' cannot be null
579 int getBacktraceString(log_t* log, int bufsize)
581 void* array[MAX_STACK_DEPTH];
582 char** strings = NULL;
592 initsize = log->length;
593 log->data[log->length] = '\0'; // is this necessary ?
594 size = backtrace(array, MAX_STACK_DEPTH);
595 if(likely(size > TRIM_STACK_DEPTH))
597 strings = BACKTRACE_SYMBOLS(array + TRIM_STACK_DEPTH, size - TRIM_STACK_DEPTH);
599 if(likely(strings != NULL))
601 for(i = TRIM_STACK_DEPTH; i < size; i++)
603 stringlen = strlen(strings[i - TRIM_STACK_DEPTH]) + 14;
604 if(log->length + stringlen >= bufsize + initsize)
607 log->length += sprintf(log->data + log->length, "%010u`,%s`,", (unsigned int)(array[i]), strings[i - TRIM_STACK_DEPTH]);
609 log->data[log->length-2] = '\0';
613 else // failed to get backtrace symbols
615 // just print trace address
616 for(i = TRIM_STACK_DEPTH; i < size; i++)
619 if(log->length + stringlen >= bufsize + initsize)
622 log->length += sprintf(log->data + log->length, "%010u`,(unknown)`,", (unsigned int)(array[i]));
624 log->data[log->length-2] = '\0';
629 return (int)(size - TRIM_STACK_DEPTH);
638 /*************************************************************************
639 * probe block control functions
640 *************************************************************************/
641 int preBlockBegin(void* caller, bool bFiltering, enum DaOptions option)
647 if(gProbeBlockCount != 0 || gProbeDepth != 0)
650 if(gTraceInfo.init_complete <= 0)
653 if((gTraceInfo.optionflag & option) == 0)
658 if(gTraceInfo.exec_map.map_start != NULL)
660 // address comparison
661 if(caller >= gTraceInfo.exec_map.map_start &&
662 caller <= gTraceInfo.exec_map.map_end)
673 // backtrace for filtering
675 strings = BACKTRACE_SYMBOLS(tarray, 1);
678 if((determineCaller(strings[0]) == 0))
691 return 2; // user call
698 return 0; // not probing
703 return 1; // internal call
708 int postBlockBegin(int preresult)
729 /*************************************************************************
730 * helper info getter functions
731 *************************************************************************/
732 // return current time in 1/10000 sec unit
733 unsigned long getCurrentTime()
735 struct timeval cTime;
737 gettimeofday(&cTime, NULL);
739 return (unsigned long)((cTime.tv_sec * 10000 + (cTime.tv_usec/100)));
742 unsigned int getCurrentEventIndex()
744 return gTraceInfo.index.eventIndex;
747 uint64_t get_current_nsec(void)
750 gettimeofday(&tv, NULL);
751 return (uint64_t)tv.tv_sec * 1000 * 1000 * 1000 + tv.tv_usec * 1000;
754 /************************************************************************
756 ************************************************************************/
757 bool setProbePoint(probeInfo_t* iProbe)
759 if(unlikely(iProbe == NULL))
766 // atomic operaion(gcc builtin) is more expensive then pthread_mutex
767 real_pthread_mutex_lock(&(gTraceInfo.index.eventMutex));
768 iProbe->eventIndex = gTraceInfo.index.eventIndex++;
769 real_pthread_mutex_unlock(&(gTraceInfo.index.eventMutex));
771 iProbe->currentTime = getCurrentTime();
772 iProbe->pID = getpid();
773 iProbe->tID = _gettid();
774 iProbe->callDepth = gProbeDepth;
780 // update heap memory size through socket
781 // return 0 if size is updated through socket
782 // return 1 if size is updated into global variable
783 int update_heap_memory_size(bool isAdd, size_t size)
788 tmp = __sync_add_and_fetch(&g_total_alloc_size, (long)size);
792 tmp = __sync_sub_and_fetch(&g_total_alloc_size, (long)size);