Handle long library search paths

Before launching the arch-specific emulator, the emulator wrapper adds
a directory to the library search path (LD_LIBRARY_PATH or PATH).
There were two problems that this change fixes:

- The new path was assembled in a 2048 byte buffer. If the assembled
  path was longer than that, it would be truncated, in effect removing
  some directories. This change dynamically allocates the buffer so
  truncation doesn't happen.

- On Windows, the new directories were appended instead of prepended
  to the existing search path. If the path was truncated due to the
  previous problem, the new directory wouldn't be added to the path,
  and the arch-specific emulator would fail to load. This isn't a real
  problem now that truncation doesn't occur, but this change makes
  the Windows version prepend the directory for consistency's sake.

Bug: http://b.android.com/33336
Change-Id: I13068c4871254f8507eea265f6a1b698e5e1e3ce
diff --git a/android/main-emulator.c b/android/main-emulator.c
index 0981a71..4c8d440 100644
--- a/android/main-emulator.c
+++ b/android/main-emulator.c
@@ -369,26 +369,42 @@
 static void
 prependSharedLibraryPath(const char* prefix)
 {
-    char temp[2048], *p=temp, *end=p+sizeof(temp);
+    size_t len = 0;
+    char *temp = NULL;
+    const char* path = NULL;
+
 #ifdef _WIN32
-    const char* path = getenv("PATH");
-    if (path == NULL || path[0] == '\0') {
-        p = bufprint(temp, end, "PATH=%s", prefix);
+    path = getenv("PATH");
+#else
+    path = getenv("LD_LIBRARY_PATH");
+#endif
+
+    /* Will need up to 7 extra characters: "PATH=", ';' or ':', and '\0' */
+    len = 7 + strlen(prefix) + (path ? strlen(path) : 0);
+    temp = malloc(len);
+    if (!temp)
+        return;
+
+    if (path && path[0] != '\0') {
+#ifdef _WIN32
+        bufprint(temp, temp + len, "PATH=%s;%s", prefix, path);
+#else
+        bufprint(temp, temp + len, "%s:%s", prefix, path);
+#endif
     } else {
-        p = bufprint(temp, end, "PATH=%s;%s", path, prefix);
+#ifdef _WIN32
+        bufprint(temp, temp + len, "PATH=%s", prefix);
+#else
+        strcpy(temp, prefix);
+#endif
     }
-    /* Ignore overflow, this will push some paths out of the variable, but
-     * so be it. */
+
+#ifdef _WIN32
     D("Setting %s\n", temp);
     putenv(strdup(temp));
 #else
-    const char* path = getenv("LD_LIBRARY_PATH");
-    if (path != NULL && path[0] != '\0') {
-        p = bufprint(temp, end, "%s:%s", prefix, path);
-        prefix = temp;
-    }
-    setenv("LD_LIBRARY_PATH",prefix,1);
-    D("Setting LD_LIBRARY_PATH=%s\n", prefix);
+    D("Setting LD_LIBRARY_PATH=%s\n", temp);
+    setenv("LD_LIBRARY_PATH", temp, 1);
 #endif
 }