OSDN Git Service

Perfprofd: Implement stopProfiling
[android-x86/system-extras.git] / perfprofd / perfprofdcore.cc
1 /*
2 **
3 ** Copyright 2015, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 #include <assert.h>
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <time.h>
30 #include <unistd.h>
31 #include <string>
32 #include <sstream>
33 #include <map>
34 #include <set>
35 #include <cctype>
36
37 #include <android-base/file.h>
38 #include <android-base/macros.h>
39 #include <android-base/properties.h>
40 #include <android-base/stringprintf.h>
41
42 #include "perfprofdcore.h"
43 #include "perfprofdutils.h"
44 #include "perf_data_converter.h"
45 #include "cpuconfig.h"
46 #include "configreader.h"
47
48 //
49 // Perf profiling daemon -- collects system-wide profiles using
50 //
51 //       simpleperf record -a
52 //
53 // and encodes them so that they can be uploaded by a separate service.
54 //
55
56 //......................................................................
57
58 //
59 // Output file from 'perf record'.
60 //
61 #define PERF_OUTPUT "perf.data"
62
63 //
64 // This enum holds the results of the "should we profile" configuration check.
65 //
66 typedef enum {
67
68   // All systems go for profile collection.
69   DO_COLLECT_PROFILE,
70
71   // The selected configuration directory doesn't exist.
72   DONT_PROFILE_MISSING_CONFIG_DIR,
73
74   // Destination directory does not contain the semaphore file that
75   // the perf profile uploading service creates when it determines
76   // that the user has opted "in" for usage data collection. No
77   // semaphore -> no user approval -> no profiling.
78   DONT_PROFILE_MISSING_SEMAPHORE,
79
80   // No perf executable present
81   DONT_PROFILE_MISSING_PERF_EXECUTABLE,
82
83   // We're running in the emulator, perf won't be able to do much
84   DONT_PROFILE_RUNNING_IN_EMULATOR
85
86 } CKPROFILE_RESULT;
87
88 //
89 // Are we running in the emulator? If so, stub out profile collection
90 // Starts as uninitialized (-1), then set to 1 or 0 at init time.
91 //
92 static int running_in_emulator = -1;
93
94 //
95 // Is this a debug build ('userdebug' or 'eng')?
96 // Starts as uninitialized (-1), then set to 1 or 0 at init time.
97 //
98 static int is_debug_build = -1;
99
100 //
101 // Path to the perf file to convert and exit? Empty value is the default, daemon mode.
102 //
103 static std::string perf_file_to_convert = "";
104
105 //
106 // Random number generator seed (set at startup time).
107 //
108 static unsigned short random_seed[3];
109
110 //
111 // SIGHUP handler. Sending SIGHUP to the daemon can be used to break it
112 // out of a sleep() call so as to trigger a new collection (debugging)
113 //
114 static void sig_hup(int /* signum */)
115 {
116   W_ALOGW("SIGHUP received");
117 }
118
119 //
120 // Parse command line args. Currently supported flags:
121 // *  "-c PATH" sets the path of the config file to PATH.
122 // *  "-x PATH" reads PATH as a perf data file and saves it as a file in
123 //    perf_profile.proto format. ".encoded" suffix is appended to PATH to form
124 //    the output file path.
125 //
126 static void parse_args(int argc, char** argv)
127 {
128   int ac;
129
130   for (ac = 1; ac < argc; ++ac) {
131     if (!strcmp(argv[ac], "-c")) {
132       if (ac >= argc-1) {
133         W_ALOGE("malformed command line: -c option requires argument)");
134         continue;
135       }
136       ConfigReader::setConfigFilePath(argv[ac+1]);
137       ++ac;
138     } else if (!strcmp(argv[ac], "-x")) {
139       if (ac >= argc-1) {
140         W_ALOGE("malformed command line: -x option requires argument)");
141         continue;
142       }
143       perf_file_to_convert = argv[ac+1];
144       ++ac;
145     } else {
146       W_ALOGE("malformed command line: unknown option or arg %s)", argv[ac]);
147       continue;
148     }
149   }
150 }
151
152 //
153 // Convert a CKPROFILE_RESULT to a string
154 //
155 const char *ckprofile_result_to_string(CKPROFILE_RESULT result)
156 {
157   switch (result) {
158     case DO_COLLECT_PROFILE:
159       return "DO_COLLECT_PROFILE";
160     case DONT_PROFILE_MISSING_CONFIG_DIR:
161       return "missing config directory";
162     case DONT_PROFILE_MISSING_SEMAPHORE:
163       return "missing semaphore file";
164     case DONT_PROFILE_MISSING_PERF_EXECUTABLE:
165       return "missing 'perf' executable";
166     case DONT_PROFILE_RUNNING_IN_EMULATOR:
167       return "running in emulator";
168     default: return "unknown";
169   }
170   return "notreached";
171 }
172
173 //
174 // Convert a PROFILE_RESULT to a string
175 //
176 const char *profile_result_to_string(PROFILE_RESULT result)
177 {
178   switch(result) {
179     case OK_PROFILE_COLLECTION:
180       return "profile collection succeeded";
181     case ERR_FORK_FAILED:
182       return "fork() system call failed";
183     case ERR_PERF_RECORD_FAILED:
184       return "perf record returned bad exit status";
185     case ERR_PERF_ENCODE_FAILED:
186       return "failure encoding perf.data to protobuf";
187     case ERR_OPEN_ENCODED_FILE_FAILED:
188       return "failed to open encoded perf file";
189     case ERR_WRITE_ENCODED_FILE_FAILED:
190       return "write to encoded perf file failed";
191     default: return "unknown";
192   }
193   return "notreached";
194 }
195
196 //
197 // Check to see whether we should perform a profile collection
198 //
199 static CKPROFILE_RESULT check_profiling_enabled(const Config& config)
200 {
201   //
202   // Profile collection in the emulator doesn't make sense
203   //
204   assert(running_in_emulator != -1);
205   if (running_in_emulator) {
206     return DONT_PROFILE_RUNNING_IN_EMULATOR;
207   }
208
209   //
210   // Check for existence of semaphore file in config directory
211   //
212   if (access(config.config_directory.c_str(), F_OK) == -1) {
213     W_ALOGW("unable to open config directory %s: (%s)",
214             config.config_directory.c_str(), strerror(errno));
215     return DONT_PROFILE_MISSING_CONFIG_DIR;
216   }
217
218   // Check for existence of semaphore file
219   std::string semaphore_filepath = config.config_directory
220                                    + "/" + SEMAPHORE_FILENAME;
221   if (access(semaphore_filepath.c_str(), F_OK) == -1) {
222     return DONT_PROFILE_MISSING_SEMAPHORE;
223   }
224
225   // Check for existence of simpleperf/perf executable
226   std::string pp = config.perf_path;
227   if (access(pp.c_str(), R_OK|X_OK) == -1) {
228     W_ALOGW("unable to access/execute %s", pp.c_str());
229     return DONT_PROFILE_MISSING_PERF_EXECUTABLE;
230   }
231
232   //
233   // We are good to go
234   //
235   return DO_COLLECT_PROFILE;
236 }
237
238 bool get_booting()
239 {
240   return android::base::GetBoolProperty("sys.boot_completed", false) != true;
241 }
242
243 //
244 // Constructor takes a timeout (in seconds) and a child pid; If an
245 // alarm set for the specified number of seconds triggers, then a
246 // SIGKILL is sent to the child. Destructor resets alarm. Example:
247 //
248 //       pid_t child_pid = ...;
249 //       { AlarmHelper h(10, child_pid);
250 //         ... = read_from_child(child_pid, ...);
251 //       }
252 //
253 // NB: this helper is not re-entrant-- avoid nested use or
254 // use by multiple threads
255 //
256 class AlarmHelper {
257  public:
258   AlarmHelper(unsigned num_seconds, pid_t child)
259   {
260     struct sigaction sigact;
261     assert(child);
262     assert(child_ == 0);
263     memset(&sigact, 0, sizeof(sigact));
264     sigact.sa_sigaction = handler;
265     sigaction(SIGALRM, &sigact, &oldsigact_);
266     child_ = child;
267     alarm(num_seconds);
268   }
269   ~AlarmHelper()
270   {
271     alarm(0);
272     child_ = 0;
273     sigaction(SIGALRM, &oldsigact_, NULL);
274   }
275   static void handler(int, siginfo_t *, void *);
276
277  private:
278   struct sigaction oldsigact_;
279   static pid_t child_;
280 };
281
282 pid_t AlarmHelper::child_;
283
284 void AlarmHelper::handler(int, siginfo_t *, void *)
285 {
286   W_ALOGW("SIGALRM timeout");
287   kill(child_, SIGKILL);
288 }
289
290 //
291 // This implementation invokes "dumpsys media.camera" and inspects the
292 // output to determine if any camera clients are active. NB: this is
293 // currently disable (via config option) until the selinux issues can
294 // be sorted out. Another possible implementation (not yet attempted)
295 // would be to use the binder to call into the native camera service
296 // via "ICameraService".
297 //
298 bool get_camera_active()
299 {
300   int pipefds[2];
301   if (pipe2(pipefds, O_CLOEXEC) != 0) {
302     W_ALOGE("pipe2() failed (%s)", strerror(errno));
303     return false;
304   }
305   pid_t pid = fork();
306   if (pid == -1) {
307     W_ALOGE("fork() failed (%s)", strerror(errno));
308     close(pipefds[0]);
309     close(pipefds[1]);
310     return false;
311   } else if (pid == 0) {
312     // child
313     close(pipefds[0]);
314     dup2(pipefds[1], fileno(stderr));
315     dup2(pipefds[1], fileno(stdout));
316     const char *argv[10];
317     unsigned slot = 0;
318     argv[slot++] = "/system/bin/dumpsys";
319     argv[slot++] = "media.camera";
320     argv[slot++] = nullptr;
321     execvp(argv[0], (char * const *)argv);
322     W_ALOGE("execvp() failed (%s)", strerror(errno));
323     return false;
324   }
325   // parent
326   AlarmHelper helper(10, pid);
327   close(pipefds[1]);
328
329   // read output
330   bool have_cam = false;
331   bool have_clients = true;
332   std::string dump_output;
333   bool result = android::base::ReadFdToString(pipefds[0], &dump_output);
334   close(pipefds[0]);
335   if (result) {
336     std::stringstream ss(dump_output);
337     std::string line;
338     while (std::getline(ss,line,'\n')) {
339       if (line.find("Camera module API version:") !=
340           std::string::npos) {
341         have_cam = true;
342       }
343       if (line.find("No camera module available") !=
344           std::string::npos ||
345           line.find("No active camera clients yet") !=
346           std::string::npos) {
347         have_clients = false;
348       }
349     }
350   }
351
352   // reap child (no zombies please)
353   int st = 0;
354   TEMP_FAILURE_RETRY(waitpid(pid, &st, 0));
355   return have_cam && have_clients;
356 }
357
358 bool get_charging()
359 {
360   std::string psdir("/sys/class/power_supply");
361   DIR* dir = opendir(psdir.c_str());
362   if (dir == NULL) {
363     W_ALOGE("Failed to open dir %s (%s)", psdir.c_str(), strerror(errno));
364     return false;
365   }
366   struct dirent* e;
367   bool result = false;
368   while ((e = readdir(dir)) != 0) {
369     if (e->d_name[0] != '.') {
370       std::string online_path = psdir + "/" + e->d_name + "/online";
371       std::string contents;
372       int value = 0;
373       if (android::base::ReadFileToString(online_path.c_str(), &contents) &&
374           sscanf(contents.c_str(), "%d", &value) == 1) {
375         if (value) {
376           result = true;
377           break;
378         }
379       }
380     }
381   }
382   closedir(dir);
383   return result;
384 }
385
386 bool postprocess_proc_stat_contents(const std::string &pscontents,
387                                     long unsigned *idleticks,
388                                     long unsigned *remainingticks)
389 {
390   long unsigned usertime, nicetime, systime, idletime, iowaittime;
391   long unsigned irqtime, softirqtime;
392
393   int rc = sscanf(pscontents.c_str(), "cpu  %lu %lu %lu %lu %lu %lu %lu",
394                   &usertime, &nicetime, &systime, &idletime,
395                   &iowaittime, &irqtime, &softirqtime);
396   if (rc != 7) {
397     return false;
398   }
399   *idleticks = idletime;
400   *remainingticks = usertime + nicetime + systime + iowaittime + irqtime + softirqtime;
401   return true;
402 }
403
404 unsigned collect_cpu_utilization()
405 {
406   std::string contents;
407   long unsigned idle[2];
408   long unsigned busy[2];
409   for (unsigned iter = 0; iter < 2; ++iter) {
410     if (!android::base::ReadFileToString("/proc/stat", &contents)) {
411       return 0;
412     }
413     if (!postprocess_proc_stat_contents(contents, &idle[iter], &busy[iter])) {
414       return 0;
415     }
416     if (iter == 0) {
417       sleep(1);
418     }
419   }
420   long unsigned total_delta = (idle[1] + busy[1]) - (idle[0] + busy[0]);
421   long unsigned busy_delta = busy[1] - busy[0];
422   return busy_delta * 100 / total_delta;
423 }
424
425 static void annotate_encoded_perf_profile(wireless_android_play_playlog::AndroidPerfProfile *profile,
426                                           const Config& config,
427                                           unsigned cpu_utilization)
428 {
429   //
430   // Incorporate cpu utilization (collected prior to perf run)
431   //
432   if (config.collect_cpu_utilization) {
433     profile->set_cpu_utilization(cpu_utilization);
434   }
435
436   //
437   // Load average as reported by the kernel
438   //
439   std::string load;
440   double fload = 0.0;
441   if (android::base::ReadFileToString("/proc/loadavg", &load) &&
442       sscanf(load.c_str(), "%lf", &fload) == 1) {
443     int iload = static_cast<int>(fload * 100.0);
444     profile->set_sys_load_average(iload);
445   } else {
446     W_ALOGE("Failed to read or scan /proc/loadavg (%s)", strerror(errno));
447   }
448
449   //
450   // Device still booting? Camera in use? Plugged into charger?
451   //
452   bool is_booting = get_booting();
453   if (config.collect_booting) {
454     profile->set_booting(is_booting);
455   }
456   if (config.collect_camera_active) {
457     profile->set_camera_active(is_booting ? false : get_camera_active());
458   }
459   if (config.collect_charging_state) {
460     profile->set_on_charger(get_charging());
461   }
462
463   //
464   // Examine the contents of wake_unlock to determine whether the
465   // device display is on or off. NB: is this really the only way to
466   // determine this info?
467   //
468   std::string disp;
469   if (android::base::ReadFileToString("/sys/power/wake_unlock", &disp)) {
470     bool ison = (strstr(disp.c_str(), "PowerManagerService.Display") == 0);
471     profile->set_display_on(ison);
472   } else {
473     W_ALOGE("Failed to read /sys/power/wake_unlock (%s)", strerror(errno));
474   }
475 }
476
477 inline char* string_as_array(std::string* str) {
478   return str->empty() ? NULL : &*str->begin();
479 }
480
481 PROFILE_RESULT encode_to_proto(const std::string &data_file_path,
482                                const char *encoded_file_path,
483                                const Config& config,
484                                unsigned cpu_utilization)
485 {
486   //
487   // Open and read perf.data file
488   //
489   const wireless_android_play_playlog::AndroidPerfProfile &encodedProfile =
490       wireless_android_logging_awp::RawPerfDataToAndroidPerfProfile(data_file_path);
491
492   //
493   // Issue error if no samples
494   //
495   if (encodedProfile.programs().size() == 0) {
496     return ERR_PERF_ENCODE_FAILED;
497   }
498
499   // All of the info in 'encodedProfile' is derived from the perf.data file;
500   // here we tack display status, cpu utilization, system load, etc.
501   wireless_android_play_playlog::AndroidPerfProfile &prof =
502       const_cast<wireless_android_play_playlog::AndroidPerfProfile&>
503       (encodedProfile);
504   annotate_encoded_perf_profile(&prof, config, cpu_utilization);
505
506   //
507   // Serialize protobuf to array
508   //
509   int size = encodedProfile.ByteSize();
510   std::string data;
511   data.resize(size);
512   ::google::protobuf::uint8* dtarget =
513         reinterpret_cast<::google::protobuf::uint8*>(string_as_array(&data));
514   encodedProfile.SerializeWithCachedSizesToArray(dtarget);
515
516   //
517   // Open file and write encoded data to it
518   //
519   FILE *fp = fopen(encoded_file_path, "w");
520   if (!fp) {
521     return ERR_OPEN_ENCODED_FILE_FAILED;
522   }
523   size_t fsiz = size;
524   if (fwrite(dtarget, fsiz, 1, fp) != 1) {
525     fclose(fp);
526     return ERR_WRITE_ENCODED_FILE_FAILED;
527   }
528   fclose(fp);
529   chmod(encoded_file_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
530
531   return OK_PROFILE_COLLECTION;
532 }
533
534 //
535 // Invoke "perf record". Return value is OK_PROFILE_COLLECTION for
536 // success, or some other error code if something went wrong.
537 //
538 static PROFILE_RESULT invoke_perf(const std::string &perf_path,
539                                   unsigned sampling_period,
540                                   const char *stack_profile_opt,
541                                   unsigned duration,
542                                   const std::string &data_file_path,
543                                   const std::string &perf_stderr_path)
544 {
545   pid_t pid = fork();
546
547   if (pid == -1) {
548     return ERR_FORK_FAILED;
549   }
550
551   if (pid == 0) {
552     // child
553
554     // Open file to receive stderr/stdout from perf
555     FILE *efp = fopen(perf_stderr_path.c_str(), "w");
556     if (efp) {
557       dup2(fileno(efp), STDERR_FILENO);
558       dup2(fileno(efp), STDOUT_FILENO);
559     } else {
560       W_ALOGW("unable to open %s for writing", perf_stderr_path.c_str());
561     }
562
563     // marshall arguments
564     constexpr unsigned max_args = 13;
565     const char *argv[max_args];
566     unsigned slot = 0;
567     argv[slot++] = perf_path.c_str();
568     argv[slot++] = "record";
569
570     // -o perf.data
571     argv[slot++] = "-o";
572     argv[slot++] = data_file_path.c_str();
573
574     // -c N
575     argv[slot++] = "-c";
576     std::string p_str = android::base::StringPrintf("%u", sampling_period);
577     argv[slot++] = p_str.c_str();
578
579     // -g if desired
580     if (stack_profile_opt)
581       argv[slot++] = stack_profile_opt;
582
583     // system wide profiling
584     argv[slot++] = "-a";
585
586     // no need for kernel symbols
587     argv[slot++] = "--no-dump-kernel-symbols";
588
589     // sleep <duration>
590     argv[slot++] = "/system/bin/sleep";
591     std::string d_str = android::base::StringPrintf("%u", duration);
592     argv[slot++] = d_str.c_str();
593
594     // terminator
595     argv[slot++] = nullptr;
596     assert(slot < max_args);
597
598     // record the final command line in the error output file for
599     // posterity/debugging purposes
600     fprintf(stderr, "perf invocation (pid=%d):\n", getpid());
601     for (unsigned i = 0; argv[i] != nullptr; ++i) {
602       fprintf(stderr, "%s%s", i ? " " : "", argv[i]);
603     }
604     fprintf(stderr, "\n");
605
606     // exec
607     execvp(argv[0], (char * const *)argv);
608     fprintf(stderr, "exec failed: %s\n", strerror(errno));
609     exit(1);
610
611   } else {
612     // parent
613     int st = 0;
614     pid_t reaped = TEMP_FAILURE_RETRY(waitpid(pid, &st, 0));
615
616     if (reaped == -1) {
617       W_ALOGW("waitpid failed: %s", strerror(errno));
618     } else if (WIFSIGNALED(st)) {
619       W_ALOGW("perf killed by signal %d", WTERMSIG(st));
620     } else if (WEXITSTATUS(st) != 0) {
621       W_ALOGW("perf bad exit status %d", WEXITSTATUS(st));
622     } else {
623       return OK_PROFILE_COLLECTION;
624     }
625   }
626
627   return ERR_PERF_RECORD_FAILED;
628 }
629
630 //
631 // Remove all files in the destination directory during initialization
632 //
633 static void cleanup_destination_dir(const std::string& dest_dir)
634 {
635   DIR* dir = opendir(dest_dir.c_str());
636   if (dir != NULL) {
637     struct dirent* e;
638     while ((e = readdir(dir)) != 0) {
639       if (e->d_name[0] != '.') {
640         std::string file_path = dest_dir + "/" + e->d_name;
641         remove(file_path.c_str());
642       }
643     }
644     closedir(dir);
645   } else {
646     W_ALOGW("unable to open destination dir %s for cleanup",
647             dest_dir.c_str());
648   }
649 }
650
651 //
652 // Post-processes after profile is collected and converted to protobuf.
653 // * GMS core stores processed file sequence numbers in
654 //   /data/data/com.google.android.gms/files/perfprofd_processed.txt
655 // * Update /data/misc/perfprofd/perfprofd_produced.txt to remove the sequence
656 //   numbers that have been processed and append the current seq number
657 // Returns true if the current_seq should increment.
658 //
659 static bool post_process(const Config& config, int current_seq)
660 {
661   const std::string& dest_dir = config.destination_directory;
662   std::string processed_file_path =
663       config.config_directory + "/" + PROCESSED_FILENAME;
664   std::string produced_file_path = dest_dir + "/" + PRODUCED_FILENAME;
665
666
667   std::set<int> processed;
668   FILE *fp = fopen(processed_file_path.c_str(), "r");
669   if (fp != NULL) {
670     int seq;
671     while(fscanf(fp, "%d\n", &seq) > 0) {
672       if (remove(android::base::StringPrintf(
673           "%s/perf.data.encoded.%d", dest_dir.c_str(),seq).c_str()) == 0) {
674         processed.insert(seq);
675       }
676     }
677     fclose(fp);
678   }
679
680   std::set<int> produced;
681   fp = fopen(produced_file_path.c_str(), "r");
682   if (fp != NULL) {
683     int seq;
684     while(fscanf(fp, "%d\n", &seq) > 0) {
685       if (processed.find(seq) == processed.end()) {
686         produced.insert(seq);
687       }
688     }
689     fclose(fp);
690   }
691
692   uint32_t maxLive = config.max_unprocessed_profiles;
693   if (produced.size() >= maxLive) {
694     return false;
695   }
696
697   produced.insert(current_seq);
698   fp = fopen(produced_file_path.c_str(), "w");
699   if (fp == NULL) {
700     W_ALOGW("Cannot write %s", produced_file_path.c_str());
701     return false;
702   }
703   for (std::set<int>::const_iterator iter = produced.begin();
704        iter != produced.end(); ++iter) {
705     fprintf(fp, "%d\n", *iter);
706   }
707   fclose(fp);
708   chmod(produced_file_path.c_str(),
709         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
710   return true;
711 }
712
713 //
714 // Collect a perf profile. Steps for this operation are:
715 // - kick off 'perf record'
716 // - read perf.data, convert to protocol buf
717 //
718 static PROFILE_RESULT collect_profile(const Config& config, int seq)
719 {
720   //
721   // Collect cpu utilization if enabled
722   //
723   unsigned cpu_utilization = 0;
724   if (config.collect_cpu_utilization) {
725     cpu_utilization = collect_cpu_utilization();
726   }
727
728   //
729   // Form perf.data file name, perf error output file name
730   //
731   const std::string& destdir = config.destination_directory;
732   std::string data_file_path(destdir);
733   data_file_path += "/";
734   data_file_path += PERF_OUTPUT;
735   std::string perf_stderr_path(destdir);
736   perf_stderr_path += "/perferr.txt";
737
738   //
739   // Remove any existing perf.data file -- if we don't do this, perf
740   // will rename the old file and we'll have extra cruft lying around.
741   //
742   struct stat statb;
743   if (stat(data_file_path.c_str(), &statb) == 0) { // if file exists...
744     if (unlink(data_file_path.c_str())) {          // then try to remove
745       W_ALOGW("unable to unlink previous perf.data file");
746     }
747   }
748
749   //
750   // The "mpdecision" daemon can cause problems for profile
751   // collection: if it decides to online a CPU partway through the
752   // 'perf record' run, the activity on that CPU will be invisible to
753   // perf, and if it offlines a CPU during the recording this can
754   // sometimes leave the PMU in an unusable state (dmesg errors of the
755   // form "perfevents: unable to request IRQXXX for ...").  To avoid
756   // these issues, if "mpdecision" is running the helper below will
757   // stop the service and then online all available CPUs. The object
758   // destructor (invoked when this routine terminates) will then
759   // restart the service again when needed.
760   //
761   uint32_t duration = config.sample_duration_in_s;
762   bool hardwire = config.hardwire_cpus;
763   uint32_t max_duration = config.hardwire_cpus_max_duration_in_s;
764   bool take_action = (hardwire && duration <= max_duration);
765   HardwireCpuHelper helper(take_action);
766
767   //
768   // Invoke perf
769   //
770   const char *stack_profile_opt =
771       (config.stack_profile ? "-g" : nullptr);
772   const std::string& perf_path = config.perf_path;
773   uint32_t period = config.sampling_period;
774
775   PROFILE_RESULT ret = invoke_perf(perf_path.c_str(),
776                                   period,
777                                   stack_profile_opt,
778                                   duration,
779                                   data_file_path,
780                                   perf_stderr_path);
781   if (ret != OK_PROFILE_COLLECTION) {
782     return ret;
783   }
784
785   //
786   // Read the resulting perf.data file, encode into protocol buffer, then write
787   // the result to the file perf.data.encoded
788   //
789   std::string path = android::base::StringPrintf(
790       "%s.encoded.%d", data_file_path.c_str(), seq);
791   return encode_to_proto(data_file_path, path.c_str(), config, cpu_utilization);
792 }
793
794 //
795 // Assuming that we want to collect a profile every N seconds,
796 // randomly partition N into two sub-intervals.
797 //
798 static void determine_before_after(unsigned &sleep_before_collect,
799                                    unsigned &sleep_after_collect,
800                                    unsigned collection_interval)
801 {
802   double frac = erand48(random_seed);
803   sleep_before_collect = (unsigned) (((double)collection_interval) * frac);
804   assert(sleep_before_collect <= collection_interval);
805   sleep_after_collect = collection_interval - sleep_before_collect;
806 }
807
808 //
809 // Set random number generator seed
810 //
811 static void set_seed(uint32_t use_fixed_seed)
812 {
813   unsigned seed = 0;
814   if (use_fixed_seed) {
815     //
816     // Use fixed user-specified seed
817     //
818     seed = use_fixed_seed;
819   } else {
820     //
821     // Randomized seed
822     //
823     seed = arc4random();
824   }
825   W_ALOGI("random seed set to %u", seed);
826   // Distribute the 32-bit seed into the three 16-bit array
827   // elements. The specific values being written do not especially
828   // matter as long as we are setting them to something based on the seed.
829   random_seed[0] = seed & 0xffff;
830   random_seed[1] = (seed >> 16);
831   random_seed[2] = (random_seed[0] ^ random_seed[1]);
832 }
833
834 static void CommonInit(uint32_t use_fixed_seed, const char* dest_dir) {
835   // Children of init inherit an artificially low OOM score -- this is not
836   // desirable for perfprofd (its OOM score should be on par with
837   // other user processes).
838   std::stringstream oomscore_path;
839   oomscore_path << "/proc/" << getpid() << "/oom_score_adj";
840   if (!android::base::WriteStringToFile("0", oomscore_path.str())) {
841     W_ALOGE("unable to write to %s", oomscore_path.str().c_str());
842   }
843
844   set_seed(use_fixed_seed);
845   if (dest_dir != nullptr) {
846     cleanup_destination_dir(dest_dir);
847   }
848
849   running_in_emulator = android::base::GetBoolProperty("ro.kernel.qemu", false);
850   is_debug_build = android::base::GetBoolProperty("ro.debuggable", false);
851 }
852
853 //
854 // Initialization
855 //
856 static void init(const Config& config)
857 {
858   // TODO: Consider whether we want to clean things or just overwrite.
859   CommonInit(config.use_fixed_seed, nullptr);
860 }
861
862 static void init(ConfigReader &config)
863 {
864   if (!config.readFile()) {
865     W_ALOGE("unable to open configuration file %s",
866             config.getConfigFilePath());
867   }
868
869   CommonInit(static_cast<uint32_t>(config.getUnsignedValue("use_fixed_seed")),
870              config.getStringValue("destination_directory").c_str());
871
872   signal(SIGHUP, sig_hup);
873 }
874
875 template <typename ConfigFn, typename UpdateFn>
876 static void ProfilingLoopImpl(ConfigFn config, UpdateFn update) {
877   unsigned iterations = 0;
878   int seq = 0;
879   while(config()->main_loop_iterations == 0 ||
880       iterations < config()->main_loop_iterations) {
881     if (config()->ShouldStopProfiling()) {
882       return;
883     }
884
885     // Figure out where in the collection interval we're going to actually
886     // run perf
887     unsigned sleep_before_collect = 0;
888     unsigned sleep_after_collect = 0;
889     determine_before_after(sleep_before_collect, sleep_after_collect,
890                            config()->collection_interval_in_s);
891     config()->Sleep(sleep_before_collect);
892
893     if (config()->ShouldStopProfiling()) {
894       return;
895     }
896
897     // Run any necessary updates.
898     update();
899
900     // Check for profiling enabled...
901     CKPROFILE_RESULT ckresult = check_profiling_enabled(*config());
902     if (ckresult != DO_COLLECT_PROFILE) {
903       W_ALOGI("profile collection skipped (%s)",
904               ckprofile_result_to_string(ckresult));
905     } else {
906       // Kick off the profiling run...
907       W_ALOGI("initiating profile collection");
908       PROFILE_RESULT result = collect_profile(*config(), seq);
909       if (result != OK_PROFILE_COLLECTION) {
910         W_ALOGI("profile collection failed (%s)",
911                 profile_result_to_string(result));
912       } else {
913         if (post_process(*config(), seq)) {
914           seq++;
915         }
916         W_ALOGI("profile collection complete");
917       }
918     }
919
920     if (config()->ShouldStopProfiling()) {
921       return;
922     }
923
924     config()->Sleep(sleep_after_collect);
925     iterations += 1;
926   }
927 }
928
929 void ProfilingLoop(Config& config) {
930   init(config);
931
932   auto config_fn = [&config]() {
933     return &config;;
934   };
935   auto do_nothing = []() {
936   };
937   ProfilingLoopImpl(config_fn, do_nothing);
938 }
939
940 //
941 // Main routine:
942 // 1. parse cmd line args
943 // 2. read config file
944 // 3. loop: {
945 //       sleep for a while
946 //       perform a profile collection
947 //    }
948 //
949 int perfprofd_main(int argc, char** argv, Config* config)
950 {
951   ConfigReader config_reader;
952
953   W_ALOGI("starting Android Wide Profiling daemon");
954
955   parse_args(argc, argv);
956   init(config_reader);
957   config_reader.FillConfig(config);
958
959   if (!perf_file_to_convert.empty()) {
960     std::string encoded_path = perf_file_to_convert + ".encoded";
961     encode_to_proto(perf_file_to_convert, encoded_path.c_str(), *config, 0);
962     return 0;
963   }
964
965   // Early exit if we're not supposed to run on this build flavor
966   if (is_debug_build != 1 && config->only_debug_build) {
967     W_ALOGI("early exit due to inappropriate build type");
968     return 0;
969   }
970
971   auto config_fn = [config]() {
972     return config;
973   };
974   auto reread_config = [&config_reader, config]() {
975     // Reread config file -- the uploader may have rewritten it as a result
976     // of a gservices change
977     config_reader.readFile();
978     config_reader.FillConfig(config);
979   };
980   ProfilingLoopImpl(config_fn, reread_config);
981
982   W_ALOGI("finishing Android Wide Profiling daemon");
983   return 0;
984 }