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
45 #include <sys/syscall.h> // for syscall
46 #include <sys/time.h> // for gettimeofday
47 #include <sys/socket.h> // for socket, connect
48 #include <sys/un.h> // for sockaddr_un
49 #include <sys/timerfd.h> // for timerfd
51 #include "probeinfo.h"
54 #include "dacollection.h"
58 #define APP_INSTALL_PATH "/opt/apps"
59 #define OSP_APP_POSTFIX ".exe"
60 #define UDS_NAME "/tmp/da.socket"
61 #define TIMERFD_INTERVAL 100000000 // 0.1 sec
63 __thread int gProbeBlockCount = 0;
64 __thread int gProbeDepth = 0;
65 __thread pid_t gTid = -1;
68 long g_total_alloc_size = 0;
69 pthread_t g_recvthread_id;
73 int getExecutableMappingAddress();
75 bool printLog(log_t* log, int msgType);
76 /******************************************************************************
78 (this means that these functions do not need to set enter/exit flag)
79 ******************************************************************************/
81 // runtime configure the probe option
82 static void _configure(char* configstr)
85 gTraceInfo.optionflag = atoi(configstr);
87 sprintf(buf, "configure in probe : %s, %lx\n", configstr, gTraceInfo.optionflag);
91 // create socket to daemon and connect
92 static int createSocket(void)
95 int clientLen, ret = 0;
96 struct sockaddr_un clientAddr;
100 if((gTraceInfo.socket.daemonSock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) != -1)
102 bzero(&clientAddr, sizeof(clientAddr));
103 clientAddr.sun_family = AF_UNIX;
104 sprintf(clientAddr.sun_path, "%s", UDS_NAME);
106 clientLen = sizeof(clientAddr);
107 if(connect(gTraceInfo.socket.daemonSock, (struct sockaddr *)&clientAddr, clientLen) >= 0)
109 // recv initial configuration value
110 recvlen = recv(gTraceInfo.socket.daemonSock, &log,
111 sizeof(log.type) + sizeof(log.length), MSG_WAITALL);
113 if(recvlen > 0) // recv succeed
117 if(log.length >= DA_LOG_MAX)
118 log.length = DA_LOG_MAX - 1;
119 recvlen = recv(gTraceInfo.socket.daemonSock, log.data,
120 log.length, MSG_WAITALL);
127 log.data[log.length] = '\0';
129 if(log.type == MSG_CONFIG)
131 _configure(log.data);
141 sprintf(buf, "recv failed in socket creation with error(%d)\n", recvlen);
143 else // closed by other peer
147 sprintf(buf, "%d|%llu", getpid(), gTraceInfo.app.startTime);
148 printLogStr(buf, MSG_PID);
149 PRINTMSG("createSocket connect() success\n");
153 close(gTraceInfo.socket.daemonSock);
154 gTraceInfo.socket.daemonSock = -1;
167 // parse backtrace string and find out the caller of probed api function
168 // return 0 if caller is user binary, otherwise return 1
169 static int determineCaller(char* tracestring)
173 // determine whether saveptr (caller binary name) is user binary or not
174 substr = strstr(tracestring, APP_INSTALL_PATH);
176 if(substr == NULL) // not user binary
183 substr = strstr(tracestring, OSP_APP_POSTFIX);
191 // return current thread id
192 static pid_t _gettid()
195 gTid = syscall(__NR_gettid); // syscall is very expensive
199 static void* recvThread(void* data)
201 fd_set readfds, workfds;
206 sigset_t profsigmask;
208 if(gTraceInfo.socket.daemonSock == -1)
213 sigemptyset(&profsigmask);
214 sigaddset(&profsigmask, SIGPROF);
215 pthread_sigmask(SIG_BLOCK, &profsigmask, NULL);
221 FD_SET(g_timerfd, &readfds);
223 if(maxfd < gTraceInfo.socket.daemonSock)
224 maxfd = gTraceInfo.socket.daemonSock;
225 FD_SET(gTraceInfo.socket.daemonSock, &readfds);
230 rc = select(maxfd + 1, &workfds, NULL, NULL, NULL);
236 if(g_timerfd > 0 && FD_ISSET(g_timerfd, &workfds))
238 recvlen = read(g_timerfd, &xtime, sizeof(xtime));
241 log.length = sprintf(log.data, "%ld", g_total_alloc_size);
242 printLog(&log, MSG_ALLOC);
250 else if(FD_ISSET(gTraceInfo.socket.daemonSock, &workfds))
252 recvlen = recv(gTraceInfo.socket.daemonSock, &log,
253 sizeof(log.type) + sizeof(log.length), MSG_WAITALL);
255 if(recvlen > 0) // recv succeed
259 if(log.length >= DA_LOG_MAX)
260 log.length = DA_LOG_MAX - 1;
261 recvlen = recv(gTraceInfo.socket.daemonSock, log.data,
262 log.length, MSG_WAITALL);
269 log.data[log.length] = '\0';
271 if(log.type == MSG_CONFIG)
273 _configure(log.data);
275 else if(log.type == MSG_STOP)
282 sprintf(buf, "recv unknown message(%d)\n", log.type);
286 else if(recvlen == 0) // closed by other peer
288 close(gTraceInfo.socket.daemonSock);
289 gTraceInfo.socket.daemonSock = -1;
295 sprintf(buf, "recv failed in recv thread with error(%d)\n", recvlen);
309 /*****************************************************************************
310 * initialize / finalize function
311 *****************************************************************************/
313 void __attribute__((constructor)) _init_probe()
315 struct timeval ttime;
316 struct itimerspec ctime;
320 initialize_hash_table();
322 initialize_screencapture();
326 getExecutableMappingAddress();
328 // get app start time
329 gettimeofday(&ttime, NULL);
330 gTraceInfo.app.startTime = (uint64_t)ttime.tv_sec * 1000 * 1000
333 // create socket for communication with da_daemon
334 if(createSocket() == 0)
337 g_timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC);
340 ctime.it_value.tv_sec = 0;
341 ctime.it_value.tv_nsec = TIMERFD_INTERVAL;
342 ctime.it_interval.tv_sec = 0;
343 ctime.it_interval.tv_nsec = TIMERFD_INTERVAL;
344 if(0 > timerfd_settime(g_timerfd, 0, &ctime, NULL))
346 PRINTMSG("failed to set timerfd\n");
353 PRINTMSG("failed to create timerdf\n");
356 // create recv Thread
357 if(pthread_create(&g_recvthread_id, NULL, recvThread, NULL) < 0) // thread creation failed
359 PRINTMSG("failed to crate recv thread\n");
361 update_heap_memory_size(true, 0);
368 PRINTMSG("dynamic analyzer probe helper so loading...\n");
370 gTraceInfo.init_complete = 1;
374 void __attribute__((destructor)) _fini_probe()
379 gTraceInfo.init_complete = -1;
380 PRINTMSG("dynamic analyzer probe helper so unloading...\n");
389 if(gTraceInfo.socket.daemonSock != -1)
391 printLogStr(NULL, MSG_TERMINATE);
392 close(gTraceInfo.socket.daemonSock);
393 gTraceInfo.socket.daemonSock = -1;
398 finalize_screencapture();
400 finalize_hash_table();
402 for(i = 0; i < NUM_ORIGINAL_LIBRARY; i++)
404 if(lib_handle[i] != NULL)
406 dlclose(lib_handle[i]);
414 /**************************************************************************
416 **************************************************************************/
418 /************************************************************************
419 * manipulate and print log functions
420 ************************************************************************/
422 bool printLog(log_t* log, int msgType)
425 if(unlikely(gTraceInfo.socket.daemonSock == -1))
428 if(unlikely(log == NULL))
433 pthread_mutex_lock(&(gTraceInfo.socket.sockMutex));
434 res = send(gTraceInfo.socket.daemonSock, log, sizeof(log->type) + sizeof(log->length) + log->length, 0);
435 pthread_mutex_unlock(&(gTraceInfo.socket.sockMutex));
441 bool printLogStr(const char* str, int msgType)
446 if(unlikely(gTraceInfo.socket.daemonSock == -1))
454 sprintf(log.data, "%s", str);
455 log.length = strlen(str);
462 pthread_mutex_lock(&(gTraceInfo.socket.sockMutex));
463 res = send(gTraceInfo.socket.daemonSock, &log, sizeof(log.type) + sizeof(log.length) + log.length, MSG_DONTWAIT);
464 pthread_mutex_unlock(&(gTraceInfo.socket.sockMutex));
471 // return 0 for successful case
472 // return non-zero for error
473 // if token is NULL then use DEFAULT TOKEN "`,"
474 // if token is not NULL then insert DEFAULT TOKEN before append input
475 int __appendTypeLog(log_t* log, int nInput, char* token, ...)
477 static char* default_token = DEFAULT_TOKEN;
480 char* seperator = default_token;
482 if(nInput <= 0 || log == NULL)
487 va_start(p_arg, token);
492 for(i = 0; i < nInput; i++)
494 type = va_arg(p_arg, int);
496 if(likely(log->length > 0)) // append token or default token
499 log->length += sprintf(log->data + log->length, "%s", default_token);
501 log->length += sprintf(log->data + log->length, "%s", seperator);
507 log->length += sprintf(log->data + log->length, "%d", va_arg(p_arg, int));
510 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, unsigned int));
513 log->length += sprintf(log->data + log->length, "%ld", va_arg(p_arg, long));
516 log->length += sprintf(log->data + log->length, "%lu", va_arg(p_arg, unsigned long));
519 log->length += sprintf(log->data + log->length, "%s", va_arg(p_arg, char*));
521 case VT_CHAR: // 'char' is promoted to 'int' when passed through '...'
522 log->length += sprintf(log->data + log->length, "%c", va_arg(p_arg, int));
525 log->length += sprintf(log->data + log->length, "%p", va_arg(p_arg, void*));
528 va_arg(p_arg, unsigned int);
531 log->length += sprintf(log->data + log->length, "%ld", va_arg(p_arg, off_t));
534 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, size_t));
537 log->length += sprintf(log->data + log->length, "%d", va_arg(p_arg, ssize_t));
540 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, socklen_t));
542 case VT_UINT16_T: // 'uint16_t' is promoted to 'int' when passed through '...'
543 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, int));
546 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, uint32_t));
549 log->length += sprintf(log->data + log->length, "%llu", va_arg(p_arg, uint64_t));
552 log->length += sprintf(log->data + log->length, "%u", va_arg(p_arg, mode_t));
555 log->length += sprintf(log->data + log->length, "%lu", va_arg(p_arg, dev_t));
558 log->length += sprintf(log->data + log->length, "%lu", va_arg(p_arg, nfds_t));
573 // get backtrace string
574 // return stack depth if succeed, otherwise return 0
575 // parameter 'log' cannot be null
576 int getBacktraceString(log_t* log, int bufsize)
578 void* array[MAX_STACK_DEPTH];
579 char** strings = NULL;
589 initsize = log->length;
590 log->data[log->length] = '\0'; // is this necessary ?
591 size = backtrace(array, MAX_STACK_DEPTH);
592 if(likely(size > TRIM_STACK_DEPTH))
594 strings = BACKTRACE_SYMBOLS(array + TRIM_STACK_DEPTH, size - TRIM_STACK_DEPTH);
596 if(likely(strings != NULL))
598 for(i = TRIM_STACK_DEPTH; i < size; i++)
600 stringlen = strlen(strings[i - TRIM_STACK_DEPTH]) + 14;
601 if(log->length + stringlen >= bufsize + initsize)
604 log->length += sprintf(log->data + log->length, "%010u`,%s`,", (unsigned int)(array[i]), strings[i - TRIM_STACK_DEPTH]);
606 log->data[log->length-2] = '\0';
610 else // failed to get backtrace symbols
612 // just print trace address
613 for(i = TRIM_STACK_DEPTH; i < size; i++)
616 if(log->length + stringlen >= bufsize + initsize)
619 log->length += sprintf(log->data + log->length, "%010u`,(unknown)`,", (unsigned int)(array[i]));
621 log->data[log->length-2] = '\0';
626 return (int)(size - TRIM_STACK_DEPTH);
635 /*************************************************************************
636 * probe block control functions
637 *************************************************************************/
638 int preBlockBegin(void* caller, bool bFiltering, enum DaOptions option)
644 if(gProbeBlockCount != 0 || gProbeDepth != 0)
647 if(gTraceInfo.init_complete <= 0)
650 if((gTraceInfo.optionflag & option) == 0)
655 if(gTraceInfo.exec_map.map_start != NULL)
657 // address comparison
658 if(caller >= gTraceInfo.exec_map.map_start &&
659 caller <= gTraceInfo.exec_map.map_end)
670 // backtrace for filtering
672 strings = BACKTRACE_SYMBOLS(tarray, 1);
675 if((determineCaller(strings[0]) == 0))
688 return 2; // user call
695 return 0; // not probing
700 return 1; // internal call
705 int postBlockBegin(int preresult)
726 /*************************************************************************
727 * helper info getter functions
728 *************************************************************************/
729 // return current time in 1/10000 sec unit
730 unsigned long getCurrentTime()
732 struct timeval cTime;
734 gettimeofday(&cTime, NULL);
736 return (unsigned long)((cTime.tv_sec * 10000 + (cTime.tv_usec/100)));
739 unsigned int getCurrentEventIndex()
741 return gTraceInfo.index.eventIndex;
744 /************************************************************************
746 ************************************************************************/
747 bool setProbePoint(probeInfo_t* iProbe)
749 if(unlikely(iProbe == NULL))
756 // atomic operaion(gcc builtin) is more expensive then pthread_mutex
757 pthread_mutex_lock(&(gTraceInfo.index.eventMutex));
758 iProbe->eventIndex = gTraceInfo.index.eventIndex++;
759 pthread_mutex_unlock(&(gTraceInfo.index.eventMutex));
761 iProbe->currentTime = getCurrentTime();
762 iProbe->pID = getpid();
763 iProbe->tID = _gettid();
764 iProbe->callDepth = gProbeDepth;
770 // update heap memory size through socket
771 // return 0 if size is updated through socket
772 // return 1 if size is updated into global variable
773 int update_heap_memory_size(bool isAdd, size_t size)
778 tmp = __sync_add_and_fetch(&g_total_alloc_size, (long)size);
782 tmp = __sync_sub_and_fetch(&g_total_alloc_size, (long)size);