+/*
+ * <rdar://problem/11128080> if we needed to call confstr during init then setting this
+ * flag will postpone stack logging until after Libsystem's initialiser has run.
+ */
+static void
+postpone_stack_logging(void)
+{
+ _malloc_printf(ASL_LEVEL_INFO, "stack logging postponed until after initialization.\n");
+ stack_logging_postponed = 1;
+}
+
+/*
+ * Check various temporary directory options starting with _PATH_TMP and use confstr.
+ * Allocating and releasing target buffer is the caller's responsibility.
+ */
+static bool
+get_writeable_temp_dir(char* target)
+{
+ if (!target) return false;
+ if (-1 != access(_PATH_TMP, W_OK)) {
+ strlcpy(target, _PATH_TMP, (size_t)PATH_MAX);
+ return true;
+ }
+ if (getenv("TMPDIR") && (-1 != access(getenv("TMPDIR"), W_OK))) {
+ strlcpy(target, getenv("TMPDIR"), (size_t)PATH_MAX);
+ return true;
+ }
+ if (stack_logging_finished_init) {
+ size_t n = confstr(_CS_DARWIN_USER_TEMP_DIR, target, (size_t) PATH_MAX);
+ if ((n > 0) && (n < PATH_MAX)) return true;
+ n = confstr(_CS_DARWIN_USER_CACHE_DIR, target, (size_t) PATH_MAX);
+ if ((n > 0) && (n < PATH_MAX)) return true;
+ } else {
+ /* <rdar://problem/11128080> Can't call confstr during init, so postpone
+ logging till after */
+ postpone_stack_logging();
+ }
+ /* No writeable tmp directory found. Maybe shd try /private/var/tmp for device here ... */
+ *target = '\0';
+ return false;
+}
+
+/*
+ * If successful, returns path to log file that was created, otherwise NULL.
+ *
+ * The log could be in one of 3 places (in decreasing order of preference)
+ *
+ * 1) value of environment variable MallocStackLoggingDirectory
+ * 2) the temp directory /tmp for desktop apps and internal apps on devices, or
+ * 3) the sandbox location + tmp/ in case of 3rd party apps on the device.
+ *
+ * For 1 and 3, we create a .link file with the path of the file. We prefer to
+ * create this file in /tmp, but if we are unable to (device 3rd party case),
+ * we create it in the same location as the .index file and issue a message
+ * in syslog asking for it to be copied to /tmp to enable tools.
+ *
+ */