]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - android-sdk/arm-ds5-gator.git/blob - daemon/Child.cpp
Merge branch 'master' into android
[android-sdk/arm-ds5-gator.git] / daemon / Child.cpp
1 /**
2  * Copyright (C) ARM Limited 2010-2012. All rights reserved.
3  *
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.
7  */
9 #include <stdlib.h>
10 #include <string.h>
11 #include <signal.h>
12 #include <sys/syscall.h>
13 #include <sys/resource.h>
14 #include <unistd.h>
15 #include <sys/prctl.h>
16 #include "Logging.h"
17 #include "CapturedXML.h"
18 #include "SessionData.h"
19 #include "Child.h"
20 #include "LocalCapture.h"
21 #include "Collector.h"
22 #include "Sender.h"
23 #include "OlyUtility.h"
24 #include "StreamlineSetup.h"
25 #include "ConfigurationXML.h"
27 static sem_t haltPipeline, senderThreadStarted, startProfile; // Shared by Child and spawned threads
28 static Fifo* collectorFifo = NULL;   // Shared by Child.cpp and spawned threads
29 static Sender* sender = NULL;        // Shared by Child.cpp and spawned threads
30 Collector* collector = NULL;
31 Child* child = NULL;                 // shared by Child.cpp and main.cpp
33 extern void cleanUp();
34 void handleException() {
35         if (child && child->numExceptions++ > 0) {
36                 // it is possible one of the below functions itself can cause an exception, thus allow only one exception
37                 logg->logMessage("Received multiple exceptions, terminating the child");
38                 exit(1);
39         }
40         fprintf(stderr, "%s", logg->getLastError());
42         if (child && child->socket) {
43                 if (sender) {
44                         // send the error, regardless of the command sent by Streamline
45                         sender->writeData(logg->getLastError(), strlen(logg->getLastError()), RESPONSE_ERROR);
47                         // cannot close the socket before Streamline issues the command, so wait for the command before exiting
48                         if (gSessionData->mWaitingOnCommand) {
49                                 char discard;
50                                 child->socket->receiveNBytes(&discard, 1);
51                         }
53                         // this indirectly calls close socket which will ensure the data has been sent
54                         delete sender;
55                 }
56         }
58         if (gSessionData->mLocalCapture)
59                 cleanUp();
61         exit(1);
62 }
64 // CTRL C Signal Handler for child process
65 void child_handler(int signum) {
66         static bool beenHere = false;
67         if (beenHere == true) {
68                 logg->logMessage("Gator is being forced to shut down.");
69                 exit(1);
70         }
71         beenHere = true;
72         logg->logMessage("Gator is shutting down.");
73         if (signum == SIGALRM || !collector) {
74                 exit(1);
75         } else {
76                 child->endSession();
77                 alarm(5); // Safety net in case endSession does not complete within 5 seconds
78         }
79 }
81 void* durationThread(void* pVoid) {
82         prctl(PR_SET_NAME, (unsigned int)&"gatord-duration", 0, 0, 0);
83         sem_wait(&startProfile);
84         if (gSessionData->mSessionIsActive) {
85                 // Time out after duration seconds
86                 // Add a second for host-side filtering
87                 sleep(gSessionData->mDuration + 1);
88                 if (gSessionData->mSessionIsActive) {
89                         logg->logMessage("Duration expired.");
90                         child->endSession();
91                 }
92         }
93         logg->logMessage("Exit duration thread");
94         return 0;
95 }
97 void* stopThread(void* pVoid) {
98         int length;
99         char type;
100         OlySocket* socket = child->socket;
102         prctl(PR_SET_NAME, (unsigned int)&"gatord-stopper", 0, 0, 0);
103         while (gSessionData->mSessionIsActive) {
104                 // This thread will stall until the APC_STOP or PING command is received over the socket or the socket is disconnected
105                 if (socket->receiveNBytes(&type, sizeof(type)) > 0) {
106                         if ((type != COMMAND_APC_STOP) && (type != COMMAND_PING)) {
107                                 logg->logMessage("INVESTIGATE: Received unknown command type %d", type);
108                         } else {
109                                 // verify a length of zero
110                                 if (socket->receiveNBytes((char*)&length, sizeof(length)) < 0) {
111                                         break;
112                                 }
114                                 if (length == 0) {
115                                         if (type == COMMAND_APC_STOP) {
116                                                 logg->logMessage("Stop command received.");
117                                                 child->endSession();
118                                         } else {
119                                                 // Ping is used to make sure gator is alive and requires an ACK as the response
120                                                 logg->logMessage("Ping command received.");
121                                                 sender->writeData(NULL, 0, RESPONSE_ACK);
122                                         }
123                                 } else {
124                                         logg->logMessage("INVESTIGATE: Received stop command but with length = %d", length);
125                                 }
126                         }
127                 }
128         }
130         logg->logMessage("Exit stop thread");
131         return 0;
134 void* senderThread(void* pVoid) {
135         int length;
136         char* data;
138         sem_post(&senderThreadStarted);
139         prctl(PR_SET_NAME, (unsigned int)&"gatord-sender", 0, 0, 0);
140         sem_wait(&haltPipeline);
142         do {
143                 data = collectorFifo->read(&length);
144                 sender->writeData(data, length, RESPONSE_APC_DATA);
145         } while (length > 0);
146         logg->logMessage("Exit sender thread");
147         return 0;
150 Child::Child(char* path) {
151         initialization();
152         sessionXMLPath = path;
153         gSessionData->mLocalCapture = true;
156 Child::Child(OlySocket* sock, int conn) {
157         initialization();
158         socket = sock;
159         numConnections = conn;
162 Child::~Child() {
165 void Child::initialization() {
166         // Set up different handlers for signals
167         gSessionData->mSessionIsActive = true;
168         signal(SIGINT, child_handler);
169         signal(SIGTERM, child_handler);
170         signal(SIGABRT, child_handler);
171         signal(SIGALRM, child_handler);
172         socket = NULL;
173         numExceptions = 0;
174         numConnections = 0;
175         sessionXMLPath = 0;
177         // Initialize semaphores
178         sem_init(&senderThreadStarted, 0, 0);
179         sem_init(&startProfile, 0, 0);
182 void Child::endSession() {
183         gSessionData->mSessionIsActive = false;
184         collector->stop();
185         sem_post(&haltPipeline);
188 void Child::run() {
189         char* collectBuffer;
190         int bytesCollected = 0;
191         LocalCapture* localCapture = NULL;
193         prctl(PR_SET_NAME, (unsigned int)&"gatord-child", 0, 0, 0);
195         // Instantiate the Sender - must be done first, after which error messages can be sent
196         sender = new Sender(socket);
198         if (numConnections > 1) {
199                 logg->logError(__FILE__, __LINE__, "Session already in progress");
200                 handleException();
201         }
203         // Populate gSessionData with the configuration
204         new ConfigurationXML();
206         // Set up the driver; must be done after gSessionData->mPerfCounterType[] is populated
207         collector = new Collector();
209         // Start up and parse session xml
210         if (socket) {
211                 // Respond to Streamline requests
212                 StreamlineSetup ss(socket);
213         } else {
214                 xmlString = util->readFromDisk(sessionXMLPath);
215                 if (xmlString == 0) {
216                         logg->logError(__FILE__, __LINE__, "Unable to read session xml file: %s", sessionXMLPath);
217                         handleException();
218                 }
219                 gSessionData->parseSessionXML(xmlString);
220                 localCapture = new LocalCapture();
221                 localCapture->createAPCDirectory(gSessionData->target_path, gSessionData->title);
222                 localCapture->copyImages(gSessionData->images);
223                 localCapture->write(xmlString);
224                 sender->createDataFile(gSessionData->apcDir);
225                 delete xmlString;
226         }
228         // Write configuration into the driver
229         collector->setupPerfCounters();
231         // Create user-space buffers
232         int fifoBufferSize = collector->getBufferSize();
233         int numCollectorBuffers = (gSessionData->mTotalBufferSize * 1024 * 1024 + fifoBufferSize - 1) / fifoBufferSize;
234         numCollectorBuffers = (numCollectorBuffers < 4) ? 4 : numCollectorBuffers;
235         logg->logMessage("Created %d %d-byte collector buffers", numCollectorBuffers, fifoBufferSize);
236         collectorFifo = new Fifo(numCollectorBuffers, fifoBufferSize);
238         // Get the initial pointer to the collect buffer
239         collectBuffer = collectorFifo->start();
241         // Sender thread shall be halted until it is signaled for one shot mode
242         sem_init(&haltPipeline, 0, gSessionData->mOneShot ? 0 : 2);
244         // Create the duration, stop, and sender threads
245         bool thread_creation_success = true;
246         if (gSessionData->mDuration > 0 && pthread_create(&durationThreadID, NULL, durationThread, NULL))
247                 thread_creation_success = false;
248         else if (socket && pthread_create(&stopThreadID, NULL, stopThread, NULL))
249                 thread_creation_success = false;
250         else if (pthread_create(&senderThreadID, NULL, senderThread, NULL))
251                 thread_creation_success = false;
252         if (!thread_creation_success) {
253                 logg->logError(__FILE__, __LINE__, "Failed to create gator threads");
254                 handleException();
255         }
257         // Wait until thread has started
258         sem_wait(&senderThreadStarted);
260         // Start profiling
261         logg->logMessage("********** Profiling started **********");
262         collector->start();
263         sem_post(&startProfile);
265         // Collect Data
266         do {
267                 // This command will stall until data is received from the driver
268                 bytesCollected = collector->collect(collectBuffer);
270                 // In one shot mode, stop collection once all the buffers are filled
271                 if (gSessionData->mOneShot && gSessionData->mSessionIsActive) {
272                         // Depth minus 1 because write() has not yet been called
273                         if ((bytesCollected == -1) || (collectorFifo->numWriteToReadBuffersFilled() == collectorFifo->depth() - 1)) {
274                                 logg->logMessage("One shot");
275                                 endSession();
276                         }
277                 }
278                 collectBuffer = collectorFifo->write(bytesCollected);
279         } while (bytesCollected > 0);
280         logg->logMessage("Exit collect data loop");
282         // Wait for the other threads to exit
283         pthread_join(senderThreadID, NULL);
285         // Shutting down the connection should break the stop thread which is stalling on the socket recv() function
286         if (socket) {
287                 logg->logMessage("Waiting on stop thread");
288                 socket->shutdownConnection();
289                 pthread_join(stopThreadID, NULL);
290         }
292         // Write the captured xml file
293         if (gSessionData->mLocalCapture) {
294                 CapturedXML capturedXML;
295                 capturedXML.write(gSessionData->apcDir);
296         }
298         logg->logMessage("Profiling ended.");
300         delete collectorFifo;
301         delete sender;
302         delete collector;
303         delete localCapture;