make sure anrd trace is being collected.

If bugreport is being taken when system is very busy, there's a chance a small
delay in creating the trace file will cause dumpstate to skip including the
file in the report. This fix makes sure the trace has been created before
proceeding.

Change-Id: I0243b8da8ad285921206e8bba88ea80125eb96a7
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index d51fb77..17d44d2 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -219,7 +219,8 @@
     struct dirent *trace;
     struct stat st;
     DIR *trace_dir;
-    long max_ctime = 0;
+    int retry = 5;
+    long max_ctime = 0, old_mtime;
     long long cur_size = 0;
     const char *trace_path = "/data/misc/anrd/";
 
@@ -232,6 +233,13 @@
     pid = pid_of_process("/system/xbin/anrd");
 
     if (pid > 0) {
+        if (stat(trace_path, &st) == 0) {
+            old_mtime = st.st_mtime;
+        } else {
+            MYLOGE("Failed to find: %s\n", trace_path);
+            return false;
+        }
+
         // send SIGUSR1 to the anrd to generate a trace.
         sprintf(buf, "%u", pid);
         if (run_command("ANRD_DUMP", 1, "kill", "-SIGUSR1", buf, NULL)) {
@@ -239,6 +247,16 @@
             return false;
         }
 
+        while (retry-- > 0 && old_mtime == st.st_mtime) {
+            sleep(1);
+            stat(trace_path, &st);
+        }
+
+        if (retry < 0 && old_mtime == st.st_mtime) {
+            MYLOGE("Failed to stat %s or trace creation timeout\n", trace_path);
+            return false;
+        }
+
         // identify the trace file by its creation time.
         if (!(trace_dir = opendir(trace_path))) {
             MYLOGE("Can't open trace file under %s\n", trace_path);