2 * Copyright (C) ARM Limited 2010-2013. All rights reserved.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
13 #include <sys/syscall.h>
14 #include <sys/prctl.h>
15 #include <sys/types.h>
17 #include <sys/mount.h>
21 #include <sys/resource.h>
22 #include <arpa/inet.h>
23 #include <sys/socket.h>
25 #include "SessionData.h"
26 #include "OlySocket.h"
28 #include "OlyUtility.h"
34 static int shutdownFilesystem();
35 static pthread_mutex_t numSessions_mutex;
36 static int numSessions = 0;
37 static OlySocket* sock = NULL;
38 static bool driverRunningAtStart = false;
39 static bool driverMountedAtStart = false;
46 #define DEFAULT_PORT 8080
49 if (shutdownFilesystem() == -1) {
50 logg->logMessage("Error shutting down gator filesystem");
57 // CTRL C Signal Handler
58 static void handler(int signum) {
59 logg->logMessage("Received signal %d, gator daemon exiting", signum);
61 // Case 1: both child and parent receive the signal
62 if (numSessions > 0) {
63 // Arbitrary sleep of 1 second to give time for the child to exit;
64 // if something bad happens, continue the shutdown process regardless
68 // Case 2: only the parent received the signal
69 if (numSessions > 0) {
70 // Kill child threads - the first signal exits gracefully
71 logg->logMessage("Killing process group as %d child was running when signal was received", numSessions);
74 // Give time for the child to exit
77 if (numSessions > 0) {
78 // The second signal force kills the child
79 logg->logMessage("Force kill the child");
81 // Again, sleep for 1 second
84 if (numSessions > 0) {
85 // Something bad has really happened; the child is not exiting and therefore may hold the /dev/gator resource open
86 printf("Unable to kill the gatord child process, thus gator.ko may still be loaded.\n");
95 // Child exit Signal Handler
96 static void child_exit(int signum) {
98 int pid = wait(&status);
100 pthread_mutex_lock(&numSessions_mutex);
102 pthread_mutex_unlock(&numSessions_mutex);
103 logg->logMessage("Child process %d exited with status %d", pid, status);
107 static int udpPort(int port) {
109 struct sockaddr_in sockaddr;
112 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
114 logg->logError(__FILE__, __LINE__, "socket failed");
119 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) != 0) {
120 logg->logError(__FILE__, __LINE__, "setsockopt failed");
124 memset((void*)&sockaddr, 0, sizeof(sockaddr));
125 sockaddr.sin_family = AF_INET;
126 sockaddr.sin_port = htons(port);
127 sockaddr.sin_addr.s_addr = INADDR_ANY;
128 if (bind(s, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0) {
129 logg->logError(__FILE__, __LINE__, "socket failed");
136 #define UDP_ANS_PORT 30000
137 #define UDP_REQ_PORT 30001
142 uint8_t ethernetAddress[8];
143 uint32_t ethernetType;
147 uint32_t defaultGateway;
149 uint32_t activeConnections;
152 static const char DST_REQ[] = { 'D', 'S', 'T', '_', 'R', 'E', 'Q', ' ', 0, 0, 0, 0x64 };
154 static void* answerThread(void* pVoid) {
155 const struct cmdline_t * const cmdline = (struct cmdline_t *)pVoid;
156 RVIConfigureInfo dstAns;
157 int req = udpPort(UDP_REQ_PORT);
158 int ans = udpPort(UDP_ANS_PORT);
160 // Format the answer buffer
161 memset(&dstAns, 0, sizeof(dstAns));
162 memcpy(dstAns.rviHeader, "STR_ANS ", sizeof(dstAns.rviHeader));
163 if (gethostname(dstAns.dhcpName, sizeof(dstAns.dhcpName) - 1) != 0) {
164 logg->logError(__FILE__, __LINE__, "gethostname failed");
167 // Subvert the defaultGateway field for the port number
168 if (cmdline->port != DEFAULT_PORT) {
169 dstAns.defaultGateway = cmdline->port;
171 // Subvert the subnetMask field for the protocol version
172 dstAns.subnetMask = PROTOCOL_VERSION;
176 struct sockaddr_in sockaddr;
179 addrlen = sizeof(sockaddr);
180 read = recvfrom(req, &buf, sizeof(buf), 0, (struct sockaddr *)&sockaddr, &addrlen);
182 logg->logError(__FILE__, __LINE__, "recvfrom failed");
184 } else if ((read == 12) && (memcmp(buf, DST_REQ, sizeof(DST_REQ)) == 0)) {
185 if (sendto(ans, &dstAns, sizeof(dstAns), 0, (struct sockaddr *)&sockaddr, addrlen) != sizeof(dstAns)) {
186 logg->logError(__FILE__, __LINE__, "sendto failed");
193 // retval: -1 = failure; 0 = was already mounted; 1 = successfully mounted
194 static int mountGatorFS() {
195 // If already mounted,
196 if (access("/dev/gator/buffer", F_OK) == 0) {
200 // else, mount the filesystem
201 mkdir("/dev/gator", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
202 if (mount("nodev", "/dev/gator", "gatorfs", 0, NULL) != 0) {
209 static bool init_module (const char * const location) {
211 const int fd = open(location, O_RDONLY);
214 if (fstat(fd, &st) == 0) {
215 void * const p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
216 if (p != MAP_FAILED) {
217 if (syscall(__NR_init_module, p, st.st_size, "") == 0) {
220 munmap(p, st.st_size);
229 static int setupFilesystem(char* module) {
232 // Verify root permissions
233 uid_t euid = geteuid();
235 logg->logError(__FILE__, __LINE__, "gatord must be launched with root privileges");
240 // unmount and rmmod if the module was specified on the commandline, i.e. ensure that the specified module is indeed running
241 shutdownFilesystem();
244 if (access("/dev/gator/buffer", F_OK) == 0) {
245 logg->logError(__FILE__, __LINE__, "Unable to remove the running gator.ko. Manually remove the module or use the running module by not specifying one on the commandline");
250 retval = mountGatorFS();
252 logg->logMessage("Driver already running at startup");
253 driverRunningAtStart = true;
254 } else if (retval == 0) {
255 logg->logMessage("Driver already mounted at startup");
256 driverRunningAtStart = driverMountedAtStart = true;
258 char command[256]; // arbitrarily large amount
259 char location[256]; // arbitrarily large amount
262 strncpy(location, module, sizeof(location));
264 // Is the driver co-located in the same directory?
265 if (util->getApplicationFullPath(location, sizeof(location)) != 0) { // allow some buffer space
266 logg->logMessage("Unable to determine the full path of gatord, the cwd will be used");
268 strncat(location, "gator.ko", sizeof(location) - strlen(location) - 1);
271 if (access(location, F_OK) == -1) {
272 logg->logError(__FILE__, __LINE__, "Unable to locate gator.ko driver:\n >>> gator.ko should be co-located with gatord in the same directory\n >>> OR insmod gator.ko prior to launching gatord\n >>> OR specify the location of gator.ko on the command line");
277 bool success = init_module(location);
279 logg->logMessage("init_module failed, trying insmod");
280 snprintf(command, sizeof(command), "insmod %s >/dev/null 2>&1", location);
281 if (system(command) != 0) {
282 logg->logMessage("Unable to load gator.ko driver with command: %s", command);
283 logg->logError(__FILE__, __LINE__, "Unable to load (insmod) gator.ko driver:\n >>> gator.ko must be built against the current kernel version & configuration\n >>> See dmesg for more details");
288 if (mountGatorFS() == -1) {
289 logg->logError(__FILE__, __LINE__, "Unable to mount the gator filesystem needed for profiling.");
297 static int shutdownFilesystem() {
298 if (driverMountedAtStart == false) {
299 umount("/dev/gator");
301 if (driverRunningAtStart == false) {
302 if (syscall(__NR_delete_module, "gator", O_NONBLOCK) != 0) {
303 logg->logMessage("delete_module failed, trying rmmod");
304 if (system("rmmod gator >/dev/null 2>&1") != 0) {
313 static struct cmdline_t parseCommandLine(int argc, char** argv) {
314 struct cmdline_t cmdline;
315 cmdline.port = DEFAULT_PORT;
316 cmdline.module = NULL;
317 char version_string[256]; // arbitrary length to hold the version information
320 // build the version string
321 if (PROTOCOL_VERSION < PROTOCOL_DEV) {
322 snprintf(version_string, sizeof(version_string), "Streamline gatord version %d (DS-5 v5.%d)", PROTOCOL_VERSION, PROTOCOL_VERSION);
324 snprintf(version_string, sizeof(version_string), "Streamline gatord development version %d", PROTOCOL_VERSION);
327 while ((c = getopt(argc, argv, "hvp:s:c:e:m:o:")) != -1) {
330 gSessionData->mConfigurationXMLPath = optarg;
333 gSessionData->mEventsXMLPath = optarg;
336 cmdline.module = optarg;
339 cmdline.port = strtol(optarg, NULL, 10);
342 gSessionData->mSessionXMLPath = optarg;
345 gSessionData->mTargetPath = optarg;
349 logg->logError(__FILE__, __LINE__,
350 "%s. All parameters are optional:\n"
351 "-c config_xml path and filename of the configuration.xml to use\n"
352 "-e events_xml path and filename of the events.xml to use\n"
353 "-h this help page\n"
354 "-m module path and filename of gator.ko\n"
355 "-p port_number port upon which the server listens; default is 8080\n"
356 "-s session_xml path and filename of a session xml used for local capture\n"
357 "-o apc_dir path and name of the output for a local capture\n"
358 "-v version information\n"
363 logg->logError(__FILE__, __LINE__, version_string);
370 if (cmdline.port != DEFAULT_PORT && gSessionData->mSessionXMLPath != NULL) {
371 logg->logError(__FILE__, __LINE__, "Only a port or a session xml can be specified, not both");
375 if (gSessionData->mTargetPath != NULL && gSessionData->mSessionXMLPath == NULL) {
376 logg->logError(__FILE__, __LINE__, "Missing -s command line option required for a local capture.");
381 logg->logError(__FILE__, __LINE__, "Unknown argument: %s. Use '-h' for help.", argv[optind]);
388 // Gator data flow: collector -> collector fifo -> sender
389 int main(int argc, char** argv, char* envp[]) {
390 // Ensure proper signal handling by making gatord the process group leader
391 // e.g. it may not be the group leader when launched as 'sudo gatord'
394 logg = new Logging(DEBUG); // Set up global thread-safe logging
395 gSessionData = new SessionData(); // Global data class
396 util = new OlyUtility(); // Set up global utility class
398 // Initialize drivers
401 prctl(PR_SET_NAME, (unsigned long)&"gatord-main", 0, 0, 0);
402 pthread_mutex_init(&numSessions_mutex, NULL);
404 signal(SIGINT, handler);
405 signal(SIGTERM, handler);
406 signal(SIGABRT, handler);
408 // Set to high priority
409 if (setpriority(PRIO_PROCESS, syscall(__NR_gettid), -19) == -1) {
410 logg->logMessage("setpriority() failed");
413 // Parse the command line parameters
414 struct cmdline_t cmdline = parseCommandLine(argc, argv);
416 // Call before setting up the SIGCHLD handler, as system() spawns child processes
417 setupFilesystem(cmdline.module);
419 // Handle child exit codes
420 signal(SIGCHLD, child_exit);
422 // Ignore the SIGPIPE signal so that any send to a broken socket will return an error code instead of asserting a signal
423 // Handling the error at the send function call is much easier than trying to do anything intelligent in the sig handler
424 signal(SIGPIPE, SIG_IGN);
426 // If the command line argument is a session xml file, no need to open a socket
427 if (gSessionData->mSessionXMLPath) {
432 pthread_t answerThreadID;
433 if (pthread_create(&answerThreadID, NULL, answerThread, &cmdline)) {
434 logg->logError(__FILE__, __LINE__, "Failed to create answer thread");
437 sock = new OlySocket(cmdline.port, true);
438 // Forever loop, can be exited via a signal or exception
440 logg->logMessage("Waiting on connection...");
441 sock->acceptConnection();
446 logg->logError(__FILE__, __LINE__, "Fork process failed. Please power cycle the target device if this error persists.");
447 } else if (pid == 0) {
449 sock->closeServerSocket();
450 child = new Child(sock, numSessions + 1);
458 pthread_mutex_lock(&numSessions_mutex);
460 pthread_mutex_unlock(&numSessions_mutex);
462 // Maximum number of connections is 2
464 while (numSessions > 1) {
465 // Throttle until one of the children exits before continuing to accept another socket connection
466 logg->logMessage("%d sessions active!", numSessions);
467 if (wait++ >= 10) { // Wait no more than 10 seconds
468 // Kill last created child