+
+/*
+ * DTrace wait for process execution
+ *
+ * This feature is using a list of entries, each entry containing a pointer
+ * on a process description. The description is provided by a client, and it
+ * contains the command we want to wait for along with a reserved space for
+ * the caught process id.
+ *
+ * Once an awaited process has been spawned, it will be suspended before
+ * notifying the client. Once the client has been back to userland, it's its
+ * duty to resume the task.
+ */
+
+lck_mtx_t dtrace_procwaitfor_lock;
+
+typedef struct dtrace_proc_awaited_entry {
+ struct dtrace_procdesc *pdesc;
+ LIST_ENTRY(dtrace_proc_awaited_entry) entries;
+} dtrace_proc_awaited_entry_t;
+
+LIST_HEAD(listhead, dtrace_proc_awaited_entry) dtrace_proc_awaited_head
+ = LIST_HEAD_INITIALIZER(dtrace_proc_awaited_head);
+
+void (*dtrace_proc_waitfor_exec_ptr)(proc_t*) = NULL;
+
+static void
+dtrace_proc_exec_notification(proc_t *p) {
+ dtrace_proc_awaited_entry_t *entry, *tmp;
+
+ ASSERT(p);
+ ASSERT(p->p_pid != -1);
+ ASSERT(current_task() != p->task);
+
+ lck_mtx_lock(&dtrace_procwaitfor_lock);
+
+ /*
+ * For each entry, if it has not been matched with a process yet we
+ * try to match it with the newly created process. If they match, the
+ * entry is initialized with the process id and the process task is
+ * suspended. Finally, we wake up the client's waiting thread.
+ */
+ LIST_FOREACH_SAFE(entry, &dtrace_proc_awaited_head, entries, tmp) {
+ if ((entry->pdesc->p_pid == -1)
+ && !strncmp(entry->pdesc->p_comm, &p->p_comm[0], sizeof(p->p_comm)))
+ {
+ entry->pdesc->p_pid = p->p_pid;
+ task_pidsuspend(p->task);
+ wakeup(entry);
+ }
+ }
+
+ lck_mtx_unlock(&dtrace_procwaitfor_lock);
+}
+
+int
+dtrace_proc_waitfor(dtrace_procdesc_t* pdesc) {
+ dtrace_proc_awaited_entry_t entry;
+ int res;
+
+ ASSERT(pdesc);
+ ASSERT(pdesc->p_comm);
+
+ lck_mtx_lock(&dtrace_procwaitfor_lock);
+
+ /* Initialize and insert the entry, then install the hook. */
+ pdesc->p_pid = -1;
+ entry.pdesc = pdesc;
+ LIST_INSERT_HEAD(&dtrace_proc_awaited_head, &entry, entries);
+ dtrace_proc_waitfor_exec_ptr = &dtrace_proc_exec_notification;
+
+ /* Sleep until the process has been executed */
+ res = msleep(&entry, &dtrace_procwaitfor_lock, PCATCH, "dtrace_proc_waitfor", NULL);
+
+ /* Remove the entry and the hook if it is not needed anymore. */
+ LIST_REMOVE(&entry, entries);
+ if (LIST_EMPTY(&dtrace_proc_awaited_head))
+ dtrace_proc_waitfor_exec_ptr = NULL;
+
+ lck_mtx_unlock(&dtrace_procwaitfor_lock);
+
+ return res;
+}
+
+