2 * @APPLE_APACHE_LICENSE_HEADER_START@
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 * @APPLE_APACHE_LICENSE_HEADER_END@
19 static const char *const __rcs_file_version__
= "$Revision: 26200 $";
22 #include "launchd_core_logic.h"
23 #include "launch_internal.h"
24 #include "launchd_helper.h"
26 #include <TargetConditionals.h>
27 #include <mach/mach.h>
28 #include <mach/mach_error.h>
29 #include <mach/boolean.h>
30 #include <mach/message.h>
31 #include <mach/notify.h>
32 #include <mach/mig_errors.h>
33 #include <mach/mach_traps.h>
34 #include <mach/mach_interface.h>
35 #include <mach/host_info.h>
36 #include <mach/mach_host.h>
37 #include <mach/exception.h>
38 #include <mach/host_reboot.h>
39 #include <sys/types.h>
40 #include <sys/queue.h>
41 #include <sys/event.h>
43 #include <sys/ucred.h>
44 #include <sys/fcntl.h>
46 #include <sys/reboot.h>
48 #include <sys/sysctl.h>
49 #include <sys/sockio.h>
51 #include <sys/resource.h>
52 #include <sys/ioctl.h>
53 #include <sys/mount.h>
56 #include <sys/socket.h>
57 #include <sys/syscall.h>
59 #include <netinet/in.h>
60 #include <netinet/in_var.h>
61 #include <netinet6/nd6.h>
62 #include <bsm/libbsm.h>
80 #include <System/sys/spawn.h>
86 #include <malloc/malloc.h>
90 #define __APPLE_API_PRIVATE
94 #include <quarantine.h>
96 #if TARGET_OS_EMBEDDED
97 #include <sys/kern_memorystatus.h>
99 extern int gL1CacheEnabled
;
100 /* To make my life easier. */
101 typedef struct jetsam_priority_entry
{
106 int32_t hiwat_reserved1
;
107 int32_t hiwat_reserved2
;
108 int32_t hiwat_reserved3
;
109 } jetsam_priority_entry_t
;
112 kJetsamFlagsFrontmost
= (1 << 0),
113 kJetsamFlagsKilled
= (1 << 1)
118 #include "launch_priv.h"
119 #include "launch_internal.h"
120 #include "bootstrap.h"
121 #include "bootstrap_priv.h"
123 #include "vproc_internal.h"
128 #include "launchd_runtime.h"
129 #include "launchd_unix_ipc.h"
130 #include "protocol_vproc.h"
131 #include "protocol_vprocServer.h"
132 #include "protocol_job_reply.h"
133 #include "protocol_job_forward.h"
134 #include "mach_excServer.h"
135 #if !TARGET_OS_EMBEDDED
136 #include "domainServer.h"
138 #endif /* !TARGET_OS_EMBEDDED */
139 #include "eventsServer.h"
141 #ifndef POSIX_SPAWN_OSX_TALAPP_START
142 #define POSIX_SPAWN_OSX_TALAPP_START 0x0400
145 #ifndef POSIX_SPAWN_OSX_WIDGET_START
146 #define POSIX_SPAWN_OSX_WIDGET_START 0x0800
149 #ifndef POSIX_SPAWN_IOS_APP_START
150 #define POSIX_SPAWN_IOS_APP_START 0x1000
153 /* LAUNCHD_DEFAULT_EXIT_TIMEOUT
154 * If the job hasn't exited in the given number of seconds after sending
155 * it a SIGTERM, SIGKILL it. Can be overriden in the job plist.
157 #define LAUNCHD_MIN_JOB_RUN_TIME 10
158 #define LAUNCHD_DEFAULT_EXIT_TIMEOUT 20
159 #define LAUNCHD_SIGKILL_TIMER 2
160 #define LAUNCHD_LOG_FAILED_EXEC_FREQ 10
162 #define SHUTDOWN_LOG_DIR "/var/log/shutdown"
164 #define TAKE_SUBSET_NAME "TakeSubsetName"
165 #define TAKE_SUBSET_PID "TakeSubsetPID"
166 #define TAKE_SUBSET_PERPID "TakeSubsetPerPID"
168 #define IS_POWER_OF_TWO(v) (!(v & (v - 1)) && v)
170 extern char **environ
;
172 struct waiting_for_removal
{
173 SLIST_ENTRY(waiting_for_removal
) sle
;
174 mach_port_t reply_port
;
177 static bool waiting4removal_new(job_t j
, mach_port_t rp
);
178 static void waiting4removal_delete(job_t j
, struct waiting_for_removal
*w4r
);
181 SLIST_ENTRY(machservice
) sle
;
182 SLIST_ENTRY(machservice
) special_port_sle
;
183 LIST_ENTRY(machservice
) name_hash_sle
;
184 LIST_ENTRY(machservice
) port_hash_sle
;
185 struct machservice
*alias
;
187 unsigned int gen_num
;
188 mach_port_name_t port
;
198 delete_on_destruction
:1,
199 drain_one_on_crash
:1,
200 drain_all_on_crash
:1,
201 event_update_port
:1, /* The job which owns this port is the event monitor. */
202 upfront
:1, /* This service was declared in the plist. */
203 event_channel
:1, /* The job is to receive events on this channel. */
204 /* Don't let the size of this field to get too small. It has to be large enough
205 * to represent the reasonable range of special port numbers.
207 special_port_num
:18;
211 static SLIST_HEAD(, machservice
) special_ports
; /* hack, this should be per jobmgr_t */
213 #define PORT_HASH_SIZE 32
214 #define HASH_PORT(x) (IS_POWER_OF_TWO(PORT_HASH_SIZE) ? (MACH_PORT_INDEX(x) & (PORT_HASH_SIZE - 1)) : (MACH_PORT_INDEX(x) % PORT_HASH_SIZE))
216 static LIST_HEAD(, machservice
) port_hash
[PORT_HASH_SIZE
];
218 static void machservice_setup(launch_data_t obj
, const char *key
, void *context
);
219 static void machservice_setup_options(launch_data_t obj
, const char *key
, void *context
);
220 static void machservice_resetport(job_t j
, struct machservice
*ms
);
221 static struct machservice
*machservice_new(job_t j
, const char *name
, mach_port_t
*serviceport
, bool pid_local
);
222 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
223 static struct machservice
*machservice_new_alias(job_t aj
, struct machservice
*orig
);
224 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
225 static void machservice_ignore(job_t j
, struct machservice
*ms
);
226 static void machservice_watch(job_t j
, struct machservice
*ms
);
227 static void machservice_delete(job_t j
, struct machservice
*, bool port_died
);
228 static void machservice_request_notifications(struct machservice
*);
229 static mach_port_t
machservice_port(struct machservice
*);
230 static job_t
machservice_job(struct machservice
*);
231 static bool machservice_hidden(struct machservice
*);
232 static bool machservice_active(struct machservice
*);
233 static const char *machservice_name(struct machservice
*);
234 static bootstrap_status_t
machservice_status(struct machservice
*);
235 void machservice_drain_port(struct machservice
*);
236 static struct machservice
*xpc_events_find_channel(job_t j
, event_name_t stream
, mach_port_t
*p
);
239 SLIST_ENTRY(socketgroup
) sle
;
241 unsigned int junkfds
:1, fd_cnt
:31;
248 static bool socketgroup_new(job_t j
, const char *name
, int *fds
, size_t fd_cnt
, bool junkfds
);
249 static void socketgroup_delete(job_t j
, struct socketgroup
*sg
);
250 static void socketgroup_watch(job_t j
, struct socketgroup
*sg
);
251 static void socketgroup_ignore(job_t j
, struct socketgroup
*sg
);
252 static void socketgroup_callback(job_t j
);
253 static void socketgroup_setup(launch_data_t obj
, const char *key
, void *context
);
254 static void socketgroup_kevent_mod(job_t j
, struct socketgroup
*sg
, bool do_add
);
256 struct calendarinterval
{
257 LIST_ENTRY(calendarinterval
) global_sle
;
258 SLIST_ENTRY(calendarinterval
) sle
;
264 static LIST_HEAD(, calendarinterval
) sorted_calendar_events
;
266 static bool calendarinterval_new(job_t j
, struct tm
*w
);
267 static bool calendarinterval_new_from_obj(job_t j
, launch_data_t obj
);
268 static void calendarinterval_new_from_obj_dict_walk(launch_data_t obj
, const char *key
, void *context
);
269 static void calendarinterval_delete(job_t j
, struct calendarinterval
*ci
);
270 static void calendarinterval_setalarm(job_t j
, struct calendarinterval
*ci
);
271 static void calendarinterval_callback(void);
272 static void calendarinterval_sanity_check(void);
275 SLIST_ENTRY(envitem
) sle
;
284 static bool envitem_new(job_t j
, const char *k
, const char *v
, bool global
, bool one_shot
);
285 static void envitem_delete(job_t j
, struct envitem
*ei
, bool global
);
286 static void envitem_setup(launch_data_t obj
, const char *key
, void *context
);
287 static void envitem_setup_one_shot(launch_data_t obj
, const char *key
, void *context
);
290 SLIST_ENTRY(limititem
) sle
;
292 unsigned int setsoft
:1, sethard
:1, which
:30;
295 static bool limititem_update(job_t j
, int w
, rlim_t r
);
296 static void limititem_delete(job_t j
, struct limititem
*li
);
297 static void limititem_setup(launch_data_t obj
, const char *key
, void *context
);
299 static void seatbelt_setup_flags(launch_data_t obj
, const char *key
, void *context
);
302 static void jetsam_property_setup(launch_data_t obj
, const char *key
, job_t j
);
319 // FILESYSTEMTYPE_IS_MOUNTED, /* for nfsiod, but maybe others */
320 } semaphore_reason_t
;
322 struct semaphoreitem
{
323 SLIST_ENTRY(semaphoreitem
) sle
;
324 semaphore_reason_t why
;
325 bool watching_parent
;
334 struct semaphoreitem_dict_iter_context
{
336 semaphore_reason_t why_true
;
337 semaphore_reason_t why_false
;
340 static bool semaphoreitem_new(job_t j
, semaphore_reason_t why
, const char *what
);
341 static void semaphoreitem_delete(job_t j
, struct semaphoreitem
*si
);
342 static void semaphoreitem_setup(launch_data_t obj
, const char *key
, void *context
);
343 static void semaphoreitem_setup_dict_iter(launch_data_t obj
, const char *key
, void *context
);
344 static void semaphoreitem_callback(job_t j
, struct kevent
*kev
);
345 static void semaphoreitem_watch(job_t j
, struct semaphoreitem
*si
);
346 static void semaphoreitem_ignore(job_t j
, struct semaphoreitem
*si
);
347 static void semaphoreitem_runtime_mod_ref(struct semaphoreitem
*si
, bool add
);
349 struct externalevent
{
350 LIST_ENTRY(externalevent
) sys_le
;
351 LIST_ENTRY(externalevent
) job_le
;
352 struct eventsystem
*sys
;
363 struct externalevent_iter_ctx
{
365 struct eventsystem
*sys
;
368 static bool externalevent_new(job_t j
, struct eventsystem
*sys
, char *evname
, launch_data_t event
);
369 static void externalevent_delete(struct externalevent
*ee
);
370 static void externalevent_setup(launch_data_t obj
, const char *key
, void *context
);
371 static struct externalevent
*externalevent_find(const char *sysname
, uint64_t id
);
374 LIST_ENTRY(eventsystem
) global_le
;
375 LIST_HEAD(, externalevent
) events
;
381 static struct eventsystem
*eventsystem_new(const char *name
);
382 static void eventsystem_delete(struct eventsystem
*sys
);
383 static void eventsystem_setup(launch_data_t obj
, const char *key
, void *context
);
384 static struct eventsystem
*eventsystem_find(const char *name
);
385 static void eventsystem_ping(void);
387 #define ACTIVE_JOB_HASH_SIZE 32
388 #define ACTIVE_JOB_HASH(x) (IS_POWER_OF_TWO(ACTIVE_JOB_HASH_SIZE) ? (x & (ACTIVE_JOB_HASH_SIZE - 1)) : (x % ACTIVE_JOB_HASH_SIZE))
390 #define MACHSERVICE_HASH_SIZE 37
392 #define LABEL_HASH_SIZE 53
394 kq_callback kqjobmgr_callback
;
395 LIST_ENTRY(jobmgr_s
) xpc_le
;
396 SLIST_ENTRY(jobmgr_s
) sle
;
397 SLIST_HEAD(, jobmgr_s
) submgrs
;
398 LIST_HEAD(, job_s
) jobs
;
399 LIST_HEAD(, job_s
) jetsam_jobs
;
401 /* For legacy reasons, we keep all job labels that are imported in the
402 * root job manager's label hash. If a job manager is an XPC domain, then
403 * it gets its own label hash that is separate from the "global" one
404 * stored in the root job manager.
406 LIST_HEAD(, job_s
) label_hash
[LABEL_HASH_SIZE
];
407 LIST_HEAD(, job_s
) active_jobs
[ACTIVE_JOB_HASH_SIZE
];
408 LIST_HEAD(, machservice
) ms_hash
[MACHSERVICE_HASH_SIZE
];
409 LIST_HEAD(, job_s
) global_env_jobs
;
411 mach_port_t req_port
;
414 time_t shutdown_time
;
415 unsigned int global_on_demand_cnt
;
416 unsigned int normal_active_cnt
;
417 unsigned int jetsam_jobs_cnt
;
420 session_initialized
:1,
421 killed_stray_jobs
:1,
423 shutdown_jobs_dirtied
:1,
424 shutdown_jobs_cleaned
:1,
427 /* XPC-specific properties. */
428 char owner
[MAXCOMLEN
];
430 mach_port_t req_bsport
;
431 mach_port_t req_excport
;
432 mach_port_t req_asport
;
438 mach_msg_type_number_t req_ctx_sz
;
439 mach_port_t req_rport
;
447 /* Global XPC domains. */
448 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
449 static jobmgr_t _s_xpc_system_domain
;
450 static LIST_HEAD(, jobmgr_s
) _s_xpc_user_domains
;
451 static LIST_HEAD(, jobmgr_s
) _s_xpc_session_domains
;
452 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
454 #define jobmgr_assumes(jm, e) \
455 (unlikely(!(e)) ? jobmgr_log_bug(jm, __LINE__), false : true)
457 static jobmgr_t
jobmgr_new(jobmgr_t jm
, mach_port_t requestorport
, mach_port_t transfer_port
, bool sflag
, const char *name
, bool no_init
, mach_port_t asport
);
458 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
459 static jobmgr_t
jobmgr_new_xpc_singleton_domain(jobmgr_t jm
, name_t name
);
460 static jobmgr_t
jobmgr_find_xpc_per_user_domain(jobmgr_t jm
, uid_t uid
);
461 static jobmgr_t
jobmgr_find_xpc_per_session_domain(jobmgr_t jm
, au_asid_t asid
);
462 static job_t
xpc_domain_import_service(jobmgr_t jm
, launch_data_t pload
);
463 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
464 static job_t
jobmgr_import2(jobmgr_t jm
, launch_data_t pload
);
465 static jobmgr_t
jobmgr_parent(jobmgr_t jm
);
466 static jobmgr_t
jobmgr_do_garbage_collection(jobmgr_t jm
);
467 static bool jobmgr_label_test(jobmgr_t jm
, const char *str
);
468 static void jobmgr_reap_bulk(jobmgr_t jm
, struct kevent
*kev
);
469 static void jobmgr_log_stray_children(jobmgr_t jm
, bool kill_strays
);
470 static void jobmgr_kill_stray_children(jobmgr_t jm
, pid_t
*p
, size_t np
);
471 static void jobmgr_remove(jobmgr_t jm
);
472 static void jobmgr_dispatch_all(jobmgr_t jm
, bool newmounthack
);
473 static job_t
jobmgr_init_session(jobmgr_t jm
, const char *session_type
, bool sflag
);
474 static job_t
jobmgr_find_by_pid_deep(jobmgr_t jm
, pid_t p
, bool anon_okay
);
475 static job_t
jobmgr_find_by_pid(jobmgr_t jm
, pid_t p
, bool create_anon
);
476 static jobmgr_t
jobmgr_find_by_name(jobmgr_t jm
, const char *where
);
477 static job_t
job_mig_intran2(jobmgr_t jm
, mach_port_t mport
, pid_t upid
);
478 static job_t
jobmgr_lookup_per_user_context_internal(job_t j
, uid_t which_user
, mach_port_t
*mp
);
479 static void job_export_all2(jobmgr_t jm
, launch_data_t where
);
480 static void jobmgr_callback(void *obj
, struct kevent
*kev
);
481 static void jobmgr_setup_env_from_other_jobs(jobmgr_t jm
);
482 static void jobmgr_export_env_from_other_jobs(jobmgr_t jm
, launch_data_t dict
);
483 static struct machservice
*jobmgr_lookup_service(jobmgr_t jm
, const char *name
, bool check_parent
, pid_t target_pid
);
484 static void jobmgr_logv(jobmgr_t jm
, int pri
, int err
, const char *msg
, va_list ap
) __attribute__((format(printf
, 4, 0)));
485 static void jobmgr_log(jobmgr_t jm
, int pri
, const char *msg
, ...) __attribute__((format(printf
, 3, 4)));
486 /* static void jobmgr_log_error(jobmgr_t jm, int pri, const char *msg, ...) __attribute__((format(printf, 3, 4))); */
487 static void jobmgr_log_bug(jobmgr_t jm
, unsigned int line
);
489 #define AUTO_PICK_LEGACY_LABEL (const char *)(~0)
490 #define AUTO_PICK_ANONYMOUS_LABEL (const char *)(~1)
491 #define AUTO_PICK_XPC_LABEL (const char *)(~2)
493 struct suspended_peruser
{
494 LIST_ENTRY(suspended_peruser
) sle
;
499 kq_callback kqjob_callback
; /* MUST be first element of this structure for benefit of launchd's run loop. */
500 LIST_ENTRY(job_s
) sle
;
501 LIST_ENTRY(job_s
) subjob_sle
;
502 LIST_ENTRY(job_s
) needing_session_sle
;
503 LIST_ENTRY(job_s
) jetsam_sle
;
504 LIST_ENTRY(job_s
) pid_hash_sle
;
505 LIST_ENTRY(job_s
) label_hash_sle
;
506 LIST_ENTRY(job_s
) global_env_sle
;
507 SLIST_ENTRY(job_s
) curious_jobs_sle
;
508 LIST_HEAD(, suspended_peruser
) suspended_perusers
;
509 LIST_HEAD(, waiting_for_exit
) exit_watchers
;
510 LIST_HEAD(, job_s
) subjobs
;
511 LIST_HEAD(, externalevent
) events
;
512 SLIST_HEAD(, socketgroup
) sockets
;
513 SLIST_HEAD(, calendarinterval
) cal_intervals
;
514 SLIST_HEAD(, envitem
) global_env
;
515 SLIST_HEAD(, envitem
) env
;
516 SLIST_HEAD(, limititem
) limits
;
517 SLIST_HEAD(, machservice
) machservices
;
518 SLIST_HEAD(, semaphoreitem
) semaphores
;
519 SLIST_HEAD(, waiting_for_removal
) removal_watchers
;
522 cpu_type_t
*j_binpref
;
523 size_t j_binpref_cnt
;
525 mach_port_t exit_status_dest
;
526 mach_port_t exit_status_port
;
527 mach_port_t spawn_reply_port
;
540 char *alt_exc_handler
;
541 struct vproc_shmem_s
*shmem
;
542 struct machservice
*lastlookup
;
543 unsigned int lastlookup_gennum
;
545 char *seatbelt_profile
;
546 uint64_t seatbelt_flags
;
549 void *quarantine_data
;
550 size_t quarantine_data_sz
;
553 int last_exit_status
;
560 int32_t jetsam_priority
;
561 int32_t jetsam_memlimit
;
563 int32_t main_thread_priority
;
565 uint32_t exit_timeout
;
566 uint64_t sent_signal_time
;
568 uint32_t min_run_time
;
569 uint32_t start_interval
;
570 uint32_t peruser_suspend_count
; /* The number of jobs that have disabled this per-user launchd. */
576 J_TYPE_ANONYMOUS
= 1,
577 J_TYPE_LANCHSERVICES
,
583 debug
:1, /* man launchd.plist --> Debug */
584 ondemand
:1, /* man launchd.plist --> KeepAlive == false */
585 session_create
:1, /* man launchd.plist --> SessionCreate */
586 low_pri_io
:1, /* man launchd.plist --> LowPriorityIO */
587 no_init_groups
:1, /* man launchd.plist --> InitGroups */
588 priv_port_has_senders
:1, /* a legacy mach_init concept to make bootstrap_create_server/service() work */
589 importing_global_env
:1, /* a hack during job importing */
590 importing_hard_limits
:1, /* a hack during job importing */
591 setmask
:1, /* man launchd.plist --> Umask */
592 anonymous
:1, /* a process that launchd knows about, but isn't managed by launchd */
593 checkedin
:1, /* a legacy mach_init concept to detect sick jobs */
594 legacy_mach_job
:1, /* a job created via bootstrap_create_server() */
595 legacy_LS_job
:1, /* a job created via spawn_via_launchd() */
596 inetcompat
:1, /* a legacy job that wants inetd compatible semantics */
597 inetcompat_wait
:1, /* a twist on inetd compatibility */
598 start_pending
:1, /* an event fired and the job should start, but not necessarily right away */
599 globargv
:1, /* man launchd.plist --> EnableGlobbing */
600 wait4debugger
:1, /* man launchd.plist --> WaitForDebugger */
601 wait4debugger_oneshot
:1, /* One-shot WaitForDebugger. */
602 internal_exc_handler
:1, /* MachExceptionHandler == true */
603 stall_before_exec
:1, /* a hack to support an option of spawn_via_launchd() */
604 only_once
:1, /* man launchd.plist --> LaunchOnlyOnce. Note: 5465184 Rename this to "HopefullyNeverExits" */
605 currently_ignored
:1, /* Make job_ignore() / job_watch() work. If these calls were balanced, then this wouldn't be necessarily. */
606 forced_peers_to_demand_mode
:1, /* A job that forced all other jobs to be temporarily launch-on-demand */
607 setnice
:1, /* man launchd.plist --> Nice */
608 removal_pending
:1, /* a job was asked to be unloaded/removed while running, we'll remove it after it exits */
609 sent_sigkill
:1, /* job_kill() was called */
610 debug_before_kill
:1, /* enter the kernel debugger before killing a job */
611 weird_bootstrap
:1, /* a hack that launchd+launchctl use during jobmgr_t creation */
612 start_on_mount
:1, /* man launchd.plist --> StartOnMount */
613 per_user
:1, /* This job is a per-user launchd managed by the PID 1 launchd */
614 unload_at_mig_return
:1, /* A job thoroughly confused launchd. We need to unload it ASAP */
615 abandon_pg
:1, /* man launchd.plist --> AbandonProcessGroup */
616 ignore_pg_at_shutdown
:1, /* During shutdown, do not send SIGTERM to stray processes in the process group of this job. */
617 poll_for_vfs_changes
:1, /* a hack to work around the fact that kqueues don't work on all filesystems */
618 deny_job_creation
:1, /* Don't let this job create new 'job_t' objects in launchd */
619 kill_via_shmem
:1, /* man launchd.plist --> EnableTransactions */
620 sent_kill_via_shmem
:1, /* We need to 'kill_via_shmem' once-and-only-once */
621 clean_kill
:1, /* The job was sent SIGKILL because it was clean. */
622 kill_after_sample
:1, /* The job is to be killed after sampling. */
623 reap_after_trace
:1, /* The job exited before sample did, so we should reap it after sample is done. */
624 nosy
:1, /* The job has an OtherJobEnabled KeepAlive criterion. */
625 crashed
:1, /* The job is the default Mach exception handler, and it crashed. */
626 reaped
:1, /* We've received NOTE_EXIT for the job. */
627 stopped
:1, /* job_stop() was called. */
628 jetsam_frontmost
:1, /* The job is considered "frontmost" by Jetsam. */
629 needs_kickoff
:1, /* The job is to be kept alive continuously, but it must be initially kicked off. */
630 is_bootstrapper
:1, /* The job is a bootstrapper. */
631 has_console
:1, /* The job owns the console. */
632 embedded_special_privileges
:1, /* The job runs as a non-root user on embedded but has select privileges of the root user. */
633 did_exec
:1, /* The job exec(2)ed successfully. */
634 xpcproxy_did_exec
:1, /* The job is an XPC service, and XPC proxy successfully exec(3)ed. */
635 holds_ref
:1, /* The (anonymous) job called vprocmgr_switch_to_session(). */
636 jetsam_properties
:1, /* The job has Jetsam limits in place. */
637 dedicated_instance
:1, /* This job was created as the result of a look up of a service provided by a per-lookup job. */
638 multiple_instances
:1, /* The job supports creating additional instances of itself. */
639 former_subjob
:1, /* The sub-job was already removed from the parent's list of sub-jobs. */
640 event_monitor
:1, /* The job is responsible for monitoring external events for this launchd. */
641 removing
:1, /* A lame hack. */
642 disable_aslr
:1, /* Disable ASLR when launching this job. */
643 xpc_service
:1, /* The job is an XPC Service. */
644 shutdown_monitor
:1, /* The job is the Performance team's shutdown monitor. */
645 dirty_at_shutdown
:1, /* We should open a transaction for the job when shutdown begins. */
646 workaround9359725
:1, /* The job was sent SIGKILL but did not exit in a timely fashion, indicating a kernel bug. */
652 /* Only set for per-user launchd's. */
654 uuid_t expected_audit_uuid
;
658 static size_t hash_label(const char *label
) __attribute__((pure
));
659 static size_t hash_ms(const char *msstr
) __attribute__((pure
));
660 static SLIST_HEAD(, job_s
) s_curious_jobs
;
662 #define job_assumes(j, e) \
663 (unlikely(!(e)) ? job_log_bug(j, __LINE__), false : true)
665 static void job_import_keys(launch_data_t obj
, const char *key
, void *context
);
666 static void job_import_bool(job_t j
, const char *key
, bool value
);
667 static void job_import_string(job_t j
, const char *key
, const char *value
);
668 static void job_import_integer(job_t j
, const char *key
, long long value
);
669 static void job_import_dictionary(job_t j
, const char *key
, launch_data_t value
);
670 static void job_import_array(job_t j
, const char *key
, launch_data_t value
);
671 static void job_import_opaque(job_t j
, const char *key
, launch_data_t value
);
672 static bool job_set_global_on_demand(job_t j
, bool val
);
673 static const char *job_active(job_t j
);
674 static void job_watch(job_t j
);
675 static void job_ignore(job_t j
);
676 static void job_cleanup_after_tracer(job_t j
);
677 static void job_reap(job_t j
);
678 static bool job_useless(job_t j
);
679 static bool job_keepalive(job_t j
);
680 static void job_dispatch_curious_jobs(job_t j
);
681 static void job_start(job_t j
);
682 static void job_start_child(job_t j
) __attribute__((noreturn
));
683 static void job_setup_attributes(job_t j
);
684 static bool job_setup_machport(job_t j
);
685 static kern_return_t
job_setup_exit_port(job_t j
);
686 static void job_setup_fd(job_t j
, int target_fd
, const char *path
, int flags
);
687 static void job_postfork_become_user(job_t j
);
688 static void job_postfork_test_user(job_t j
);
689 static void job_log_pids_with_weird_uids(job_t j
);
690 static void job_setup_exception_port(job_t j
, task_t target_task
);
691 static void job_callback(void *obj
, struct kevent
*kev
);
692 static void job_callback_proc(job_t j
, struct kevent
*kev
);
693 static void job_callback_timer(job_t j
, void *ident
);
694 static void job_callback_read(job_t j
, int ident
);
695 static void job_log_stray_pg(job_t j
);
696 static void job_log_children_without_exec(job_t j
);
697 static job_t
job_new_anonymous(jobmgr_t jm
, pid_t anonpid
) __attribute__((malloc
, nonnull
, warn_unused_result
));
698 static job_t
job_new(jobmgr_t jm
, const char *label
, const char *prog
, const char *const *argv
) __attribute__((malloc
, nonnull(1,2), warn_unused_result
));
699 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
700 static job_t
job_new_alias(jobmgr_t jm
, job_t src
);
701 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
702 static job_t
job_new_via_mach_init(job_t j
, const char *cmd
, uid_t uid
, bool ond
) __attribute__((malloc
, nonnull
, warn_unused_result
));
703 static job_t
job_new_subjob(job_t j
, uuid_t identifier
);
704 static void job_kill(job_t j
);
705 static void job_uncork_fork(job_t j
);
706 static void job_log_stdouterr(job_t j
);
707 static void job_logv(job_t j
, int pri
, int err
, const char *msg
, va_list ap
) __attribute__((format(printf
, 4, 0)));
708 static void job_log_error(job_t j
, int pri
, const char *msg
, ...) __attribute__((format(printf
, 3, 4)));
709 static void job_log_bug(job_t j
, unsigned int line
);
710 static void job_log_stdouterr2(job_t j
, const char *msg
, ...);
711 static void job_set_exception_port(job_t j
, mach_port_t port
);
712 static kern_return_t
job_mig_spawn_internal(job_t j
, vm_offset_t indata
, mach_msg_type_number_t indataCnt
, mach_port_t asport
, job_t
*outj
);
713 static void job_open_shutdown_transaction(job_t ji
);
714 static void job_close_shutdown_transaction(job_t ji
);
716 static const struct {
719 } launchd_keys2limits
[] = {
720 { LAUNCH_JOBKEY_RESOURCELIMIT_CORE
, RLIMIT_CORE
},
721 { LAUNCH_JOBKEY_RESOURCELIMIT_CPU
, RLIMIT_CPU
},
722 { LAUNCH_JOBKEY_RESOURCELIMIT_DATA
, RLIMIT_DATA
},
723 { LAUNCH_JOBKEY_RESOURCELIMIT_FSIZE
, RLIMIT_FSIZE
},
724 { LAUNCH_JOBKEY_RESOURCELIMIT_MEMLOCK
, RLIMIT_MEMLOCK
},
725 { LAUNCH_JOBKEY_RESOURCELIMIT_NOFILE
, RLIMIT_NOFILE
},
726 { LAUNCH_JOBKEY_RESOURCELIMIT_NPROC
, RLIMIT_NPROC
},
727 { LAUNCH_JOBKEY_RESOURCELIMIT_RSS
, RLIMIT_RSS
},
728 { LAUNCH_JOBKEY_RESOURCELIMIT_STACK
, RLIMIT_STACK
},
731 static time_t cronemu(int mon
, int mday
, int hour
, int min
);
732 static time_t cronemu_wday(int wday
, int hour
, int min
);
733 static bool cronemu_mon(struct tm
*wtm
, int mon
, int mday
, int hour
, int min
);
734 static bool cronemu_mday(struct tm
*wtm
, int mday
, int hour
, int min
);
735 static bool cronemu_hour(struct tm
*wtm
, int hour
, int min
);
736 static bool cronemu_min(struct tm
*wtm
, int min
);
738 /* These functions are a total nightmare to get to through headers.
739 * See rdar://problem/8223092.
741 typedef __darwin_mach_port_t fileport_t
;
742 #define FILEPORT_NULL ((fileport_t)0)
743 extern int fileport_makeport(int, fileport_t
*);
744 extern int fileport_makefd(fileport_t
);
746 /* miscellaneous file local functions */
747 static size_t get_kern_max_proc(void);
748 static int dir_has_files(job_t j
, const char *path
);
749 static char **mach_cmd2argv(const char *string
);
750 static size_t our_strhash(const char *s
) __attribute__((pure
));
751 static void extract_rcsid_substr(const char *i
, char *o
, size_t osz
);
753 void eliminate_double_reboot(void);
755 /* file local globals */
756 static size_t total_children
;
757 static size_t total_anon_children
;
758 static mach_port_t the_exception_server
;
759 static job_t workaround_5477111
;
760 static LIST_HEAD(, job_s
) s_needing_sessions
;
761 static LIST_HEAD(, eventsystem
) _s_event_systems
;
762 static job_t _s_event_monitor
;
763 static job_t _s_xpc_bootstrapper
;
764 static job_t _s_shutdown_monitor
;
765 static mach_port_t _s_event_update_port
;
766 mach_port_t g_audit_session_port
= MACH_PORT_NULL
;
767 static uint32_t s_jetsam_sequence_id
;
769 #if !TARGET_OS_EMBEDDED
770 static job_t s_embedded_privileged_job
= (job_t
)&root_jobmgr
;
771 au_asid_t g_audit_session
= AU_DEFAUDITSID
;
773 static job_t s_embedded_privileged_job
= NULL
;
774 pid_t g_audit_session
= 0;
777 static int s_no_hang_fd
= -1;
779 /* process wide globals */
780 mach_port_t inherited_bootstrap_port
;
781 jobmgr_t root_jobmgr
;
782 bool g_shutdown_debugging
= false;
783 bool g_verbose_boot
= false;
784 bool g_embedded_privileged_action
= false;
785 bool g_runtime_busy_time
= false;
790 struct semaphoreitem
*si
;
791 struct socketgroup
*sg
;
792 struct machservice
*ms
;
794 if (j
->currently_ignored
) {
798 job_log(j
, LOG_DEBUG
, "Ignoring...");
800 j
->currently_ignored
= true;
802 if (j
->poll_for_vfs_changes
) {
803 j
->poll_for_vfs_changes
= false;
804 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->semaphores
, EVFILT_TIMER
, EV_DELETE
, 0, 0, j
) != -1);
807 SLIST_FOREACH(sg
, &j
->sockets
, sle
) {
808 socketgroup_ignore(j
, sg
);
811 SLIST_FOREACH(ms
, &j
->machservices
, sle
) {
812 machservice_ignore(j
, ms
);
815 SLIST_FOREACH(si
, &j
->semaphores
, sle
) {
816 semaphoreitem_ignore(j
, si
);
823 struct semaphoreitem
*si
;
824 struct socketgroup
*sg
;
825 struct machservice
*ms
;
827 if (!j
->currently_ignored
) {
831 job_log(j
, LOG_DEBUG
, "Watching...");
833 j
->currently_ignored
= false;
835 SLIST_FOREACH(sg
, &j
->sockets
, sle
) {
836 socketgroup_watch(j
, sg
);
839 SLIST_FOREACH(ms
, &j
->machservices
, sle
) {
840 machservice_watch(j
, ms
);
843 SLIST_FOREACH(si
, &j
->semaphores
, sle
) {
844 semaphoreitem_watch(j
, si
);
854 if (unlikely(!j
->p
|| j
->stopped
|| j
->anonymous
)) {
858 #if TARGET_OS_EMBEDDED
859 if (g_embedded_privileged_action
&& s_embedded_privileged_job
) {
860 if (!job_assumes(j
, s_embedded_privileged_job
->username
!= NULL
&& j
->username
!= NULL
)) {
865 if (strcmp(j
->username
, s_embedded_privileged_job
->username
) != 0) {
869 } else if (g_embedded_privileged_action
) {
875 if (j
->kill_via_shmem
) {
877 if (!j
->sent_kill_via_shmem
) {
878 j
->shmem
->vp_shmem_flags
|= VPROC_SHMEM_EXITING
;
879 newval
= __sync_sub_and_fetch(&j
->shmem
->vp_shmem_transaction_cnt
, 1);
880 j
->sent_kill_via_shmem
= true;
882 newval
= j
->shmem
->vp_shmem_transaction_cnt
;
889 j
->sent_signal_time
= runtime_get_opaque_time();
892 j
->clean_kill
= true;
895 (void)job_assumes(j
, runtime_kill(j
->p
, SIGTERM
) != -1);
897 if (j
->exit_timeout
) {
898 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->exit_timeout
, EVFILT_TIMER
, EV_ADD
|EV_ONESHOT
, NOTE_SECONDS
, j
->exit_timeout
, j
) != -1);
900 job_log(j
, LOG_NOTICE
, "This job has an infinite exit timeout");
903 if (j
->kill_via_shmem
) {
904 snprintf(extralog
, sizeof(extralog
), ": %d remaining transactions", newval
+ 1);
909 job_log(j
, LOG_DEBUG
, "Sent SIGTERM signal%s", extralog
);
918 launch_data_t tmp
, tmp2
, tmp3
, r
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
924 if ((tmp
= launch_data_new_string(j
->label
))) {
925 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_LABEL
);
927 if ((tmp
= launch_data_new_string(j
->mgr
->name
))) {
928 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
);
930 if ((tmp
= launch_data_new_bool(j
->ondemand
))) {
931 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_ONDEMAND
);
933 if ((tmp
= launch_data_new_integer(j
->last_exit_status
))) {
934 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_LASTEXITSTATUS
);
936 if (j
->p
&& (tmp
= launch_data_new_integer(j
->p
))) {
937 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_PID
);
939 if ((tmp
= launch_data_new_integer(j
->timeout
))) {
940 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_TIMEOUT
);
942 if (j
->prog
&& (tmp
= launch_data_new_string(j
->prog
))) {
943 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_PROGRAM
);
945 if (j
->stdinpath
&& (tmp
= launch_data_new_string(j
->stdinpath
))) {
946 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_STANDARDINPATH
);
948 if (j
->stdoutpath
&& (tmp
= launch_data_new_string(j
->stdoutpath
))) {
949 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_STANDARDOUTPATH
);
951 if (j
->stderrpath
&& (tmp
= launch_data_new_string(j
->stderrpath
))) {
952 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_STANDARDERRORPATH
);
954 if (likely(j
->argv
) && (tmp
= launch_data_alloc(LAUNCH_DATA_ARRAY
))) {
957 for (i
= 0; i
< j
->argc
; i
++) {
958 if ((tmp2
= launch_data_new_string(j
->argv
[i
]))) {
959 launch_data_array_set_index(tmp
, tmp2
, i
);
963 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_PROGRAMARGUMENTS
);
966 if (j
->kill_via_shmem
&& (tmp
= launch_data_new_bool(true))) {
967 int32_t tmp_cnt
= -1;
969 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_ENABLETRANSACTIONS
);
972 tmp_cnt
= j
->shmem
->vp_shmem_transaction_cnt
;
975 if (j
->sent_kill_via_shmem
) {
979 if ((tmp
= launch_data_new_integer(tmp_cnt
))) {
980 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_TRANSACTIONCOUNT
);
984 if (j
->session_create
&& (tmp
= launch_data_new_bool(true))) {
985 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_SESSIONCREATE
);
988 if (j
->inetcompat
&& (tmp
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
))) {
989 if ((tmp2
= launch_data_new_bool(j
->inetcompat_wait
))) {
990 launch_data_dict_insert(tmp
, tmp2
, LAUNCH_JOBINETDCOMPATIBILITY_WAIT
);
992 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_INETDCOMPATIBILITY
);
995 if (!SLIST_EMPTY(&j
->sockets
) && (tmp
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
))) {
996 struct socketgroup
*sg
;
999 SLIST_FOREACH(sg
, &j
->sockets
, sle
) {
1003 if ((tmp2
= launch_data_alloc(LAUNCH_DATA_ARRAY
))) {
1004 for (i
= 0; i
< sg
->fd_cnt
; i
++) {
1005 if ((tmp3
= launch_data_new_fd(sg
->fds
[i
]))) {
1006 launch_data_array_set_index(tmp2
, tmp3
, i
);
1009 launch_data_dict_insert(tmp
, tmp2
, sg
->name
);
1013 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_SOCKETS
);
1016 if (!SLIST_EMPTY(&j
->machservices
) && (tmp
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
))) {
1017 struct machservice
*ms
;
1021 SLIST_FOREACH(ms
, &j
->machservices
, sle
) {
1024 tmp3
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
1027 tmp2
= launch_data_new_machport(MACH_PORT_NULL
);
1028 launch_data_dict_insert(tmp3
, tmp2
, ms
->name
);
1031 tmp2
= launch_data_new_machport(MACH_PORT_NULL
);
1032 launch_data_dict_insert(tmp
, tmp2
, ms
->name
);
1036 launch_data_dict_insert(r
, tmp
, LAUNCH_JOBKEY_MACHSERVICES
);
1039 launch_data_dict_insert(r
, tmp3
, LAUNCH_JOBKEY_PERJOBMACHSERVICES
);
1047 jobmgr_log_active_jobs(jobmgr_t jm
)
1049 const char *why_active
;
1053 SLIST_FOREACH(jmi
, &jm
->submgrs
, sle
) {
1054 jobmgr_log_active_jobs(jmi
);
1057 LIST_FOREACH(ji
, &jm
->jobs
, sle
) {
1058 if ((why_active
= job_active(ji
))) {
1060 job_log(ji
, LOG_DEBUG
| LOG_CONSOLE
, "%s", why_active
);
1067 jobmgr_still_alive_with_check(jobmgr_t jm
)
1069 jobmgr_log(jm
, LOG_DEBUG
| LOG_CONSOLE
, "Still alive with %lu/%lu (normal/anonymous) children.", total_children
, total_anon_children
);
1070 jobmgr_log_active_jobs(jm
);
1074 jobmgr_shutdown(jobmgr_t jm
)
1077 jobmgr_log(jm
, LOG_DEBUG
, "Beginning job manager shutdown with flags: %s", reboot_flags_to_C_names(jm
->reboot_flags
));
1079 jm
->shutdown_time
= runtime_get_wall_time() / USEC_PER_SEC
;
1082 (void)localtime_r(&jm
->shutdown_time
, &curtime
);
1085 (void)asctime_r(&curtime
, date
);
1086 /* Trim the new line that asctime_r(3) puts there for some reason. */
1089 if (jm
== root_jobmgr
&& pid1_magic
) {
1090 jobmgr_log(jm
, LOG_DEBUG
| LOG_CONSOLE
, "Userspace shutdown begun at: %s", date
);
1092 jobmgr_log(jm
, LOG_DEBUG
, "Job manager shutdown begun at: %s", date
);
1095 jm
->shutting_down
= true;
1097 SLIST_FOREACH_SAFE(jmi
, &jm
->submgrs
, sle
, jmn
) {
1098 jobmgr_shutdown(jmi
);
1101 if (jm
->parentmgr
== NULL
&& pid1_magic
) {
1102 (void)jobmgr_assumes(jm
, kevent_mod((uintptr_t)jm
, EVFILT_TIMER
, EV_ADD
, NOTE_SECONDS
, 5, jm
));
1104 /* Spawn the shutdown monitor. */
1105 if (_s_shutdown_monitor
&& !_s_shutdown_monitor
->p
) {
1106 job_log(_s_shutdown_monitor
, LOG_NOTICE
| LOG_CONSOLE
, "Starting shutdown monitor.");
1107 job_dispatch(_s_shutdown_monitor
, true);
1111 return jobmgr_do_garbage_collection(jm
);
1115 jobmgr_remove(jobmgr_t jm
)
1120 jobmgr_log(jm
, LOG_DEBUG
, "Removing job manager.");
1121 if (!jobmgr_assumes(jm
, SLIST_EMPTY(&jm
->submgrs
))) {
1122 while ((jmi
= SLIST_FIRST(&jm
->submgrs
))) {
1127 while ((ji
= LIST_FIRST(&jm
->jobs
))) {
1128 if (!ji
->anonymous
&& !job_assumes(ji
, ji
->p
== 0)) {
1135 (void)jobmgr_assumes(jm
, launchd_mport_deallocate(jm
->req_port
) == KERN_SUCCESS
);
1138 (void)jobmgr_assumes(jm
, launchd_mport_close_recv(jm
->jm_port
) == KERN_SUCCESS
);
1141 if (jm
->req_bsport
) {
1142 (void)jobmgr_assumes(jm
, launchd_mport_deallocate(jm
->req_bsport
) == KERN_SUCCESS
);
1144 if (jm
->req_excport
) {
1145 (void)jobmgr_assumes(jm
, launchd_mport_deallocate(jm
->req_excport
) == KERN_SUCCESS
);
1147 if (jm
->req_asport
) {
1148 (void)jobmgr_assumes(jm
, launchd_mport_deallocate(jm
->req_asport
) == KERN_SUCCESS
);
1150 #if !TARGET_OS_EMBEDDED
1151 if (jm
->req_rport
) {
1152 kern_return_t kr
= xpc_call_wakeup(jm
->req_rport
, jm
->error
);
1153 if (!(kr
== KERN_SUCCESS
|| kr
== MACH_SEND_INVALID_DEST
)) {
1154 /* If the originator went away, the reply port will be a dead name,
1155 * and we expect this to fail.
1158 (void)jobmgr_assumes(jm
, kr
== KERN_SUCCESS
);
1161 #endif /* !TARGET_OS_EMBEDDED */
1163 (void)jobmgr_assumes(jm
, vm_deallocate(mach_task_self(), jm
->req_ctx
, jm
->req_ctx_sz
) == KERN_SUCCESS
);
1166 time_t ts
= runtime_get_wall_time() / USEC_PER_SEC
;
1168 (void)localtime_r(&ts
, &curtime
);
1171 (void)asctime_r(&curtime
, date
);
1174 time_t delta
= ts
- jm
->shutdown_time
;
1175 if (jm
== root_jobmgr
&& pid1_magic
) {
1176 jobmgr_log(jm
, LOG_DEBUG
| LOG_CONSOLE
, "Userspace shutdown finished at: %s", date
);
1177 jobmgr_log(jm
, LOG_DEBUG
| LOG_CONSOLE
, "Userspace shutdown took approximately %ld second%s.", delta
, (delta
!= 1) ? "s" : "");
1179 jobmgr_log(jm
, LOG_DEBUG
, "Job manager shutdown finished at: %s", date
);
1180 jobmgr_log(jm
, LOG_DEBUG
, "Job manager shutdown took approximately %ld second%s.", delta
, (delta
!= 1) ? "s" : "");
1183 if (jm
->parentmgr
) {
1184 runtime_del_weak_ref();
1185 SLIST_REMOVE(&jm
->parentmgr
->submgrs
, jm
, jobmgr_s
, sle
);
1186 } else if (pid1_magic
) {
1187 eliminate_double_reboot();
1188 launchd_log_vm_stats();
1189 jobmgr_log_stray_children(jm
, true);
1190 jobmgr_log(root_jobmgr
, LOG_NOTICE
| LOG_CONSOLE
, "About to call: reboot(%s).", reboot_flags_to_C_names(jm
->reboot_flags
));
1192 (void)jobmgr_assumes(jm
, reboot(jm
->reboot_flags
) != -1);
1194 jobmgr_log(jm
, LOG_DEBUG
, "About to exit");
1205 struct waiting_for_removal
*w4r
;
1206 struct calendarinterval
*ci
;
1207 struct semaphoreitem
*si
;
1208 struct socketgroup
*sg
;
1209 struct machservice
*ms
;
1210 struct limititem
*li
;
1214 /* HACK: Egregious code duplication. But as with machservice_delete(),
1215 * job aliases can't (and shouldn't) have any complex behaviors
1216 * associated with them.
1218 while ((ms
= SLIST_FIRST(&j
->machservices
))) {
1219 machservice_delete(j
, ms
, false);
1222 LIST_REMOVE(j
, sle
);
1223 LIST_REMOVE(j
, label_hash_sle
);
1228 #if TARGET_OS_EMBEDDED
1229 if (g_embedded_privileged_action
&& s_embedded_privileged_job
) {
1230 if (!job_assumes(j
, s_embedded_privileged_job
->username
!= NULL
&& j
->username
!= NULL
)) {
1235 if (strcmp(j
->username
, s_embedded_privileged_job
->username
) != 0) {
1239 } else if (g_embedded_privileged_action
) {
1245 /* Do this BEFORE we check and see whether the job is still active. If we're a
1246 * sub-job, we're being removed due to the parent job removing us. Therefore, the
1247 * parent job will free itself after this call completes. So if we defer removing
1248 * ourselves from the parent's list, we'll crash when we finally get around to it.
1250 if (j
->dedicated_instance
&& !j
->former_subjob
) {
1251 LIST_REMOVE(j
, subjob_sle
);
1252 j
->former_subjob
= true;
1255 if (unlikely(j
->p
)) {
1259 job_log(j
, LOG_DEBUG
, "Removal pended until the job exits");
1261 if (!j
->removal_pending
) {
1262 j
->removal_pending
= true;
1272 job_dispatch_curious_jobs(j
);
1275 ipc_close_all_with_job(j
);
1277 job_log(j
, LOG_INFO
, "Total rusage: utime %ld.%06u stime %ld.%06u maxrss %lu ixrss %lu idrss %lu isrss %lu minflt %lu majflt %lu nswap %lu inblock %lu oublock %lu msgsnd %lu msgrcv %lu nsignals %lu nvcsw %lu nivcsw %lu",
1278 j
->ru
.ru_utime
.tv_sec
, j
->ru
.ru_utime
.tv_usec
,
1279 j
->ru
.ru_stime
.tv_sec
, j
->ru
.ru_stime
.tv_usec
,
1280 j
->ru
.ru_maxrss
, j
->ru
.ru_ixrss
, j
->ru
.ru_idrss
, j
->ru
.ru_isrss
,
1281 j
->ru
.ru_minflt
, j
->ru
.ru_majflt
,
1282 j
->ru
.ru_nswap
, j
->ru
.ru_inblock
, j
->ru
.ru_oublock
,
1283 j
->ru
.ru_msgsnd
, j
->ru
.ru_msgrcv
,
1284 j
->ru
.ru_nsignals
, j
->ru
.ru_nvcsw
, j
->ru
.ru_nivcsw
);
1286 if (j
->forced_peers_to_demand_mode
) {
1287 job_set_global_on_demand(j
, false);
1290 if (!job_assumes(j
, j
->fork_fd
== 0)) {
1291 (void)job_assumes(j
, runtime_close(j
->fork_fd
) != -1);
1295 (void)job_assumes(j
, runtime_close(j
->stdin_fd
) != -1);
1298 if (!job_assumes(j
, j
->log_redirect_fd
== 0)) {
1299 (void)job_assumes(j
, runtime_close(j
->log_redirect_fd
) != -1);
1303 (void)job_assumes(j
, launchd_mport_close_recv(j
->j_port
) == KERN_SUCCESS
);
1306 while ((sg
= SLIST_FIRST(&j
->sockets
))) {
1307 socketgroup_delete(j
, sg
);
1309 while ((ci
= SLIST_FIRST(&j
->cal_intervals
))) {
1310 calendarinterval_delete(j
, ci
);
1312 while ((ei
= SLIST_FIRST(&j
->env
))) {
1313 envitem_delete(j
, ei
, false);
1315 while ((ei
= SLIST_FIRST(&j
->global_env
))) {
1316 envitem_delete(j
, ei
, true);
1318 while ((li
= SLIST_FIRST(&j
->limits
))) {
1319 limititem_delete(j
, li
);
1321 while ((ms
= SLIST_FIRST(&j
->machservices
))) {
1322 machservice_delete(j
, ms
, false);
1324 while ((si
= SLIST_FIRST(&j
->semaphores
))) {
1325 semaphoreitem_delete(j
, si
);
1327 while ((w4r
= SLIST_FIRST(&j
->removal_watchers
))) {
1328 waiting4removal_delete(j
, w4r
);
1331 struct externalevent
*eei
= NULL
;
1332 while ((eei
= LIST_FIRST(&j
->events
))) {
1334 externalevent_delete(eei
);
1338 /* Event systems exist independently of an actual monitor job. They're
1339 * created on-demand when a job has a LaunchEvents dictionary. So we
1340 * really don't need to get rid of them.
1342 if (j
->event_monitor
) {
1343 struct eventsystem
*esi
= NULL
;
1344 while ((esi
= LIST_FIRST(&_s_event_systems
))) {
1345 eventsystem_delete(esi
);
1350 /* Make gcc happy. */
1351 eventsystem_delete(NULL
);
1353 if (j
->event_monitor
) {
1354 if (_s_event_update_port
!= MACH_PORT_NULL
) {
1355 (void)job_assumes(j
, launchd_mport_deallocate(_s_event_update_port
) == KERN_SUCCESS
);
1356 _s_event_update_port
= MACH_PORT_NULL
;
1358 _s_event_monitor
= NULL
;
1371 if (j
->workingdir
) {
1372 free(j
->workingdir
);
1383 if (j
->stdoutpath
) {
1384 free(j
->stdoutpath
);
1386 if (j
->stderrpath
) {
1387 free(j
->stderrpath
);
1389 if (j
->alt_exc_handler
) {
1390 free(j
->alt_exc_handler
);
1393 if (j
->seatbelt_profile
) {
1394 free(j
->seatbelt_profile
);
1398 if (j
->quarantine_data
) {
1399 free(j
->quarantine_data
);
1405 if (j
->start_interval
) {
1406 runtime_del_weak_ref();
1407 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->start_interval
, EVFILT_TIMER
, EV_DELETE
, 0, 0, NULL
) != -1);
1409 if (j
->poll_for_vfs_changes
) {
1410 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->semaphores
, EVFILT_TIMER
, EV_DELETE
, 0, 0, j
) != -1);
1412 if (j
->exit_timeout
) {
1413 /* Not a big deal if this fails. It means that the timer's already been freed. */
1414 kevent_mod((uintptr_t)&j
->exit_timeout
, EVFILT_TIMER
, EV_DELETE
, 0, 0, NULL
);
1416 if (j
->jetsam_properties
) {
1417 LIST_REMOVE(j
, jetsam_sle
);
1418 j
->mgr
->jetsam_jobs_cnt
--;
1420 if (j
->asport
!= MACH_PORT_NULL
) {
1421 (void)job_assumes(j
, launchd_mport_deallocate(j
->asport
) == KERN_SUCCESS
);
1423 if (!uuid_is_null(j
->expected_audit_uuid
)) {
1424 LIST_REMOVE(j
, needing_session_sle
);
1426 if (j
->embedded_special_privileges
) {
1427 s_embedded_privileged_job
= NULL
;
1429 if (j
->shutdown_monitor
) {
1430 _s_shutdown_monitor
= NULL
;
1433 kevent_mod((uintptr_t)j
, EVFILT_TIMER
, EV_DELETE
, 0, 0, NULL
);
1435 LIST_REMOVE(j
, sle
);
1436 LIST_REMOVE(j
, label_hash_sle
);
1440 LIST_FOREACH_SAFE(ji
, &j
->subjobs
, subjob_sle
, jit
) {
1444 job_log(j
, LOG_DEBUG
, "Removed");
1446 j
->kqjob_callback
= (kq_callback
)0x8badf00d;
1451 socketgroup_setup(launch_data_t obj
, const char *key
, void *context
)
1453 launch_data_t tmp_oai
;
1455 size_t i
, fd_cnt
= 1;
1458 if (launch_data_get_type(obj
) == LAUNCH_DATA_ARRAY
) {
1459 fd_cnt
= launch_data_array_get_count(obj
);
1462 fds
= alloca(fd_cnt
* sizeof(int));
1464 for (i
= 0; i
< fd_cnt
; i
++) {
1465 if (launch_data_get_type(obj
) == LAUNCH_DATA_ARRAY
) {
1466 tmp_oai
= launch_data_array_get_index(obj
, i
);
1471 fds
[i
] = launch_data_get_fd(tmp_oai
);
1474 socketgroup_new(j
, key
, fds
, fd_cnt
, strcmp(key
, LAUNCH_JOBKEY_BONJOURFDS
) == 0);
1476 ipc_revoke_fds(obj
);
1480 job_set_global_on_demand(job_t j
, bool val
)
1482 if (j
->forced_peers_to_demand_mode
&& val
) {
1484 } else if (!j
->forced_peers_to_demand_mode
&& !val
) {
1488 if ((j
->forced_peers_to_demand_mode
= val
)) {
1489 j
->mgr
->global_on_demand_cnt
++;
1491 j
->mgr
->global_on_demand_cnt
--;
1494 if (j
->mgr
->global_on_demand_cnt
== 0) {
1495 jobmgr_dispatch_all(j
->mgr
, false);
1502 job_setup_machport(job_t j
)
1504 mach_msg_size_t mxmsgsz
;
1506 if (!job_assumes(j
, launchd_mport_create_recv(&j
->j_port
) == KERN_SUCCESS
)) {
1510 /* Sigh... at the moment, MIG has maxsize == sizeof(reply union) */
1511 mxmsgsz
= (typeof(mxmsgsz
)) sizeof(union __RequestUnion__job_mig_protocol_vproc_subsystem
);
1512 if (job_mig_protocol_vproc_subsystem
.maxsize
> mxmsgsz
) {
1513 mxmsgsz
= job_mig_protocol_vproc_subsystem
.maxsize
;
1516 if (!job_assumes(j
, runtime_add_mport(j
->j_port
, protocol_vproc_server
, mxmsgsz
) == KERN_SUCCESS
)) {
1520 if (!job_assumes(j
, launchd_mport_notify_req(j
->j_port
, MACH_NOTIFY_NO_SENDERS
) == KERN_SUCCESS
)) {
1521 (void)job_assumes(j
, launchd_mport_close_recv(j
->j_port
) == KERN_SUCCESS
);
1527 (void)job_assumes(j
, launchd_mport_close_recv(j
->j_port
) == KERN_SUCCESS
);
1533 job_setup_exit_port(job_t j
)
1535 kern_return_t kr
= launchd_mport_create_recv(&j
->exit_status_port
);
1536 if (!job_assumes(j
, kr
== KERN_SUCCESS
)) {
1537 return MACH_PORT_NULL
;
1540 struct mach_port_limits limits
= {
1543 kr
= mach_port_set_attributes(mach_task_self(), j
->exit_status_port
, MACH_PORT_LIMITS_INFO
, (mach_port_info_t
)&limits
, sizeof(limits
));
1544 (void)job_assumes(j
, kr
== KERN_SUCCESS
);
1546 kr
= launchd_mport_make_send_once(j
->exit_status_port
, &j
->exit_status_dest
);
1547 if (!job_assumes(j
, kr
== KERN_SUCCESS
)) {
1548 (void)job_assumes(j
, launchd_mport_close_recv(j
->exit_status_port
) == KERN_SUCCESS
);
1549 j
->exit_status_port
= MACH_PORT_NULL
;
1556 job_new_via_mach_init(job_t j
, const char *cmd
, uid_t uid
, bool ond
)
1558 const char **argv
= (const char **)mach_cmd2argv(cmd
);
1561 if (!job_assumes(j
, argv
!= NULL
)) {
1565 jr
= job_new(j
->mgr
, AUTO_PICK_LEGACY_LABEL
, NULL
, argv
);
1569 /* jobs can easily be denied creation during shutdown */
1570 if (unlikely(jr
== NULL
)) {
1576 jr
->legacy_mach_job
= true;
1577 jr
->abandon_pg
= true;
1578 jr
->priv_port_has_senders
= true; /* the IPC that called us will make-send on this port */
1580 if (!job_setup_machport(jr
)) {
1584 job_log(jr
, LOG_INFO
, "Legacy%s server created", ond
? " on-demand" : "");
1596 job_new_anonymous(jobmgr_t jm
, pid_t anonpid
)
1598 struct proc_bsdshortinfo proc
;
1599 bool shutdown_state
;
1600 job_t jp
= NULL
, jr
= NULL
;
1601 uid_t kp_euid
, kp_uid
, kp_svuid
;
1602 gid_t kp_egid
, kp_gid
, kp_svgid
;
1604 if (!jobmgr_assumes(jm
, anonpid
!= 0)) {
1609 if (!jobmgr_assumes(jm
, anonpid
< 100000)) {
1610 /* The kernel current defines PID_MAX to be 99999, but that define isn't exported */
1615 /* libproc returns the number of bytes written into the buffer upon success,
1618 if (proc_pidinfo(anonpid
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
1619 if (errno
!= ESRCH
) {
1620 (void)jobmgr_assumes(jm
, errno
== 0);
1625 if (!jobmgr_assumes(jm
, proc
.pbsi_comm
[0] != '\0')) {
1630 if (unlikely(proc
.pbsi_status
== SZOMB
)) {
1631 jobmgr_log(jm
, LOG_DEBUG
, "Tried to create an anonymous job for zombie PID %u: %s", anonpid
, proc
.pbsi_comm
);
1634 if (unlikely(proc
.pbsi_flags
& P_SUGID
)) {
1635 jobmgr_log(jm
, LOG_DEBUG
, "Inconsistency: P_SUGID is set on PID %u: %s", anonpid
, proc
.pbsi_comm
);
1638 kp_euid
= proc
.pbsi_uid
;
1639 kp_uid
= proc
.pbsi_ruid
;
1640 kp_svuid
= proc
.pbsi_svuid
;
1641 kp_egid
= proc
.pbsi_gid
;
1642 kp_gid
= proc
.pbsi_rgid
;
1643 kp_svgid
= proc
.pbsi_svgid
;
1645 if (unlikely(kp_euid
!= kp_uid
|| kp_euid
!= kp_svuid
|| kp_uid
!= kp_svuid
|| kp_egid
!= kp_gid
|| kp_egid
!= kp_svgid
|| kp_gid
!= kp_svgid
)) {
1646 jobmgr_log(jm
, LOG_DEBUG
, "Inconsistency: Mixed credentials (e/r/s UID %u/%u/%u GID %u/%u/%u) detected on PID %u: %s",
1647 kp_euid
, kp_uid
, kp_svuid
, kp_egid
, kp_gid
, kp_svgid
, anonpid
, proc
.pbsi_comm
);
1650 /* "Fix" for a problem that shouldn't even exist.
1651 * See rdar://problem/7264615 for the symptom and rdar://problem/5020256
1652 * as to why this can happen.
1654 if (!jobmgr_assumes(jm
, (pid_t
)proc
.pbsi_ppid
!= anonpid
)) {
1655 jobmgr_log(jm
, LOG_WARNING
, "Process has become its own parent through ptrace(3). It should find a different way to do whatever it's doing. Setting PPID to 0: %s", proc
.pbsi_comm
);
1660 /* A total hack: Normally, job_new() returns an error during shutdown, but anonymous jobs are special. */
1661 if (unlikely(shutdown_state
= jm
->shutting_down
)) {
1662 jm
->shutting_down
= false;
1665 /* We only set requestor_pid for XPC domains. */
1666 const char *whichlabel
= (jm
->req_pid
== anonpid
) ? AUTO_PICK_XPC_LABEL
: AUTO_PICK_ANONYMOUS_LABEL
;
1667 if (jobmgr_assumes(jm
, (jr
= job_new(jm
, whichlabel
, proc
.pbsi_comm
, NULL
)) != NULL
)) {
1668 u_int proc_fflags
= NOTE_EXEC
|NOTE_FORK
|NOTE_EXIT
;
1670 total_anon_children
++;
1671 jr
->anonymous
= true;
1674 /* anonymous process reaping is messy */
1675 LIST_INSERT_HEAD(&jm
->active_jobs
[ACTIVE_JOB_HASH(jr
->p
)], jr
, pid_hash_sle
);
1677 if (unlikely(kevent_mod(jr
->p
, EVFILT_PROC
, EV_ADD
, proc_fflags
, 0, root_jobmgr
) == -1) && job_assumes(jr
, errno
== ESRCH
)) {
1678 /* zombies are weird */
1679 job_log(jr
, LOG_ERR
, "Failed to add kevent for PID %u. Will unload at MIG return", jr
->p
);
1680 jr
->unload_at_mig_return
= true;
1683 if (unlikely(shutdown_state
)) {
1684 job_log(jr
, LOG_SCOLDING
, "This process showed up to the party while all the guests were leaving. Odds are that it will have a miserable time.");
1687 job_log(jr
, LOG_DEBUG
, "Created PID %u anonymously by PPID %u%s%s", anonpid
, proc
.pbsi_ppid
, jp
? ": " : "", jp
? jp
->label
: "");
1690 if (unlikely(shutdown_state
)) {
1691 jm
->shutting_down
= true;
1694 /* This is down here to mitigate the effects of rdar://problem/7264615, in which a process
1695 * attaches to its own parent. We need to make sure that the anonymous job has been added
1696 * to the process list so that, if it's used ptrace(3) to cause a cycle in the process
1697 * tree (thereby making it not a tree anymore), we'll find the tracing parent PID of the
1698 * parent process, which is the child, when we go looking for it in jobmgr_find_by_pid().
1700 switch (proc
.pbsi_ppid
) {
1706 /* we cannot possibly find a parent job_t that is useful in this function */
1711 jp
= jobmgr_find_by_pid(jm
, proc
.pbsi_ppid
, true);
1712 if (jobmgr_assumes(jm
, jp
!= NULL
)) {
1713 if (jp
&& !jp
->anonymous
&& unlikely(!(proc
.pbsi_flags
& P_EXEC
))) {
1714 job_log(jp
, LOG_DEBUG
, "Called *fork(). Please switch to posix_spawn*(), pthreads or launchd. Child PID %u", proc
.pbsi_pid
);
1724 job_new_subjob(job_t j
, uuid_t identifier
)
1727 uuid_string_t idstr
;
1728 uuid_unparse(identifier
, idstr
);
1729 size_t label_sz
= snprintf(label
, 0, "%s.%s", j
->label
, idstr
);
1731 job_t nj
= (struct job_s
*)calloc(1, sizeof(struct job_s
) + label_sz
+ 1);
1732 if (launchd_assumes(nj
!= NULL
)) {
1733 nj
->kqjob_callback
= job_callback
;
1735 nj
->min_run_time
= j
->min_run_time
;
1736 nj
->timeout
= j
->timeout
;
1737 nj
->exit_timeout
= j
->exit_timeout
;
1739 snprintf((char *)nj
->label
, label_sz
+ 1, "%s.%s", j
->label
, idstr
);
1741 /* Set all our simple Booleans that are applicable. */
1742 nj
->debug
= j
->debug
;
1743 nj
->ondemand
= j
->ondemand
;
1744 nj
->checkedin
= true;
1745 nj
->low_pri_io
= j
->low_pri_io
;
1746 nj
->setmask
= j
->setmask
;
1747 nj
->wait4debugger
= j
->wait4debugger
;
1748 nj
->internal_exc_handler
= j
->internal_exc_handler
;
1749 nj
->setnice
= j
->setnice
;
1750 nj
->abandon_pg
= j
->abandon_pg
;
1751 nj
->ignore_pg_at_shutdown
= j
->ignore_pg_at_shutdown
;
1752 nj
->deny_job_creation
= j
->deny_job_creation
;
1753 nj
->kill_via_shmem
= j
->kill_via_shmem
;
1754 nj
->needs_kickoff
= j
->needs_kickoff
;
1755 nj
->currently_ignored
= true;
1756 nj
->dedicated_instance
= true;
1757 nj
->xpc_service
= j
->xpc_service
;
1758 nj
->xpc_bootstrapper
= j
->xpc_bootstrapper
;
1761 uuid_copy(nj
->instance_id
, identifier
);
1763 /* These jobs are purely on-demand Mach jobs. */
1765 /* {Hard | Soft}ResourceLimits are not supported. */
1767 struct machservice
*msi
= NULL
;
1768 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
1769 /* Only copy MachServices that were actually declared in the plist.
1770 * So skip over per-PID ones and ones that were created via
1771 * bootstrap_register().
1774 mach_port_t mp
= MACH_PORT_NULL
;
1775 struct machservice
*msj
= machservice_new(nj
, msi
->name
, &mp
, msi
->per_pid
);
1776 if (job_assumes(nj
, msj
!= NULL
)) {
1777 msj
->reset
= msi
->reset
;
1778 msj
->delete_on_destruction
= msi
->delete_on_destruction
;
1779 msj
->drain_one_on_crash
= msi
->drain_one_on_crash
;
1780 msj
->drain_all_on_crash
= msi
->drain_all_on_crash
;
1786 nj
->prog
= strdup(j
->prog
);
1789 size_t sz
= malloc_size(j
->argv
);
1790 nj
->argv
= (char **)malloc(sz
);
1791 if (job_assumes(nj
, nj
->argv
!= NULL
)) {
1792 /* This is the start of our strings. */
1793 char *p
= ((char *)nj
->argv
) + ((j
->argc
+ 1) * sizeof(char *));
1796 for (i
= 0; i
< j
->argc
; i
++) {
1797 (void)strcpy(p
, j
->argv
[i
]);
1799 p
+= (strlen(j
->argv
[i
]) + 1);
1807 /* We ignore global environment variables. */
1808 struct envitem
*ei
= NULL
;
1809 SLIST_FOREACH(ei
, &j
->env
, sle
) {
1810 (void)job_assumes(nj
, envitem_new(nj
, ei
->key
, ei
->value
, false, false));
1813 uuid_unparse(identifier
, val
);
1814 (void)job_assumes(nj
, envitem_new(nj
, LAUNCH_ENV_INSTANCEID
, val
, false, false));
1817 nj
->rootdir
= strdup(j
->rootdir
);
1819 if (j
->workingdir
) {
1820 nj
->workingdir
= strdup(j
->workingdir
);
1823 nj
->username
= strdup(j
->username
);
1826 nj
->groupname
= strdup(j
->groupname
);
1828 /* FIXME: We shouldn't redirect all the output from these jobs to the same
1829 * file. We should uniquify the file names.
1832 nj
->stdinpath
= strdup(j
->stdinpath
);
1834 if (j
->stdoutpath
) {
1835 nj
->stdoutpath
= strdup(j
->stdinpath
);
1837 if (j
->stderrpath
) {
1838 nj
->stderrpath
= strdup(j
->stderrpath
);
1840 if (j
->alt_exc_handler
) {
1841 nj
->alt_exc_handler
= strdup(j
->alt_exc_handler
);
1844 if (j
->seatbelt_profile
) {
1845 nj
->seatbelt_profile
= strdup(j
->seatbelt_profile
);
1850 if (j
->quarantine_data
) {
1851 nj
->quarantine_data
= strdup(j
->quarantine_data
);
1853 nj
->quarantine_data_sz
= j
->quarantine_data_sz
;
1856 size_t sz
= malloc_size(j
->j_binpref
);
1857 nj
->j_binpref
= (cpu_type_t
*)malloc(sz
);
1858 if (job_assumes(nj
, nj
->j_binpref
)) {
1859 memcpy(&nj
->j_binpref
, &j
->j_binpref
, sz
);
1863 /* JetsamPriority is unsupported. */
1865 if (j
->asport
!= MACH_PORT_NULL
) {
1866 (void)job_assumes(nj
, launchd_mport_copy_send(j
->asport
) == KERN_SUCCESS
);
1867 nj
->asport
= j
->asport
;
1870 LIST_INSERT_HEAD(&nj
->mgr
->jobs
, nj
, sle
);
1872 jobmgr_t where2put
= root_jobmgr
;
1873 if (j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
) {
1876 LIST_INSERT_HEAD(&where2put
->label_hash
[hash_label(nj
->label
)], nj
, label_hash_sle
);
1877 LIST_INSERT_HEAD(&j
->subjobs
, nj
, subjob_sle
);
1884 job_new(jobmgr_t jm
, const char *label
, const char *prog
, const char *const *argv
)
1886 const char *const *argv_tmp
= argv
;
1887 char tmp_path
[PATH_MAX
];
1888 char auto_label
[1000];
1889 const char *bn
= NULL
;
1891 size_t minlabel_len
;
1895 launchd_assert(offsetof(struct job_s
, kqjob_callback
) == 0);
1897 if (unlikely(jm
->shutting_down
)) {
1902 if (unlikely(prog
== NULL
&& argv
== NULL
)) {
1907 char *anon_or_legacy
= (label
== AUTO_PICK_ANONYMOUS_LABEL
) ? "anonymous" : "mach_init";
1908 if (unlikely(label
== AUTO_PICK_LEGACY_LABEL
|| label
== AUTO_PICK_ANONYMOUS_LABEL
)) {
1912 strlcpy(tmp_path
, argv
[0], sizeof(tmp_path
));
1913 bn
= basename(tmp_path
); /* prog for auto labels is kp.kp_kproc.p_comm */
1915 snprintf(auto_label
, sizeof(auto_label
), "%s.%s.%s", sizeof(void *) == 8 ? "0xdeadbeeffeedface" : "0xbabecafe", anon_or_legacy
, bn
);
1917 /* This is so we can do gross things later. See NOTE_EXEC for anonymous jobs */
1918 minlabel_len
= strlen(label
) + MAXCOMLEN
;
1920 if (label
== AUTO_PICK_XPC_LABEL
) {
1921 minlabel_len
= snprintf(auto_label
, sizeof(auto_label
), "com.apple.xpc.domain-owner.%s", jm
->owner
);
1923 minlabel_len
= strlen(label
);
1927 j
= calloc(1, sizeof(struct job_s
) + minlabel_len
+ 1);
1929 if (!jobmgr_assumes(jm
, j
!= NULL
)) {
1933 if (unlikely(label
== auto_label
)) {
1934 snprintf((char *)j
->label
, strlen(label
) + 1, "%p.%s.%s", j
, anon_or_legacy
, bn
);
1936 strcpy((char *)j
->label
, (label
== AUTO_PICK_XPC_LABEL
) ? auto_label
: label
);
1938 j
->kqjob_callback
= job_callback
;
1940 j
->min_run_time
= LAUNCHD_MIN_JOB_RUN_TIME
;
1941 j
->timeout
= RUNTIME_ADVISABLE_IDLE_TIMEOUT
;
1942 j
->exit_timeout
= LAUNCHD_DEFAULT_EXIT_TIMEOUT
;
1943 j
->currently_ignored
= true;
1945 j
->checkedin
= true;
1946 j
->jetsam_priority
= -1;
1947 j
->jetsam_memlimit
= -1;
1949 uuid_clear(j
->expected_audit_uuid
);
1952 j
->prog
= strdup(prog
);
1953 if (!job_assumes(j
, j
->prog
!= NULL
)) {
1959 while (*argv_tmp
++) {
1963 for (i
= 0; i
< j
->argc
; i
++) {
1964 cc
+= strlen(argv
[i
]) + 1;
1967 j
->argv
= malloc((j
->argc
+ 1) * sizeof(char *) + cc
);
1969 if (!job_assumes(j
, j
->argv
!= NULL
)) {
1973 co
= ((char *)j
->argv
) + ((j
->argc
+ 1) * sizeof(char *));
1975 for (i
= 0; i
< j
->argc
; i
++) {
1977 strcpy(co
, argv
[i
]);
1978 co
+= strlen(argv
[i
]) + 1;
1983 if (strcmp(j
->label
, "com.apple.WindowServer") == 0) {
1984 j
->has_console
= true;
1987 LIST_INSERT_HEAD(&jm
->jobs
, j
, sle
);
1989 jobmgr_t where2put_label
= root_jobmgr
;
1990 if (j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
) {
1991 where2put_label
= j
->mgr
;
1993 LIST_INSERT_HEAD(&where2put_label
->label_hash
[hash_label(j
->label
)], j
, label_hash_sle
);
1994 uuid_clear(j
->expected_audit_uuid
);
1996 job_log(j
, LOG_DEBUG
, "Conceived");
2009 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
2011 job_new_alias(jobmgr_t jm
, job_t src
)
2014 if (job_find(jm
, src
->label
)) {
2017 j
= calloc(1, sizeof(struct job_s
) + strlen(src
->label
) + 1);
2018 if (jobmgr_assumes(jm
, j
!= NULL
)) {
2019 strcpy((char *)j
->label
, src
->label
);
2020 LIST_INSERT_HEAD(&jm
->jobs
, j
, sle
);
2021 LIST_INSERT_HEAD(&jm
->label_hash
[hash_label(j
->label
)], j
, label_hash_sle
);
2022 /* Bad jump address. The kqueue callback for aliases should never be
2025 j
->kqjob_callback
= (kq_callback
)0xfa1afe1;
2029 struct machservice
*msi
= NULL
;
2030 SLIST_FOREACH(msi
, &src
->machservices
, sle
) {
2031 if (!machservice_new_alias(j
, msi
)) {
2032 jobmgr_log(jm
, LOG_ERR
, "Failed to alias job: %s", src
->label
);
2042 job_log(j
, LOG_DEBUG
, "Aliased service into domain: %s", jm
->name
);
2048 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
2051 job_import(launch_data_t pload
)
2053 job_t j
= jobmgr_import2(root_jobmgr
, pload
);
2055 if (unlikely(j
== NULL
)) {
2059 /* Since jobs are effectively stalled until they get security sessions assigned
2060 * to them, we may wish to reconsider this behavior of calling the job "enabled"
2061 * as far as other jobs with the OtherJobEnabled KeepAlive criterion set.
2063 job_dispatch_curious_jobs(j
);
2064 return job_dispatch(j
, false);
2068 job_import_bulk(launch_data_t pload
)
2070 launch_data_t resp
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
2072 size_t i
, c
= launch_data_array_get_count(pload
);
2074 ja
= alloca(c
* sizeof(job_t
));
2076 for (i
= 0; i
< c
; i
++) {
2077 if ((likely(ja
[i
] = jobmgr_import2(root_jobmgr
, launch_data_array_get_index(pload
, i
)))) && errno
!= ENEEDAUTH
) {
2080 launch_data_array_set_index(resp
, launch_data_new_errno(errno
), i
);
2083 for (i
= 0; i
< c
; i
++) {
2084 if (likely(ja
[i
])) {
2085 job_dispatch_curious_jobs(ja
[i
]);
2086 job_dispatch(ja
[i
], false);
2094 job_import_bool(job_t j
, const char *key
, bool value
)
2096 bool found_key
= false;
2101 if (strcasecmp(key
, LAUNCH_JOBKEY_ABANDONPROCESSGROUP
) == 0) {
2102 j
->abandon_pg
= value
;
2108 if (strcasecmp(key
, LAUNCH_JOBKEY_BEGINTRANSACTIONATSHUTDOWN
) == 0) {
2109 j
->dirty_at_shutdown
= value
;
2115 if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE
) == 0) {
2116 j
->ondemand
= !value
;
2122 if (strcasecmp(key
, LAUNCH_JOBKEY_ONDEMAND
) == 0) {
2123 j
->ondemand
= value
;
2129 if (strcasecmp(key
, LAUNCH_JOBKEY_DEBUG
) == 0) {
2132 } else if (strcasecmp(key
, LAUNCH_JOBKEY_DISABLED
) == 0) {
2133 (void)job_assumes(j
, !value
);
2135 } else if (strcasecmp(key
, LAUNCH_JOBKEY_DISABLEASLR
) == 0) {
2136 j
->disable_aslr
= value
;
2142 if (strcasecmp(key
, LAUNCH_JOBKEY_HOPEFULLYEXITSLAST
) == 0) {
2143 job_log(j
, LOG_INFO
, "%s has been deprecated. Please use the new %s key instead and add EnableTransactions to your launchd.plist.", LAUNCH_JOBKEY_HOPEFULLYEXITSLAST
, LAUNCH_JOBKEY_BEGINTRANSACTIONATSHUTDOWN
);
2144 j
->dirty_at_shutdown
= value
;
2150 if (strcasecmp(key
, LAUNCH_JOBKEY_SESSIONCREATE
) == 0) {
2151 j
->session_create
= value
;
2153 } else if (strcasecmp(key
, LAUNCH_JOBKEY_STARTONMOUNT
) == 0) {
2154 j
->start_on_mount
= value
;
2156 } else if (strcasecmp(key
, LAUNCH_JOBKEY_SERVICEIPC
) == 0) {
2157 /* this only does something on Mac OS X 10.4 "Tiger" */
2159 } else if (strcasecmp(key
, LAUNCH_JOBKEY_SHUTDOWNMONITOR
) == 0) {
2160 if (_s_shutdown_monitor
) {
2161 job_log(j
, LOG_ERR
, "Only one job may monitor shutdown.");
2163 j
->shutdown_monitor
= true;
2164 _s_shutdown_monitor
= j
;
2171 if (strcasecmp(key
, LAUNCH_JOBKEY_LOWPRIORITYIO
) == 0) {
2172 j
->low_pri_io
= value
;
2174 } else if (strcasecmp(key
, LAUNCH_JOBKEY_LAUNCHONLYONCE
) == 0) {
2175 j
->only_once
= value
;
2181 if (strcasecmp(key
, LAUNCH_JOBKEY_MACHEXCEPTIONHANDLER
) == 0) {
2182 j
->internal_exc_handler
= value
;
2184 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MULTIPLEINSTANCES
) == 0) {
2185 j
->multiple_instances
= value
;
2191 if (strcasecmp(key
, LAUNCH_JOBKEY_INITGROUPS
) == 0) {
2192 if (getuid() != 0) {
2193 job_log(j
, LOG_WARNING
, "Ignored this key: %s", key
);
2196 j
->no_init_groups
= !value
;
2198 } else if (strcasecmp(key
, LAUNCH_JOBKEY_IGNOREPROCESSGROUPATSHUTDOWN
) == 0) {
2199 j
->ignore_pg_at_shutdown
= value
;
2205 if (strcasecmp(key
, LAUNCH_JOBKEY_RUNATLOAD
) == 0) {
2207 /* We don't want value == false to change j->start_pending */
2208 j
->start_pending
= true;
2215 if (strcasecmp(key
, LAUNCH_JOBKEY_ENABLEGLOBBING
) == 0) {
2216 j
->globargv
= value
;
2218 } else if (strcasecmp(key
, LAUNCH_JOBKEY_ENABLETRANSACTIONS
) == 0) {
2219 j
->kill_via_shmem
= value
;
2221 } else if (strcasecmp(key
, LAUNCH_JOBKEY_ENTERKERNELDEBUGGERBEFOREKILL
) == 0) {
2222 j
->debug_before_kill
= value
;
2224 } else if (strcasecmp(key
, LAUNCH_JOBKEY_EMBEDDEDPRIVILEGEDISPENSATION
) == 0) {
2225 if (!s_embedded_privileged_job
) {
2226 j
->embedded_special_privileges
= value
;
2227 s_embedded_privileged_job
= j
;
2229 job_log(j
, LOG_ERR
, "Job tried to claim %s after it has already been claimed.", key
);
2232 } else if (strcasecmp(key
, LAUNCH_JOBKEY_EVENTMONITOR
) == 0) {
2233 if (job_assumes(j
, _s_event_monitor
== NULL
)) {
2234 j
->event_monitor
= value
;
2236 _s_event_monitor
= j
;
2239 job_log(j
, LOG_NOTICE
, "Job tried to steal event monitoring responsibility!");
2246 if (strcasecmp(key
, LAUNCH_JOBKEY_WAITFORDEBUGGER
) == 0) {
2247 j
->wait4debugger
= value
;
2253 if (strcasecmp(key
, LAUNCH_JOBKEY_XPCDOMAINBOOTSTRAPPER
) == 0) {
2255 if (_s_xpc_bootstrapper
) {
2256 job_log(j
, LOG_ERR
, "This job tried to steal the XPC domain bootstrapper property from the following job: %s", _s_xpc_bootstrapper
->label
);
2258 _s_xpc_bootstrapper
= j
;
2259 j
->xpc_bootstrapper
= value
;
2262 job_log(j
, LOG_ERR
, "Non-daemon tried to claim XPC bootstrapper property.");
2271 if (unlikely(!found_key
)) {
2272 job_log(j
, LOG_WARNING
, "Unknown key for boolean: %s", key
);
2277 job_import_string(job_t j
, const char *key
, const char *value
)
2279 char **where2put
= NULL
;
2284 if (strcasecmp(key
, LAUNCH_JOBKEY_MACHEXCEPTIONHANDLER
) == 0) {
2285 where2put
= &j
->alt_exc_handler
;
2290 if (strcasecmp(key
, LAUNCH_JOBKEY_PROGRAM
) == 0) {
2292 } else if (strcasecmp(key
, LAUNCH_JOBKEY_POSIXSPAWNTYPE
) == 0) {
2293 if (strcasecmp(value
, LAUNCH_KEY_POSIXSPAWNTYPE_TALAPP
) == 0) {
2294 j
->pstype
= POSIX_SPAWN_OSX_TALAPP_START
;
2295 } else if (strcasecmp(value
, LAUNCH_KEY_POSIXSPAWNTYPE_WIDGET
) == 0) {
2296 j
->pstype
= POSIX_SPAWN_OSX_WIDGET_START
;
2298 #if TARGET_OS_EMBEDDED
2299 else if (strcasecmp(value
, LAUNCH_KEY_POSIXSPAWNTYPE_IOSAPP
) == 0) {
2300 j
->pstype
= POSIX_SPAWN_IOS_APP_START
;
2302 #endif /* TARGET_OS_EMBEDDED */
2304 job_log(j
, LOG_ERR
, "Unknown value for key %s: %s", key
, value
);
2311 if (strcasecmp(key
, LAUNCH_JOBKEY_LABEL
) == 0) {
2313 } else if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADTOHOSTS
) == 0) {
2315 } else if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADFROMHOSTS
) == 0) {
2317 } else if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
) == 0) {
2323 if (strcasecmp(key
, LAUNCH_JOBKEY_ROOTDIRECTORY
) == 0) {
2324 if (getuid() != 0) {
2325 job_log(j
, LOG_WARNING
, "Ignored this key: %s", key
);
2328 where2put
= &j
->rootdir
;
2333 if (strcasecmp(key
, LAUNCH_JOBKEY_WORKINGDIRECTORY
) == 0) {
2334 where2put
= &j
->workingdir
;
2339 if (strcasecmp(key
, LAUNCH_JOBKEY_USERNAME
) == 0) {
2340 if (getuid() != 0) {
2341 job_log(j
, LOG_WARNING
, "Ignored this key: %s", key
);
2343 } else if (strcmp(value
, "root") == 0) {
2346 where2put
= &j
->username
;
2351 if (strcasecmp(key
, LAUNCH_JOBKEY_GROUPNAME
) == 0) {
2352 if (getuid() != 0) {
2353 job_log(j
, LOG_WARNING
, "Ignored this key: %s", key
);
2355 } else if (strcmp(value
, "wheel") == 0) {
2358 where2put
= &j
->groupname
;
2363 if (strcasecmp(key
, LAUNCH_JOBKEY_STANDARDOUTPATH
) == 0) {
2364 where2put
= &j
->stdoutpath
;
2365 } else if (strcasecmp(key
, LAUNCH_JOBKEY_STANDARDERRORPATH
) == 0) {
2366 where2put
= &j
->stderrpath
;
2367 } else if (strcasecmp(key
, LAUNCH_JOBKEY_STANDARDINPATH
) == 0) {
2368 where2put
= &j
->stdinpath
;
2369 j
->stdin_fd
= _fd(open(value
, O_RDONLY
|O_CREAT
|O_NOCTTY
|O_NONBLOCK
, DEFFILEMODE
));
2370 if (job_assumes(j
, j
->stdin_fd
!= -1)) {
2371 /* open() should not block, but regular IO by the job should */
2372 (void)job_assumes(j
, fcntl(j
->stdin_fd
, F_SETFL
, 0) != -1);
2373 /* XXX -- EV_CLEAR should make named pipes happy? */
2374 (void)job_assumes(j
, kevent_mod(j
->stdin_fd
, EVFILT_READ
, EV_ADD
|EV_CLEAR
, 0, 0, j
) != -1);
2379 } else if (strcasecmp(key
, LAUNCH_JOBKEY_SANDBOXPROFILE
) == 0) {
2380 where2put
= &j
->seatbelt_profile
;
2386 if (strcasecmp(key
, LAUNCH_JOBKEY_XPCDOMAIN
) == 0) {
2391 job_log(j
, LOG_WARNING
, "Unknown key for string: %s", key
);
2395 if (likely(where2put
)) {
2396 (void)job_assumes(j
, (*where2put
= strdup(value
)) != NULL
);
2398 /* See rdar://problem/5496612. These two are okay. */
2399 if (strncmp(key
, "SHAuthorizationRight", sizeof("SHAuthorizationRight")) != 0 && strncmp(key
, "ServiceDescription", sizeof("ServiceDescription")) != 0) {
2400 job_log(j
, LOG_WARNING
, "Unknown key: %s", key
);
2406 job_import_integer(job_t j
, const char *key
, long long value
)
2411 if (strcasecmp(key
, LAUNCH_JOBKEY_EXITTIMEOUT
) == 0) {
2412 if (unlikely(value
< 0)) {
2413 job_log(j
, LOG_WARNING
, "%s less than zero. Ignoring.", LAUNCH_JOBKEY_EXITTIMEOUT
);
2414 } else if (unlikely(value
> UINT32_MAX
)) {
2415 job_log(j
, LOG_WARNING
, "%s is too large. Ignoring.", LAUNCH_JOBKEY_EXITTIMEOUT
);
2417 j
->exit_timeout
= (typeof(j
->exit_timeout
)) value
;
2419 } else if (strcasecmp(key
, LAUNCH_JOBKEY_EMBEDDEDMAINTHREADPRIORITY
) == 0) {
2420 j
->main_thread_priority
= value
;
2425 if (strcasecmp(key
, LAUNCH_JOBKEY_JETSAMPRIORITY
) == 0) {
2426 job_log(j
, LOG_WARNING
| LOG_CONSOLE
, "Please change the JetsamPriority key to be in a dictionary named JetsamProperties.");
2428 launch_data_t pri
= launch_data_new_integer(value
);
2429 if (job_assumes(j
, pri
!= NULL
)) {
2430 jetsam_property_setup(pri
, LAUNCH_JOBKEY_JETSAMPRIORITY
, j
);
2431 launch_data_free(pri
);
2436 if (strcasecmp(key
, LAUNCH_JOBKEY_NICE
) == 0) {
2437 if (unlikely(value
< PRIO_MIN
)) {
2438 job_log(j
, LOG_WARNING
, "%s less than %d. Ignoring.", LAUNCH_JOBKEY_NICE
, PRIO_MIN
);
2439 } else if (unlikely(value
> PRIO_MAX
)) {
2440 job_log(j
, LOG_WARNING
, "%s is greater than %d. Ignoring.", LAUNCH_JOBKEY_NICE
, PRIO_MAX
);
2442 j
->nice
= (typeof(j
->nice
)) value
;
2449 if (strcasecmp(key
, LAUNCH_JOBKEY_TIMEOUT
) == 0) {
2450 if (unlikely(value
< 0)) {
2451 job_log(j
, LOG_WARNING
, "%s less than zero. Ignoring.", LAUNCH_JOBKEY_TIMEOUT
);
2452 } else if (unlikely(value
> UINT32_MAX
)) {
2453 job_log(j
, LOG_WARNING
, "%s is too large. Ignoring.", LAUNCH_JOBKEY_TIMEOUT
);
2455 j
->timeout
= (typeof(j
->timeout
)) value
;
2457 } else if (strcasecmp(key
, LAUNCH_JOBKEY_THROTTLEINTERVAL
) == 0) {
2459 job_log(j
, LOG_WARNING
, "%s less than zero. Ignoring.", LAUNCH_JOBKEY_THROTTLEINTERVAL
);
2460 } else if (value
> UINT32_MAX
) {
2461 job_log(j
, LOG_WARNING
, "%s is too large. Ignoring.", LAUNCH_JOBKEY_THROTTLEINTERVAL
);
2463 j
->min_run_time
= (typeof(j
->min_run_time
)) value
;
2469 if (strcasecmp(key
, LAUNCH_JOBKEY_UMASK
) == 0) {
2476 if (strcasecmp(key
, LAUNCH_JOBKEY_STARTINTERVAL
) == 0) {
2477 if (unlikely(value
<= 0)) {
2478 job_log(j
, LOG_WARNING
, "%s is not greater than zero. Ignoring.", LAUNCH_JOBKEY_STARTINTERVAL
);
2479 } else if (unlikely(value
> UINT32_MAX
)) {
2480 job_log(j
, LOG_WARNING
, "%s is too large. Ignoring.", LAUNCH_JOBKEY_STARTINTERVAL
);
2482 runtime_add_weak_ref();
2483 j
->start_interval
= (typeof(j
->start_interval
)) value
;
2485 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->start_interval
, EVFILT_TIMER
, EV_ADD
, NOTE_SECONDS
, j
->start_interval
, j
) != -1);
2488 } else if (strcasecmp(key
, LAUNCH_JOBKEY_SANDBOXFLAGS
) == 0) {
2489 j
->seatbelt_flags
= value
;
2495 job_log(j
, LOG_WARNING
, "Unknown key for integer: %s", key
);
2501 job_import_opaque(job_t j
__attribute__((unused
)),
2502 const char *key
, launch_data_t value
__attribute__((unused
)))
2508 if (strcasecmp(key
, LAUNCH_JOBKEY_QUARANTINEDATA
) == 0) {
2509 size_t tmpsz
= launch_data_get_opaque_size(value
);
2511 if (job_assumes(j
, j
->quarantine_data
= malloc(tmpsz
))) {
2512 memcpy(j
->quarantine_data
, launch_data_get_opaque(value
), tmpsz
);
2513 j
->quarantine_data_sz
= tmpsz
;
2519 if (strcasecmp(key
, LAUNCH_JOBKEY_SECURITYSESSIONUUID
) == 0) {
2520 size_t tmpsz
= launch_data_get_opaque_size(value
);
2521 if (job_assumes(j
, tmpsz
== sizeof(uuid_t
))) {
2522 memcpy(j
->expected_audit_uuid
, launch_data_get_opaque(value
), sizeof(uuid_t
));
2532 policy_setup(launch_data_t obj
, const char *key
, void *context
)
2535 bool found_key
= false;
2540 if (strcasecmp(key
, LAUNCH_JOBPOLICY_DENYCREATINGOTHERJOBS
) == 0) {
2541 j
->deny_job_creation
= launch_data_get_bool(obj
);
2549 if (unlikely(!found_key
)) {
2550 job_log(j
, LOG_WARNING
, "Unknown policy: %s", key
);
2555 job_import_dictionary(job_t j
, const char *key
, launch_data_t value
)
2562 if (strcasecmp(key
, LAUNCH_JOBKEY_POLICIES
) == 0) {
2563 launch_data_dict_iterate(value
, policy_setup
, j
);
2568 if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE
) == 0) {
2569 launch_data_dict_iterate(value
, semaphoreitem_setup
, j
);
2574 if (strcasecmp(key
, LAUNCH_JOBKEY_INETDCOMPATIBILITY
) == 0) {
2575 j
->inetcompat
= true;
2576 j
->abandon_pg
= true;
2577 if ((tmp
= launch_data_dict_lookup(value
, LAUNCH_JOBINETDCOMPATIBILITY_WAIT
))) {
2578 j
->inetcompat_wait
= launch_data_get_bool(tmp
);
2584 if (strcasecmp(key
, LAUNCH_JOBKEY_JETSAMPROPERTIES
) == 0) {
2585 launch_data_dict_iterate(value
, (void (*)(launch_data_t
, const char *, void *))jetsam_property_setup
, j
);
2589 if (strcasecmp(key
, LAUNCH_JOBKEY_ENVIRONMENTVARIABLES
) == 0) {
2590 launch_data_dict_iterate(value
, envitem_setup
, j
);
2595 if (strcasecmp(key
, LAUNCH_JOBKEY_USERENVIRONMENTVARIABLES
) == 0) {
2596 j
->importing_global_env
= true;
2597 launch_data_dict_iterate(value
, envitem_setup
, j
);
2598 j
->importing_global_env
= false;
2603 if (strcasecmp(key
, LAUNCH_JOBKEY_SOCKETS
) == 0) {
2604 launch_data_dict_iterate(value
, socketgroup_setup
, j
);
2605 } else if (strcasecmp(key
, LAUNCH_JOBKEY_STARTCALENDARINTERVAL
) == 0) {
2606 calendarinterval_new_from_obj(j
, value
);
2607 } else if (strcasecmp(key
, LAUNCH_JOBKEY_SOFTRESOURCELIMITS
) == 0) {
2608 launch_data_dict_iterate(value
, limititem_setup
, j
);
2610 } else if (strcasecmp(key
, LAUNCH_JOBKEY_SANDBOXFLAGS
) == 0) {
2611 launch_data_dict_iterate(value
, seatbelt_setup_flags
, j
);
2617 if (strcasecmp(key
, LAUNCH_JOBKEY_HARDRESOURCELIMITS
) == 0) {
2618 j
->importing_hard_limits
= true;
2619 launch_data_dict_iterate(value
, limititem_setup
, j
);
2620 j
->importing_hard_limits
= false;
2625 if (strcasecmp(key
, LAUNCH_JOBKEY_MACHSERVICES
) == 0) {
2626 launch_data_dict_iterate(value
, machservice_setup
, j
);
2631 if (strcasecmp(key
, LAUNCH_JOBKEY_LAUNCHEVENTS
) == 0) {
2632 launch_data_dict_iterate(value
, eventsystem_setup
, j
);
2634 if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADTOHARDWARE
) == 0) {
2637 if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADFROMHARDWARE
) == 0) {
2643 job_log(j
, LOG_WARNING
, "Unknown key for dictionary: %s", key
);
2649 job_import_array(job_t j
, const char *key
, launch_data_t value
)
2651 size_t i
, value_cnt
= launch_data_array_get_count(value
);
2657 if (strcasecmp(key
, LAUNCH_JOBKEY_PROGRAMARGUMENTS
) == 0) {
2663 if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADTOHOSTS
) == 0) {
2665 } else if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADFROMHOSTS
) == 0) {
2667 } else if (strcasecmp(key
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
) == 0) {
2668 job_log(j
, LOG_NOTICE
, "launchctl should have transformed the \"%s\" array to a string", LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
);
2674 if (strcasecmp(key
, LAUNCH_JOBKEY_QUEUEDIRECTORIES
) == 0) {
2675 for (i
= 0; i
< value_cnt
; i
++) {
2676 str
= launch_data_get_string(launch_data_array_get_index(value
, i
));
2677 if (job_assumes(j
, str
!= NULL
)) {
2678 semaphoreitem_new(j
, DIR_NOT_EMPTY
, str
);
2686 if (strcasecmp(key
, LAUNCH_JOBKEY_WATCHPATHS
) == 0) {
2687 for (i
= 0; i
< value_cnt
; i
++) {
2688 str
= launch_data_get_string(launch_data_array_get_index(value
, i
));
2689 if (job_assumes(j
, str
!= NULL
)) {
2690 semaphoreitem_new(j
, PATH_CHANGES
, str
);
2697 if (strcasecmp(key
, LAUNCH_JOBKEY_BONJOURFDS
) == 0) {
2698 socketgroup_setup(value
, LAUNCH_JOBKEY_BONJOURFDS
, j
);
2699 } else if (strcasecmp(key
, LAUNCH_JOBKEY_BINARYORDERPREFERENCE
) == 0) {
2700 if (job_assumes(j
, j
->j_binpref
= malloc(value_cnt
* sizeof(*j
->j_binpref
)))) {
2701 j
->j_binpref_cnt
= value_cnt
;
2702 for (i
= 0; i
< value_cnt
; i
++) {
2703 j
->j_binpref
[i
] = (cpu_type_t
) launch_data_get_integer(launch_data_array_get_index(value
, i
));
2710 if (strcasecmp(key
, LAUNCH_JOBKEY_STARTCALENDARINTERVAL
) == 0) {
2711 for (i
= 0; i
< value_cnt
; i
++) {
2712 calendarinterval_new_from_obj(j
, launch_data_array_get_index(value
, i
));
2717 job_log(j
, LOG_WARNING
, "Unknown key for array: %s", key
);
2723 job_import_keys(launch_data_t obj
, const char *key
, void *context
)
2726 launch_data_type_t kind
;
2728 if (!launchd_assumes(obj
!= NULL
)) {
2732 kind
= launch_data_get_type(obj
);
2735 case LAUNCH_DATA_BOOL
:
2736 job_import_bool(j
, key
, launch_data_get_bool(obj
));
2738 case LAUNCH_DATA_STRING
:
2739 job_import_string(j
, key
, launch_data_get_string(obj
));
2741 case LAUNCH_DATA_INTEGER
:
2742 job_import_integer(j
, key
, launch_data_get_integer(obj
));
2744 case LAUNCH_DATA_DICTIONARY
:
2745 job_import_dictionary(j
, key
, obj
);
2747 case LAUNCH_DATA_ARRAY
:
2748 job_import_array(j
, key
, obj
);
2750 case LAUNCH_DATA_OPAQUE
:
2751 job_import_opaque(j
, key
, obj
);
2754 job_log(j
, LOG_WARNING
, "Unknown value type '%d' for key: %s", kind
, key
);
2760 jobmgr_import2(jobmgr_t jm
, launch_data_t pload
)
2762 launch_data_t tmp
, ldpa
;
2763 const char *label
= NULL
, *prog
= NULL
;
2764 const char **argv
= NULL
;
2767 if (!jobmgr_assumes(jm
, pload
!= NULL
)) {
2772 if (unlikely(launch_data_get_type(pload
) != LAUNCH_DATA_DICTIONARY
)) {
2777 if (unlikely(!(tmp
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_LABEL
)))) {
2782 if (unlikely(launch_data_get_type(tmp
) != LAUNCH_DATA_STRING
)) {
2787 if (unlikely(!(label
= launch_data_get_string(tmp
)))) {
2792 #if TARGET_OS_EMBEDDED
2793 if (unlikely(g_embedded_privileged_action
&& s_embedded_privileged_job
)) {
2794 if (unlikely(!(tmp
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_USERNAME
)))) {
2799 const char *username
= NULL
;
2800 if (likely(tmp
&& launch_data_get_type(tmp
) == LAUNCH_DATA_STRING
)) {
2801 username
= launch_data_get_string(tmp
);
2807 if (!jobmgr_assumes(jm
, s_embedded_privileged_job
->username
!= NULL
&& username
!= NULL
)) {
2812 if (unlikely(strcmp(s_embedded_privileged_job
->username
, username
) != 0)) {
2816 } else if (g_embedded_privileged_action
) {
2822 if ((tmp
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_PROGRAM
)) &&
2823 (launch_data_get_type(tmp
) == LAUNCH_DATA_STRING
)) {
2824 prog
= launch_data_get_string(tmp
);
2828 if ((ldpa
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_PROGRAMARGUMENTS
))) {
2831 if (launch_data_get_type(ldpa
) != LAUNCH_DATA_ARRAY
) {
2836 c
= launch_data_array_get_count(ldpa
);
2838 argv
= alloca((c
+ 1) * sizeof(char *));
2840 for (i
= 0; i
< c
; i
++) {
2841 tmp
= launch_data_array_get_index(ldpa
, i
);
2843 if (launch_data_get_type(tmp
) != LAUNCH_DATA_STRING
) {
2848 argv
[i
] = launch_data_get_string(tmp
);
2855 if (!prog
&& argc
== 0) {
2856 jobmgr_log(jm
, LOG_ERR
, "Job specifies neither Program nor ProgramArguments: %s", label
);
2861 /* Find the requested session. You cannot load services into XPC domains in
2864 launch_data_t session
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE
);
2866 jobmgr_t jmt
= NULL
;
2867 if (launch_data_get_type(session
) == LAUNCH_DATA_STRING
) {
2868 jmt
= jobmgr_find_by_name(jm
, launch_data_get_string(session
));
2870 jobmgr_log(jm
, LOG_ERR
, "Could not find requested session: %s", launch_data_get_string(session
));
2875 jobmgr_log(jm
, LOG_ERR
, "Session type is not a string.");
2884 /* For legacy reasons, we have a global hash of all labels in all job
2885 * managers. So rather than make it a global, we store it in the root job
2886 * manager. But for an XPC domain, we store a local hash of all services in
2889 jobmgr_t where2look
= (jm
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
) ? jm
: root_jobmgr
;
2890 if (unlikely((j
= job_find(where2look
, label
)) != NULL
)) {
2891 if (jm
->xpc_singleton
) {
2892 /* There can (and probably will be) multiple attemtps to import the
2893 * same XPC service from the same framework. This is okay. It's
2894 * treated as a singleton, so just return the existing one so that
2895 * it may be aliased into the requesting process' XPC domain.
2899 /* If we're not a global XPC domain, then it's an error to try
2900 * importing the same job/service multiple times.
2905 } else if (unlikely(!jobmgr_label_test(where2look
, label
))) {
2909 jobmgr_log(jm
, LOG_DEBUG
, "Importing %s.", label
);
2911 if (likely(j
= job_new(jm
, label
, prog
, argv
))) {
2912 launch_data_dict_iterate(pload
, job_import_keys
, j
);
2913 if (!uuid_is_null(j
->expected_audit_uuid
)) {
2914 uuid_string_t uuid_str
;
2915 uuid_unparse(j
->expected_audit_uuid
, uuid_str
);
2916 job_log(j
, LOG_DEBUG
, "Imported job. Waiting for session for UUID %s.", uuid_str
);
2917 LIST_INSERT_HEAD(&s_needing_sessions
, j
, needing_session_sle
);
2920 job_log(j
, LOG_DEBUG
, "No security session specified.");
2921 j
->asport
= MACH_PORT_NULL
;
2924 if (j
->event_monitor
) {
2925 if (job_assumes(j
, LIST_FIRST(&j
->events
) == NULL
)) {
2926 struct machservice
*msi
= NULL
;
2927 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
2928 if (msi
->event_update_port
) {
2933 if (job_assumes(j
, msi
!= NULL
)) {
2934 /* Create our send-once right so we can kick things off. */
2935 (void)job_assumes(j
, launchd_mport_make_send_once(msi
->port
, &_s_event_update_port
) == KERN_SUCCESS
);
2936 if (!LIST_EMPTY(&_s_event_systems
)) {
2941 job_log(j
, LOG_ERR
, "The event monitor job may not have a LaunchEvents dictionary.");
2952 jobmgr_label_test(jobmgr_t jm
, const char *str
)
2956 if (str
[0] == '\0') {
2957 jobmgr_log(jm
, LOG_ERR
, "Empty job labels are not allowed");
2961 for (ptr
= str
; *ptr
; ptr
++) {
2962 if (iscntrl(*ptr
)) {
2963 jobmgr_log(jm
, LOG_ERR
, "ASCII control characters are not allowed in job labels. Index: %td Value: 0x%hhx", ptr
- str
, *ptr
);
2968 if ((strncasecmp(str
, "com.apple.launchd", strlen("com.apple.launchd")) == 0) ||
2969 (strncasecmp(str
, "com.apple.launchctl", strlen("com.apple.launchctl")) == 0)) {
2970 jobmgr_log(jm
, LOG_ERR
, "Job labels are not allowed to use a reserved prefix: %s", str
);
2978 job_find(jobmgr_t jm
, const char *label
)
2986 LIST_FOREACH(ji
, &jm
->label_hash
[hash_label(label
)], label_hash_sle
) {
2987 if (unlikely(ji
->removal_pending
|| ji
->mgr
->shutting_down
)) {
2988 continue; /* 5351245 and 5488633 respectively */
2991 if (strcmp(ji
->label
, label
) == 0) {
3000 /* Should try and consolidate with job_mig_intran2() and jobmgr_find_by_pid(). */
3002 jobmgr_find_by_pid_deep(jobmgr_t jm
, pid_t p
, bool anon_okay
)
3005 LIST_FOREACH(ji
, &jm
->active_jobs
[ACTIVE_JOB_HASH(p
)], pid_hash_sle
) {
3006 if (ji
->p
== p
&& (!ji
->anonymous
|| (ji
->anonymous
&& anon_okay
)) ) {
3011 jobmgr_t jmi
= NULL
;
3012 SLIST_FOREACH(jmi
, &jm
->submgrs
, sle
) {
3013 if ((ji
= jobmgr_find_by_pid_deep(jmi
, p
, anon_okay
))) {
3022 jobmgr_find_by_pid(jobmgr_t jm
, pid_t p
, bool create_anon
)
3026 LIST_FOREACH(ji
, &jm
->active_jobs
[ACTIVE_JOB_HASH(p
)], pid_hash_sle
) {
3032 return create_anon
? job_new_anonymous(jm
, p
) : NULL
;
3036 job_mig_intran2(jobmgr_t jm
, mach_port_t mport
, pid_t upid
)
3041 if (jm
->jm_port
== mport
) {
3042 return jobmgr_find_by_pid(jm
, upid
, true);
3045 SLIST_FOREACH(jmi
, &jm
->submgrs
, sle
) {
3048 if ((jr
= job_mig_intran2(jmi
, mport
, upid
))) {
3053 LIST_FOREACH(ji
, &jm
->jobs
, sle
) {
3054 if (ji
->j_port
== mport
) {
3063 job_mig_intran(mach_port_t p
)
3065 struct ldcred
*ldc
= runtime_get_caller_creds();
3068 jr
= job_mig_intran2(root_jobmgr
, p
, ldc
->pid
);
3070 if (!jobmgr_assumes(root_jobmgr
, jr
!= NULL
)) {
3071 struct proc_bsdshortinfo proc
;
3072 if (proc_pidinfo(ldc
->pid
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
3073 if (errno
!= ESRCH
) {
3074 (void)jobmgr_assumes(root_jobmgr
, errno
== 0);
3076 jobmgr_log(root_jobmgr
, LOG_ERR
, "%s() was confused by PID %u UID %u EUID %u Mach Port 0x%x: %s", __func__
, ldc
->pid
, ldc
->uid
, ldc
->euid
, p
, proc
.pbsi_comm
);
3085 job_find_by_service_port(mach_port_t p
)
3087 struct machservice
*ms
;
3089 LIST_FOREACH(ms
, &port_hash
[HASH_PORT(p
)], port_hash_sle
) {
3090 if (ms
->recv
&& (ms
->port
== p
)) {
3099 job_mig_destructor(job_t j
)
3104 * 'j' can be invalid at this point. We should fix this up after Leopard ships.
3107 if (unlikely(j
&& (j
!= workaround_5477111
) && j
->unload_at_mig_return
)) {
3108 job_log(j
, LOG_NOTICE
, "Unloading PID %u at MIG return.", j
->p
);
3112 workaround_5477111
= NULL
;
3114 calendarinterval_sanity_check();
3118 job_export_all2(jobmgr_t jm
, launch_data_t where
)
3123 SLIST_FOREACH(jmi
, &jm
->submgrs
, sle
) {
3124 job_export_all2(jmi
, where
);
3127 LIST_FOREACH(ji
, &jm
->jobs
, sle
) {
3130 if (jobmgr_assumes(jm
, (tmp
= job_export(ji
)) != NULL
)) {
3131 launch_data_dict_insert(where
, tmp
, ji
->label
);
3137 job_export_all(void)
3139 launch_data_t resp
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
);
3141 if (launchd_assumes(resp
!= NULL
)) {
3142 job_export_all2(root_jobmgr
, resp
);
3149 job_log_stray_pg(job_t j
)
3152 size_t len
= sizeof(pid_t
) * get_kern_max_proc();
3153 int i
= 0, kp_cnt
= 0;
3155 if (!do_apple_internal_logging
) {
3159 runtime_ktrace(RTKT_LAUNCHD_FINDING_STRAY_PG
, j
->p
, 0, 0);
3161 if (!job_assumes(j
, (pids
= malloc(len
)) != NULL
)) {
3164 if (!job_assumes(j
, (kp_cnt
= proc_listpgrppids(j
->p
, pids
, len
)) != -1)) {
3168 for (i
= 0; i
< kp_cnt
; i
++) {
3169 pid_t p_i
= pids
[i
];
3172 } else if (!job_assumes(j
, p_i
!= 0 && p_i
!= 1)) {
3176 struct proc_bsdshortinfo proc
;
3177 if (proc_pidinfo(p_i
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
3178 if (errno
!= ESRCH
) {
3179 job_assumes(j
, errno
== 0);
3184 pid_t pp_i
= proc
.pbsi_ppid
;
3185 const char *z
= (proc
.pbsi_status
== SZOMB
) ? "zombie " : "";
3186 const char *n
= proc
.pbsi_comm
;
3188 job_log(j
, LOG_WARNING
, "Stray %sprocess with PGID equal to this dead job: PID %u PPID %u PGID %u %s", z
, p_i
, pp_i
, proc
.pbsi_pgid
, n
);
3201 bool is_system_bootstrapper
= j
->is_bootstrapper
&& pid1_magic
&& !j
->mgr
->parentmgr
;
3203 job_log(j
, LOG_DEBUG
, "Reaping");
3206 (void)job_assumes(j
, vm_deallocate(mach_task_self(), (vm_address_t
)j
->shmem
, getpagesize()) == 0);
3210 if (unlikely(j
->weird_bootstrap
)) {
3212 job_mig_swap_integer(j
, VPROC_GSK_WEIRD_BOOTSTRAP
, 0, 0, &junk
);
3215 if (j
->log_redirect_fd
&& !j
->legacy_LS_job
) {
3216 job_log_stdouterr(j
); /* one last chance */
3218 if (j
->log_redirect_fd
) {
3219 (void)job_assumes(j
, runtime_close(j
->log_redirect_fd
) != -1);
3220 j
->log_redirect_fd
= 0;
3225 (void)job_assumes(j
, runtime_close(j
->fork_fd
) != -1);
3231 memset(&ru
, 0, sizeof(ru
));
3234 * The job is dead. While the PID/PGID is still known to be
3235 * valid, try to kill abandoned descendant processes.
3237 job_log_stray_pg(j
);
3238 if (!j
->abandon_pg
) {
3239 if (unlikely(runtime_killpg(j
->p
, SIGTERM
) == -1 && errno
!= ESRCH
)) {
3241 job_log(j
, LOG_APPLEONLY
, "Bug: 5487498");
3243 (void)job_assumes(j
, false);
3248 /* We have to work around one of two kernel bugs here. ptrace(3) may
3249 * have abducted the child away from us and reparented it to the tracing
3250 * process. If the process then exits, we still get NOTE_EXIT, but we
3251 * cannot reap it because the kernel may not have restored the true
3252 * parent/child relationship in time.
3254 * See <rdar://problem/5020256>.
3256 * The other bug is if the shutdown monitor has suspended a task and not
3257 * resumed it before exiting. In this case, the kernel will not clean up
3258 * after the shutdown monitor. It will, instead, leave the task
3259 * task suspended and not process any pending signals on the event loop
3262 * There are a variety of other kernel bugs that could prevent a process
3263 * from exiting, usually having to do with faulty hardware or talking to
3264 * misbehaving drivers that mark a thread as uninterruptible and
3265 * deadlock/hang before unmarking it as such. So we have to work around
3268 * See <rdar://problem/9284889&9359725>.
3270 if (j
->workaround9359725
) {
3271 job_log(j
, LOG_NOTICE
, "Simulated exit: <rdar://problem/9359725>");
3272 status
= W_EXITCODE(-1, SIGSEGV
);
3273 memset(&ru
, 0, sizeof(ru
));
3274 } else if (wait4(j
->p
, &status
, 0, &ru
) == -1) {
3275 job_log(j
, LOG_NOTICE
, "Assuming job exited: <rdar://problem/5020256>: %d: %s", errno
, strerror(errno
));
3276 status
= W_EXITCODE(-1, SIGSEGV
);
3277 memset(&ru
, 0, sizeof(ru
));
3281 if (j
->exit_timeout
) {
3282 kevent_mod((uintptr_t)&j
->exit_timeout
, EVFILT_TIMER
, EV_DELETE
, 0, 0, NULL
);
3285 LIST_REMOVE(j
, pid_hash_sle
);
3287 if (j
->sent_signal_time
) {
3288 uint64_t td_sec
, td_usec
, td
= runtime_get_nanoseconds_since(j
->sent_signal_time
);
3290 td_sec
= td
/ NSEC_PER_SEC
;
3291 td_usec
= (td
% NSEC_PER_SEC
) / NSEC_PER_USEC
;
3293 job_log(j
, LOG_DEBUG
, "Exited %llu.%06llu seconds after the first signal was sent", td_sec
, td_usec
);
3296 timeradd(&ru
.ru_utime
, &j
->ru
.ru_utime
, &j
->ru
.ru_utime
);
3297 timeradd(&ru
.ru_stime
, &j
->ru
.ru_stime
, &j
->ru
.ru_stime
);
3298 j
->ru
.ru_maxrss
+= ru
.ru_maxrss
;
3299 j
->ru
.ru_ixrss
+= ru
.ru_ixrss
;
3300 j
->ru
.ru_idrss
+= ru
.ru_idrss
;
3301 j
->ru
.ru_isrss
+= ru
.ru_isrss
;
3302 j
->ru
.ru_minflt
+= ru
.ru_minflt
;
3303 j
->ru
.ru_majflt
+= ru
.ru_majflt
;
3304 j
->ru
.ru_nswap
+= ru
.ru_nswap
;
3305 j
->ru
.ru_inblock
+= ru
.ru_inblock
;
3306 j
->ru
.ru_oublock
+= ru
.ru_oublock
;
3307 j
->ru
.ru_msgsnd
+= ru
.ru_msgsnd
;
3308 j
->ru
.ru_msgrcv
+= ru
.ru_msgrcv
;
3309 j
->ru
.ru_nsignals
+= ru
.ru_nsignals
;
3310 j
->ru
.ru_nvcsw
+= ru
.ru_nvcsw
;
3311 j
->ru
.ru_nivcsw
+= ru
.ru_nivcsw
;
3313 if (WIFEXITED(status
) && WEXITSTATUS(status
) != 0) {
3314 int level
= LOG_WARNING
;
3315 if (!j
->did_exec
&& (j
->fail_cnt
++ % LAUNCHD_LOG_FAILED_EXEC_FREQ
) != 0) {
3319 job_log(j
, level
, "Exited with code: %d", WEXITSTATUS(status
));
3324 if (WIFSIGNALED(status
)) {
3325 int s
= WTERMSIG(status
);
3326 if ((SIGKILL
== s
|| SIGTERM
== s
) && !j
->stopped
) {
3327 job_log(j
, LOG_NOTICE
, "Exited: %s", strsignal(s
));
3328 } else if (!j
->stopped
&& !j
->clean_kill
) {
3330 /* Signals which indicate a crash. */
3337 /* If the kernel has posted NOTE_EXIT and the signal sent to the process was
3338 * SIGTRAP, assume that it's a crash.
3342 job_log(j
, LOG_WARNING
, "Job appears to have crashed: %s", strsignal(s
));
3345 job_log(j
, LOG_WARNING
, "Exited abnormally: %s", strsignal(s
));
3349 if (is_system_bootstrapper
&& j
->crashed
) {
3350 job_log(j
, LOG_ERR
| LOG_CONSOLE
, "The %s bootstrapper has crashed: %s", j
->mgr
->name
, strsignal(s
));
3357 struct machservice
*msi
= NULL
;
3358 if (j
->crashed
|| !(j
->did_exec
|| j
->anonymous
)) {
3359 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
3360 if (j
->crashed
&& !msi
->isActive
&& (msi
->drain_one_on_crash
|| msi
->drain_all_on_crash
)) {
3361 machservice_drain_port(msi
);
3364 if (!j
->did_exec
&& msi
->reset
&& job_assumes(j
, !msi
->isActive
)) {
3365 machservice_resetport(j
, msi
);
3370 /* HACK: Essentially duplicating the logic directly above. But this has
3371 * gotten really hairy, and I don't want to try consolidating it right now.
3373 if (j
->xpc_service
&& !j
->xpcproxy_did_exec
) {
3374 job_log(j
, LOG_ERR
, "XPC Service could not exec(3). Resetting port.");
3375 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
3376 /* Drain the messages but do not reset the port. If xpcproxy could
3377 * not exec(3), then we don't want to continue trying, since there
3378 * is very likely a serious configuration error with the service.
3380 * <rdar://problem/8986802>
3382 machservice_resetport(j
, msi
);
3386 struct suspended_peruser
*spi
= NULL
;
3387 while ((spi
= LIST_FIRST(&j
->suspended_perusers
))) {
3388 job_log(j
, LOG_ERR
, "Job exited before resuming per-user launchd for UID %u. Will forcibly resume.", spi
->j
->mach_uid
);
3389 spi
->j
->peruser_suspend_count
--;
3390 if (spi
->j
->peruser_suspend_count
== 0) {
3391 job_dispatch(spi
->j
, false);
3393 LIST_REMOVE(spi
, sle
);
3397 j
->last_exit_status
= status
;
3399 if (j
->exit_status_dest
) {
3400 errno
= helper_downcall_wait(j
->exit_status_dest
, j
->last_exit_status
);
3401 if (errno
&& errno
!= MACH_SEND_INVALID_DEST
) {
3402 (void)job_assumes(j
, errno
== 0);
3405 j
->exit_status_dest
= MACH_PORT_NULL
;
3408 if (j
->spawn_reply_port
) {
3409 /* If the child never called exec(3), we must send a spawn() reply so
3410 * that the requestor can get exit status from it. If we fail to send
3411 * the reply for some reason, we have to deallocate the exit status port
3414 kern_return_t kr
= job_mig_spawn2_reply(j
->spawn_reply_port
, BOOTSTRAP_SUCCESS
, j
->p
, j
->exit_status_port
);
3416 if (kr
!= MACH_SEND_INVALID_DEST
) {
3418 (void)job_assumes(j
, errno
== KERN_SUCCESS
);
3421 (void)job_assumes(j
, launchd_mport_close_recv(j
->exit_status_port
) == KERN_SUCCESS
);
3424 j
->exit_status_port
= MACH_PORT_NULL
;
3425 j
->spawn_reply_port
= MACH_PORT_NULL
;
3429 total_anon_children
--;
3438 if (j
->has_console
) {
3442 if (j
->shutdown_monitor
) {
3443 job_log(j
, LOG_NOTICE
| LOG_CONSOLE
, "Shutdown monitor has exited.");
3444 _s_shutdown_monitor
= NULL
;
3445 j
->shutdown_monitor
= false;
3448 if (j
->event_monitor
&& !j
->mgr
->shutting_down
) {
3450 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
3451 if (msi
->event_update_port
) {
3455 /* Only do this if we've gotten the port-destroyed notification already.
3456 * If we haven't yet, the port destruction handler will do this.
3458 if (job_assumes(j
, msi
!= NULL
) && !msi
->isActive
) {
3459 if (_s_event_update_port
== MACH_PORT_NULL
) {
3460 (void)job_assumes(j
, launchd_mport_make_send_once(msi
->port
, &_s_event_update_port
) == KERN_SUCCESS
);
3466 if (!j
->anonymous
) {
3467 j
->mgr
->normal_active_cnt
--;
3469 j
->sent_signal_time
= 0;
3470 j
->sent_sigkill
= false;
3471 j
->clean_kill
= false;
3472 j
->sent_kill_via_shmem
= false;
3473 j
->lastlookup
= NULL
;
3474 j
->lastlookup_gennum
= 0;
3479 jobmgr_dispatch_all(jobmgr_t jm
, bool newmounthack
)
3484 if (jm
->shutting_down
) {
3488 SLIST_FOREACH_SAFE(jmi
, &jm
->submgrs
, sle
, jmn
) {
3489 jobmgr_dispatch_all(jmi
, newmounthack
);
3492 LIST_FOREACH_SAFE(ji
, &jm
->jobs
, sle
, jn
) {
3493 if (newmounthack
&& ji
->start_on_mount
) {
3494 ji
->start_pending
= true;
3497 job_dispatch(ji
, false);
3502 job_dispatch_curious_jobs(job_t j
)
3504 job_t ji
= NULL
, jt
= NULL
;
3505 SLIST_FOREACH_SAFE(ji
, &s_curious_jobs
, curious_jobs_sle
, jt
) {
3506 struct semaphoreitem
*si
= NULL
;
3507 SLIST_FOREACH(si
, &ji
->semaphores
, sle
) {
3508 if (!(si
->why
== OTHER_JOB_ENABLED
|| si
->why
== OTHER_JOB_DISABLED
)) {
3512 if (strcmp(si
->what
, j
->label
) == 0) {
3513 job_log(ji
, LOG_DEBUG
, "Dispatching out of interest in \"%s\".", j
->label
);
3515 if (!ji
->removing
) {
3516 job_dispatch(ji
, false);
3518 job_log(ji
, LOG_NOTICE
, "The following job is circularly dependent upon this one: %s", j
->label
);
3521 /* ji could be removed here, so don't do anything with it or its semaphores
3531 job_dispatch(job_t j
, bool kickstart
)
3533 /* Don't dispatch a job if it has no audit session set. */
3534 if (!uuid_is_null(j
->expected_audit_uuid
)) {
3541 #if TARGET_OS_EMBEDDED
3542 if (g_embedded_privileged_action
&& s_embedded_privileged_job
) {
3543 if (!job_assumes(j
, s_embedded_privileged_job
->username
!= NULL
&& j
->username
!= NULL
)) {
3548 if (strcmp(j
->username
, s_embedded_privileged_job
->username
) != 0) {
3552 } else if (g_embedded_privileged_action
) {
3559 * The whole job removal logic needs to be consolidated. The fact that
3560 * a job can be removed from just about anywhere makes it easy to have
3561 * stale pointers left behind somewhere on the stack that might get
3562 * used after the deallocation. In particular, during job iteration.
3564 * This is a classic example. The act of dispatching a job may delete it.
3566 if (!job_active(j
)) {
3567 if (job_useless(j
)) {
3571 if (unlikely(j
->per_user
&& j
->peruser_suspend_count
> 0)) {
3575 if (kickstart
|| job_keepalive(j
)) {
3576 job_log(j
, LOG_DEBUG
, "Starting job (kickstart = %s)", kickstart
? "true" : "false");
3579 job_log(j
, LOG_DEBUG
, "Watching job (kickstart = %s)", kickstart
? "true" : "false");
3585 * Path checking and monitoring is really racy right now.
3586 * We should clean this up post Leopard.
3588 if (job_keepalive(j
)) {
3593 job_log(j
, LOG_DEBUG
, "Tried to dispatch an already active job (%s).", job_active(j
));
3600 job_log_stdouterr2(job_t j
, const char *msg
, ...)
3602 struct runtime_syslog_attr attr
= { j
->label
, j
->label
, j
->mgr
->name
, LOG_NOTICE
, getuid(), j
->p
, j
->p
};
3606 runtime_vsyslog(&attr
, msg
, ap
);
3611 job_log_stdouterr(job_t j
)
3613 char *msg
, *bufindex
, *buf
= malloc(BIG_PIPE_SIZE
+ 1);
3614 bool close_log_redir
= false;
3617 if (!job_assumes(j
, buf
!= NULL
)) {
3623 rsz
= read(j
->log_redirect_fd
, buf
, BIG_PIPE_SIZE
);
3625 if (unlikely(rsz
== 0)) {
3626 job_log(j
, LOG_DEBUG
, "Standard out/error pipe closed");
3627 close_log_redir
= true;
3628 } else if (rsz
== -1) {
3629 if (!job_assumes(j
, errno
== EAGAIN
)) {
3630 close_log_redir
= true;
3635 while ((msg
= strsep(&bufindex
, "\n\r"))) {
3637 job_log_stdouterr2(j
, "%s", msg
);
3644 if (unlikely(close_log_redir
)) {
3645 (void)job_assumes(j
, runtime_close(j
->log_redirect_fd
) != -1);
3646 j
->log_redirect_fd
= 0;
3647 job_dispatch(j
, false);
3654 if (unlikely(!j
->p
|| j
->anonymous
)) {
3658 (void)job_assumes(j
, runtime_kill(j
->p
, SIGKILL
) != -1);
3660 j
->sent_sigkill
= true;
3661 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->exit_timeout
, EVFILT_TIMER
, EV_ADD
|EV_ONESHOT
, NOTE_SECONDS
, LAUNCHD_SIGKILL_TIMER
, j
) != -1);
3663 job_log(j
, LOG_DEBUG
, "Sent SIGKILL signal");
3667 job_open_shutdown_transaction(job_t j
)
3669 if (j
->kill_via_shmem
) {
3671 job_log(j
, LOG_DEBUG
, "Opening shutdown transaction for job.");
3672 (void)__sync_add_and_fetch(&j
->shmem
->vp_shmem_transaction_cnt
, 1);
3674 job_log(j
, LOG_DEBUG
, "Job wants to be dirty at shutdown, but it has not set up shared memory. Treating normally.");
3675 j
->dirty_at_shutdown
= false;
3678 job_log(j
, LOG_DEBUG
, "Job wants to be dirty at shutdown, but it is not Instant Off-compliant. Treating normally.");
3679 j
->dirty_at_shutdown
= false;
3684 job_close_shutdown_transaction(job_t j
)
3686 if (j
->dirty_at_shutdown
) {
3687 job_log(j
, LOG_DEBUG
, "Closing shutdown transaction for job.");
3688 if (__sync_sub_and_fetch(&j
->shmem
->vp_shmem_transaction_cnt
, 1) == -1) {
3689 job_log(j
, LOG_DEBUG
, "Job is now clean. Killing.");
3692 j
->dirty_at_shutdown
= false;
3697 job_log_children_without_exec(job_t j
)
3700 size_t len
= sizeof(pid_t
) * get_kern_max_proc();
3701 int i
= 0, kp_cnt
= 0;
3703 if (!do_apple_internal_logging
|| j
->anonymous
|| j
->per_user
) {
3707 if (!job_assumes(j
, (pids
= malloc(len
)) != NULL
)) {
3710 if (!job_assumes(j
, (kp_cnt
= proc_listchildpids(j
->p
, pids
, len
)) != -1)) {
3714 for (i
= 0; i
< kp_cnt
; i
++) {
3715 struct proc_bsdshortinfo proc
;
3716 if (proc_pidinfo(pids
[i
], PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
3717 if (errno
!= ESRCH
) {
3718 job_assumes(j
, errno
== 0);
3722 if (proc
.pbsi_flags
& P_EXEC
) {
3726 job_log(j
, LOG_DEBUG
, "Called *fork(). Please switch to posix_spawn*(), pthreads or launchd. Child PID %u", pids
[i
]);
3734 job_cleanup_after_tracer(job_t j
)
3737 if (j
->reap_after_trace
) {
3738 job_log(j
, LOG_DEBUG
| LOG_CONSOLE
, "Reaping job now that attached tracer is gone.");
3740 EV_SET(&kev
, j
->p
, 0, 0, NOTE_EXIT
, 0, 0);
3742 /* Fake a kevent to keep our logic consistent. */
3743 job_callback_proc(j
, &kev
);
3745 /* Normally, after getting a EVFILT_PROC event, we do garbage collection
3746 * on the root job manager. To make our fakery complete, we will do garbage
3747 * collection at the beginning of the next run loop cycle (after we're done
3748 * draining the current queue of kevents).
3750 (void)job_assumes(j
, kevent_mod((uintptr_t)&root_jobmgr
->reboot_flags
, EVFILT_TIMER
, EV_ADD
| EV_ONESHOT
, NOTE_NSECONDS
, 1, root_jobmgr
) != -1);
3755 job_callback_proc(job_t j
, struct kevent
*kev
)
3757 bool program_changed
= false;
3758 int fflags
= kev
->fflags
;
3760 job_log(j
, LOG_DEBUG
, "EVFILT_PROC event for job.");
3761 log_kevent_struct(LOG_DEBUG
, kev
, 0);
3763 if (fflags
& NOTE_EXIT
) {
3764 if (j
->p
== (pid_t
)kev
->ident
&& !j
->anonymous
) {
3765 /* Note that the third argument to proc_pidinfo() is a magic argument for
3766 * PROC_PIDT_SHORTBSDINFO. Specifically, passing 1 means "don't fail on a zombie
3769 struct proc_bsdshortinfo proc
;
3770 if (job_assumes(j
, proc_pidinfo(j
->p
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) > 0)) {
3771 if (!job_assumes(j
, (pid_t
)proc
.pbsi_ppid
== getpid())) {
3772 /* Someone has attached to the process with ptrace(). There's a race here.
3773 * If we determine that we are not the parent process and then fail to attach
3774 * a kevent to the parent PID (who is probably using ptrace()), we can take that as an
3775 * indication that the parent exited between sysctl(3) and kevent_mod(). The
3776 * reparenting of the PID should be atomic to us, so in that case, we reap the
3779 * Otherwise, we wait for the death of the parent tracer and then reap, just as we
3780 * would if a job died while we were sampling it at shutdown.
3782 * Note that we foolishly assume that in the process *tree* a node cannot be its
3783 * own parent. Apparently, that is not correct. If this is the case, we forsake
3784 * the process to its own devices. Let it reap itself.
3786 if (!job_assumes(j
, proc
.pbsi_ppid
!= kev
->ident
)) {
3787 job_log(j
, LOG_WARNING
, "Job is its own parent and has (somehow) exited. Leaving it to waste away.");
3790 if (job_assumes(j
, kevent_mod(proc
.pbsi_ppid
, EVFILT_PROC
, EV_ADD
, NOTE_EXIT
, 0, j
) != -1)) {
3791 j
->tracing_pid
= proc
.pbsi_ppid
;
3792 j
->reap_after_trace
= true;
3797 } else if (!j
->anonymous
) {
3798 if (j
->tracing_pid
== (pid_t
)kev
->ident
) {
3799 job_cleanup_after_tracer(j
);
3802 } else if (j
->tracing_pid
&& !j
->reap_after_trace
) {
3803 /* The job exited before our sample completed. */
3804 job_log(j
, LOG_DEBUG
| LOG_CONSOLE
, "Job has exited. Will reap after tracing PID %i exits.", j
->tracing_pid
);
3805 j
->reap_after_trace
= true;
3811 if (fflags
& NOTE_EXEC
) {
3812 program_changed
= true;
3815 struct proc_bsdshortinfo proc
;
3816 if (proc_pidinfo(j
->p
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) > 0) {
3817 char newlabel
[1000];
3819 snprintf(newlabel
, sizeof(newlabel
), "%p.anonymous.%s", j
, proc
.pbsi_comm
);
3821 job_log(j
, LOG_INFO
, "Program changed. Updating the label to: %s", newlabel
);
3822 j
->lastlookup
= NULL
;
3823 j
->lastlookup_gennum
= 0;
3825 LIST_REMOVE(j
, label_hash_sle
);
3826 strcpy((char *)j
->label
, newlabel
);
3828 jobmgr_t where2put
= root_jobmgr
;
3829 if (j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
) {
3832 LIST_INSERT_HEAD(&where2put
->label_hash
[hash_label(j
->label
)], j
, label_hash_sle
);
3833 } else if (errno
!= ESRCH
) {
3834 job_assumes(j
, errno
== 0);
3837 if (j
->spawn_reply_port
) {
3838 errno
= job_mig_spawn2_reply(j
->spawn_reply_port
, BOOTSTRAP_SUCCESS
, j
->p
, j
->exit_status_port
);
3840 if (errno
!= MACH_SEND_INVALID_DEST
) {
3841 (void)job_assumes(j
, errno
== KERN_SUCCESS
);
3843 (void)job_assumes(j
, launchd_mport_close_recv(j
->exit_status_port
) == KERN_SUCCESS
);
3846 j
->spawn_reply_port
= MACH_PORT_NULL
;
3847 j
->exit_status_port
= MACH_PORT_NULL
;
3850 if (j
->xpc_service
&& j
->did_exec
) {
3851 j
->xpcproxy_did_exec
= true;
3855 job_log(j
, LOG_DEBUG
, "Program changed");
3859 if (fflags
& NOTE_FORK
) {
3860 job_log(j
, LOG_DEBUG
, "fork()ed%s", program_changed
? ". For this message only: We don't know whether this event happened before or after execve()." : "");
3861 job_log_children_without_exec(j
);
3864 if (fflags
& NOTE_EXIT
) {
3871 j
= job_dispatch(j
, false);
3877 job_callback_timer(job_t j
, void *ident
)
3880 job_log(j
, LOG_DEBUG
, "j == ident (%p)", ident
);
3881 job_dispatch(j
, true);
3882 } else if (&j
->semaphores
== ident
) {
3883 job_log(j
, LOG_DEBUG
, "&j->semaphores == ident (%p)", ident
);
3884 job_dispatch(j
, false);
3885 } else if (&j
->start_interval
== ident
) {
3886 job_log(j
, LOG_DEBUG
, "&j->start_interval == ident (%p)", ident
);
3887 j
->start_pending
= true;
3888 job_dispatch(j
, false);
3889 } else if (&j
->exit_timeout
== ident
) {
3890 if (!job_assumes(j
, j
->p
!= 0)) {
3894 if (j
->sent_sigkill
) {
3895 uint64_t td
= runtime_get_nanoseconds_since(j
->sent_signal_time
);
3898 td
-= j
->clean_kill
? 0 : j
->exit_timeout
;
3900 job_log(j
, LOG_WARNING
| LOG_CONSOLE
, "Job has not died after being %skilled %llu seconds ago. Simulating exit.", j
->clean_kill
? "cleanly " : "", td
);
3901 j
->workaround9359725
= true;
3903 if (g_trap_sigkill_bugs
) {
3904 job_log(j
, LOG_NOTICE
| LOG_CONSOLE
, "Trapping into kernel debugger. You can continue the machine after it has been debugged, and shutdown will proceed normally.");
3905 (void)job_assumes(j
, host_reboot(mach_host_self(), HOST_REBOOT_DEBUGGER
) == KERN_SUCCESS
);
3908 /* We've simulated the exit, so we have to cancel the kevent for
3909 * this job, otherwise we may get a kevent later down the road that
3910 * has a stale context pointer (if we've removed the job). Or worse,
3911 * it'll corrupt our data structures if the job still exists or the
3912 * allocation was recycled.
3914 * If the failing process had a tracer attached to it, we need to
3915 * remove out NOTE_EXIT for that tracer too, otherwise the same
3916 * thing might happen.
3918 * Note that, if we're not shutting down, this will result in a
3919 * zombie process just hanging around forever. But if the process
3920 * didn't exit after receiving SIGKILL, odds are it would've just
3921 * stuck around forever anyway.
3923 * See <rdar://problem/9481630>.
3925 kevent_mod((uintptr_t)j
->p
, EVFILT_PROC
, EV_DELETE
, 0, 0, NULL
);
3926 if (j
->tracing_pid
) {
3927 kevent_mod((uintptr_t)j
->tracing_pid
, EVFILT_PROC
, EV_DELETE
, 0, 0, NULL
);
3930 struct kevent bogus_exit
;
3931 EV_SET(&bogus_exit
, j
->p
, EVFILT_PROC
, 0, NOTE_EXIT
, 0, 0);
3932 jobmgr_callback(j
->mgr
, &bogus_exit
);
3934 if (unlikely(j
->debug_before_kill
)) {
3935 job_log(j
, LOG_NOTICE
, "Exit timeout elapsed. Entering the kernel debugger");
3936 (void)job_assumes(j
, host_reboot(mach_host_self(), HOST_REBOOT_DEBUGGER
) == KERN_SUCCESS
);
3939 job_log(j
, LOG_WARNING
| LOG_CONSOLE
, "Exit timeout elapsed (%u seconds). Killing", j
->exit_timeout
);
3943 (void)job_assumes(j
, false);
3948 job_callback_read(job_t j
, int ident
)
3950 if (ident
== j
->log_redirect_fd
) {
3951 job_log_stdouterr(j
);
3952 } else if (ident
== j
->stdin_fd
) {
3953 job_dispatch(j
, true);
3955 socketgroup_callback(j
);
3960 jobmgr_reap_bulk(jobmgr_t jm
, struct kevent
*kev
)
3965 SLIST_FOREACH(jmi
, &jm
->submgrs
, sle
) {
3966 jobmgr_reap_bulk(jmi
, kev
);
3969 if ((j
= jobmgr_find_by_pid(jm
, (pid_t
)kev
->ident
, false))) {
3971 job_callback(j
, kev
);
3976 jobmgr_callback(void *obj
, struct kevent
*kev
)
3981 switch (kev
->filter
) {
3983 jobmgr_reap_bulk(jm
, kev
);
3984 root_jobmgr
= jobmgr_do_garbage_collection(root_jobmgr
);
3987 switch (kev
->ident
) {
3989 jobmgr_log(jm
, LOG_DEBUG
, "Got SIGTERM. Shutting down.");
3990 return launchd_shutdown();
3992 return calendarinterval_callback();
3994 fake_shutdown_in_progress
= true;
3995 runtime_setlogmask(LOG_UPTO(LOG_DEBUG
));
3997 runtime_closelog(); /* HACK -- force 'start' time to be set */
4000 int64_t now
= runtime_get_wall_time();
4002 jobmgr_log(jm
, LOG_NOTICE
, "Anticipatory shutdown began at: %lld.%06llu", now
/ USEC_PER_SEC
, now
% USEC_PER_SEC
);
4004 LIST_FOREACH(ji
, &root_jobmgr
->jobs
, sle
) {
4005 if (ji
->per_user
&& ji
->p
) {
4006 (void)job_assumes(ji
, runtime_kill(ji
->p
, SIGUSR2
) != -1);
4010 jobmgr_log(jm
, LOG_NOTICE
, "Anticipatory per-user launchd shutdown");
4015 return (void)jobmgr_assumes(jm
, false);
4019 if (kev
->fflags
& VQ_MOUNT
) {
4020 jobmgr_dispatch_all(jm
, true);
4022 jobmgr_dispatch_all_semaphores(jm
);
4025 if (kev
->ident
== (uintptr_t)&sorted_calendar_events
) {
4026 calendarinterval_callback();
4027 } else if (kev
->ident
== (uintptr_t)jm
) {
4028 jobmgr_log(jm
, LOG_DEBUG
, "Shutdown timer firing.");
4029 jobmgr_still_alive_with_check(jm
);
4030 } else if (kev
->ident
== (uintptr_t)&jm
->reboot_flags
) {
4031 jobmgr_do_garbage_collection(jm
);
4032 } else if (kev
->ident
== (uintptr_t)&g_runtime_busy_time
) {
4033 jobmgr_log(jm
, LOG_DEBUG
, "Idle exit timer fired. Shutting down.");
4034 if (jobmgr_assumes(jm
, runtime_busy_cnt
== 0)) {
4035 return launchd_shutdown();
4040 if (kev
->ident
== (uintptr_t)s_no_hang_fd
) {
4041 int _no_hang_fd
= open("/dev/autofs_nowait", O_EVTONLY
| O_NONBLOCK
);
4042 if (unlikely(_no_hang_fd
!= -1)) {
4043 jobmgr_log(root_jobmgr
, LOG_DEBUG
, "/dev/autofs_nowait has appeared!");
4044 (void)jobmgr_assumes(root_jobmgr
, kevent_mod((uintptr_t)s_no_hang_fd
, EVFILT_VNODE
, EV_DELETE
, 0, 0, NULL
) != -1);
4045 (void)jobmgr_assumes(root_jobmgr
, runtime_close(s_no_hang_fd
) != -1);
4046 s_no_hang_fd
= _fd(_no_hang_fd
);
4048 } else if (pid1_magic
&& g_console
&& kev
->ident
== (uintptr_t)fileno(g_console
)) {
4050 if (launchd_assumes((cfd
= open(_PATH_CONSOLE
, O_WRONLY
| O_NOCTTY
)) != -1)) {
4052 if (!launchd_assumes((g_console
= fdopen(cfd
, "w")) != NULL
)) {
4059 return (void)jobmgr_assumes(jm
, false);
4064 job_callback(void *obj
, struct kevent
*kev
)
4068 job_log(j
, LOG_DEBUG
, "Dispatching kevent callback.");
4070 switch (kev
->filter
) {
4072 return job_callback_proc(j
, kev
);
4074 return job_callback_timer(j
, (void *) kev
->ident
);
4076 return semaphoreitem_callback(j
, kev
);
4078 return job_callback_read(j
, (int) kev
->ident
);
4079 case EVFILT_MACHPORT
:
4080 return (void)job_dispatch(j
, true);
4082 return (void)job_assumes(j
, false);
4096 u_int proc_fflags
= NOTE_EXIT
|NOTE_FORK
|NOTE_EXEC
;
4098 if (!job_assumes(j
, j
->mgr
!= NULL
)) {
4102 if (unlikely(job_active(j
))) {
4103 job_log(j
, LOG_DEBUG
, "Already started");
4108 * Some users adjust the wall-clock and then expect software to not notice.
4109 * Therefore, launchd must use an absolute clock instead of the wall clock
4110 * wherever possible.
4112 td
= runtime_get_nanoseconds_since(j
->start_time
);
4115 if (j
->start_time
&& (td
< j
->min_run_time
) && !j
->legacy_mach_job
&& !j
->inetcompat
) {
4116 time_t respawn_delta
= j
->min_run_time
- (uint32_t)td
;
4119 * We technically should ref-count throttled jobs to prevent idle exit,
4120 * but we're not directly tracking the 'throttled' state at the moment.
4122 int level
= LOG_WARNING
;
4123 if (!j
->did_exec
&& ((j
->fail_cnt
- 1) % LAUNCHD_LOG_FAILED_EXEC_FREQ
) != 0) {
4127 job_log(j
, level
, "Throttling respawn: Will start in %ld seconds", respawn_delta
);
4128 (void)job_assumes(j
, kevent_mod((uintptr_t)j
, EVFILT_TIMER
, EV_ADD
|EV_ONESHOT
, NOTE_SECONDS
, respawn_delta
, j
) != -1);
4133 if (likely(!j
->legacy_mach_job
)) {
4134 sipc
= ((!SLIST_EMPTY(&j
->sockets
) || !SLIST_EMPTY(&j
->machservices
)) && !j
->deny_job_creation
) || j
->embedded_special_privileges
;
4138 (void)job_assumes(j
, socketpair(AF_UNIX
, SOCK_STREAM
, 0, spair
) != -1);
4141 (void)job_assumes(j
, socketpair(AF_UNIX
, SOCK_STREAM
, 0, execspair
) != -1);
4143 if (likely(!j
->legacy_mach_job
) && job_assumes(j
, pipe(oepair
) != -1)) {
4144 j
->log_redirect_fd
= _fd(oepair
[0]);
4145 (void)job_assumes(j
, fcntl(j
->log_redirect_fd
, F_SETFL
, O_NONBLOCK
) != -1);
4146 (void)job_assumes(j
, kevent_mod(j
->log_redirect_fd
, EVFILT_READ
, EV_ADD
, 0, 0, j
) != -1);
4149 switch (c
= runtime_fork(j
->weird_bootstrap
? j
->j_port
: j
->mgr
->jm_port
)) {
4151 job_log_error(j
, LOG_ERR
, "fork() failed, will try again in one second");
4152 (void)job_assumes(j
, kevent_mod((uintptr_t)j
, EVFILT_TIMER
, EV_ADD
|EV_ONESHOT
, NOTE_SECONDS
, 1, j
) != -1);
4155 (void)job_assumes(j
, runtime_close(execspair
[0]) == 0);
4156 (void)job_assumes(j
, runtime_close(execspair
[1]) == 0);
4158 (void)job_assumes(j
, runtime_close(spair
[0]) == 0);
4159 (void)job_assumes(j
, runtime_close(spair
[1]) == 0);
4161 if (likely(!j
->legacy_mach_job
)) {
4162 (void)job_assumes(j
, runtime_close(oepair
[0]) != -1);
4163 (void)job_assumes(j
, runtime_close(oepair
[1]) != -1);
4164 j
->log_redirect_fd
= 0;
4168 if (unlikely(_vproc_post_fork_ping())) {
4169 _exit(EXIT_FAILURE
);
4171 if (!j
->legacy_mach_job
) {
4172 (void)job_assumes(j
, dup2(oepair
[1], STDOUT_FILENO
) != -1);
4173 (void)job_assumes(j
, dup2(oepair
[1], STDERR_FILENO
) != -1);
4174 (void)job_assumes(j
, runtime_close(oepair
[1]) != -1);
4176 (void)job_assumes(j
, runtime_close(execspair
[0]) == 0);
4177 /* wait for our parent to say they've attached a kevent to us */
4178 read(_fd(execspair
[1]), &c
, sizeof(c
));
4181 (void)job_assumes(j
, runtime_close(spair
[0]) == 0);
4182 snprintf(nbuf
, sizeof(nbuf
), "%d", spair
[1]);
4183 setenv(LAUNCHD_TRUSTED_FD_ENV
, nbuf
, 1);
4188 j
->start_time
= runtime_get_opaque_time();
4190 job_log(j
, LOG_DEBUG
, "Started as PID: %u", c
);
4192 j
->did_exec
= false;
4193 j
->xpcproxy_did_exec
= false;
4194 j
->checkedin
= false;
4195 j
->start_pending
= false;
4199 if (j
->needs_kickoff
) {
4200 j
->needs_kickoff
= false;
4202 if (SLIST_EMPTY(&j
->semaphores
)) {
4203 j
->ondemand
= false;
4207 if (j
->has_console
) {
4213 LIST_INSERT_HEAD(&j
->mgr
->active_jobs
[ACTIVE_JOB_HASH(c
)], j
, pid_hash_sle
);
4215 if (likely(!j
->legacy_mach_job
)) {
4216 (void)job_assumes(j
, runtime_close(oepair
[1]) != -1);
4220 j
->mgr
->normal_active_cnt
++;
4221 j
->fork_fd
= _fd(execspair
[0]);
4222 (void)job_assumes(j
, runtime_close(execspair
[1]) == 0);
4224 (void)job_assumes(j
, runtime_close(spair
[1]) == 0);
4225 ipc_open(_fd(spair
[0]), j
);
4227 if (job_assumes(j
, kevent_mod(c
, EVFILT_PROC
, EV_ADD
, proc_fflags
, 0, root_jobmgr
? root_jobmgr
: j
->mgr
) != -1)) {
4233 j
->wait4debugger_oneshot
= false;
4235 struct envitem
*ei
= NULL
, *et
= NULL
;
4236 SLIST_FOREACH_SAFE(ei
, &j
->env
, sle
, et
) {
4238 SLIST_REMOVE(&j
->env
, ei
, envitem
, sle
);
4242 if (likely(!j
->stall_before_exec
)) {
4250 job_start_child(job_t j
)
4252 typeof(posix_spawn
) *psf
;
4253 const char *file2exec
= "/usr/libexec/launchproxy";
4255 posix_spawnattr_t spattr
;
4256 int gflags
= GLOB_NOSORT
|GLOB_NOCHECK
|GLOB_TILDE
|GLOB_DOOFFS
;
4258 short spflags
= POSIX_SPAWN_SETEXEC
;
4259 size_t binpref_out_cnt
= 0;
4262 (void)job_assumes(j
, posix_spawnattr_init(&spattr
) == 0);
4264 job_setup_attributes(j
);
4266 if (unlikely(j
->argv
&& j
->globargv
)) {
4268 for (i
= 0; i
< j
->argc
; i
++) {
4270 gflags
|= GLOB_APPEND
;
4272 if (glob(j
->argv
[i
], gflags
, NULL
, &g
) != 0) {
4273 job_log_error(j
, LOG_ERR
, "glob(\"%s\")", j
->argv
[i
]);
4277 g
.gl_pathv
[0] = (char *)file2exec
;
4278 argv
= (const char **)g
.gl_pathv
;
4279 } else if (likely(j
->argv
)) {
4280 argv
= alloca((j
->argc
+ 2) * sizeof(char *));
4281 argv
[0] = file2exec
;
4282 for (i
= 0; i
< j
->argc
; i
++) {
4283 argv
[i
+ 1] = j
->argv
[i
];
4287 argv
= alloca(3 * sizeof(char *));
4288 argv
[0] = file2exec
;
4293 if (likely(!j
->inetcompat
)) {
4297 if (unlikely(j
->wait4debugger
|| j
->wait4debugger_oneshot
)) {
4298 if (!j
->legacy_LS_job
) {
4299 job_log(j
, LOG_WARNING
, "Spawned and waiting for the debugger to attach before continuing...");
4301 spflags
|= POSIX_SPAWN_START_SUSPENDED
;
4304 if (unlikely(j
->disable_aslr
)) {
4305 spflags
|= _POSIX_SPAWN_DISABLE_ASLR
;
4307 spflags
|= j
->pstype
;
4309 (void)job_assumes(j
, posix_spawnattr_setflags(&spattr
, spflags
) == 0);
4311 if (unlikely(j
->j_binpref_cnt
)) {
4312 (void)job_assumes(j
, posix_spawnattr_setbinpref_np(&spattr
, j
->j_binpref_cnt
, j
->j_binpref
, &binpref_out_cnt
) == 0);
4313 (void)job_assumes(j
, binpref_out_cnt
== j
->j_binpref_cnt
);
4317 if (j
->quarantine_data
) {
4320 if (job_assumes(j
, qp
= qtn_proc_alloc())) {
4321 if (job_assumes(j
, qtn_proc_init_with_data(qp
, j
->quarantine_data
, j
->quarantine_data_sz
) == 0)) {
4322 (void)job_assumes(j
, qtn_proc_apply_to_self(qp
) == 0);
4329 if (j
->seatbelt_profile
) {
4330 char *seatbelt_err_buf
= NULL
;
4332 if (!job_assumes(j
, sandbox_init(j
->seatbelt_profile
, j
->seatbelt_flags
, &seatbelt_err_buf
) != -1)) {
4333 if (seatbelt_err_buf
) {
4334 job_log(j
, LOG_ERR
, "Sandbox failed to init: %s", seatbelt_err_buf
);
4341 psf
= j
->prog
? posix_spawn
: posix_spawnp
;
4343 if (likely(!j
->inetcompat
)) {
4344 file2exec
= j
->prog
? j
->prog
: argv
[0];
4347 errno
= psf(NULL
, file2exec
, NULL
, &spattr
, (char *const *)argv
, environ
);
4348 if (errno
!= EBADARCH
) {
4349 int level
= LOG_ERR
;
4350 if ((j
->fail_cnt
++ % LAUNCHD_LOG_FAILED_EXEC_FREQ
) != 0) {
4353 job_log_error(j
, level
, "posix_spawn(\"%s\", ...)", file2exec
);
4354 errno
= EXIT_FAILURE
;
4364 jobmgr_export_env_from_other_jobs(jobmgr_t jm
, launch_data_t dict
)
4370 if (jm
->parentmgr
) {
4371 jobmgr_export_env_from_other_jobs(jm
->parentmgr
, dict
);
4373 char **tmpenviron
= environ
;
4374 for (; *tmpenviron
; tmpenviron
++) {
4376 launch_data_t s
= launch_data_alloc(LAUNCH_DATA_STRING
);
4377 launch_data_set_string(s
, strchr(*tmpenviron
, '=') + 1);
4378 strncpy(envkey
, *tmpenviron
, sizeof(envkey
));
4379 *(strchr(envkey
, '=')) = '\0';
4380 launch_data_dict_insert(dict
, s
, envkey
);
4384 LIST_FOREACH(ji
, &jm
->jobs
, sle
) {
4385 SLIST_FOREACH(ei
, &ji
->global_env
, sle
) {
4386 if ((tmp
= launch_data_new_string(ei
->value
))) {
4387 launch_data_dict_insert(dict
, tmp
, ei
->key
);
4394 jobmgr_setup_env_from_other_jobs(jobmgr_t jm
)
4399 if (jm
->parentmgr
) {
4400 jobmgr_setup_env_from_other_jobs(jm
->parentmgr
);
4403 LIST_FOREACH(ji
, &jm
->global_env_jobs
, global_env_sle
) {
4404 SLIST_FOREACH(ei
, &ji
->global_env
, sle
) {
4405 setenv(ei
->key
, ei
->value
, 1);
4411 job_log_pids_with_weird_uids(job_t j
)
4413 size_t len
= sizeof(pid_t
) * get_kern_max_proc();
4415 uid_t u
= j
->mach_uid
;
4416 int i
= 0, kp_cnt
= 0;
4418 if (!do_apple_internal_logging
) {
4423 if (!job_assumes(j
, pids
!= NULL
)) {
4427 runtime_ktrace(RTKT_LAUNCHD_FINDING_WEIRD_UIDS
, j
->p
, u
, 0);
4429 /* libproc actually has some serious performance drawbacks when used over sysctl(3) in
4430 * scenarios like this. Whereas sysctl(3) can give us back all the kinfo_proc's in
4431 * one kernel call, libproc requires that we get a list of PIDs we're interested in
4432 * (in this case, all PIDs on the system) and then get a single proc_bsdshortinfo
4433 * struct back in a single call for each one.
4435 * This kind of thing is also more inherently racy than sysctl(3). While sysctl(3)
4436 * returns a snapshot, it returns the whole shebang at once. Any PIDs given to us by
4437 * libproc could go stale before we call proc_pidinfo().
4439 * Note that proc_list*() APIs return the number of PIDs given back, not the number
4440 * of bytes written to the buffer.
4442 if (!job_assumes(j
, (kp_cnt
= proc_listallpids(pids
, len
)) != -1)) {
4446 for (i
= 0; i
< kp_cnt
; i
++) {
4447 struct proc_bsdshortinfo proc
;
4448 /* We perhaps should not log a bug here if we get ESRCH back, due to the race
4451 if (proc_pidinfo(pids
[i
], PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
4452 if (errno
!= ESRCH
) {
4453 job_assumes(j
, errno
== 0);
4458 uid_t i_euid
= proc
.pbsi_uid
;
4459 uid_t i_uid
= proc
.pbsi_ruid
;
4460 uid_t i_svuid
= proc
.pbsi_svuid
;
4461 pid_t i_pid
= pids
[i
];
4463 if (i_euid
!= u
&& i_uid
!= u
&& i_svuid
!= u
) {
4467 job_log(j
, LOG_ERR
, "PID %u \"%s\" has no account to back it! Real/effective/saved UIDs: %u/%u/%u", i_pid
, proc
.pbsi_comm
, i_uid
, i_euid
, i_svuid
);
4469 /* Temporarily disabled due to 5423935 and 4946119. */
4471 /* Ask the accountless process to exit. */
4472 (void)job_assumes(j
, runtime_kill(i_pid
, SIGTERM
) != -1);
4480 static struct passwd
*
4481 job_getpwnam(job_t j
, const char *name
)
4484 * methodology for system daemons
4486 * first lookup user record without any opendirectoryd interaction,
4487 * we don't know what interprocess dependencies might be in flight.
4488 * if that fails, we re-enable opendirectoryd interaction and
4489 * re-issue the lookup. We have to disable the libinfo L1 cache
4490 * otherwise libinfo will return the negative cache entry on the retry
4493 #if !TARGET_OS_EMBEDDED
4494 struct passwd
*pw
= NULL
;
4496 if (pid1_magic
&& j
->mgr
== root_jobmgr
) {
4497 si_search_module_set_flags("ds", 1 /* SEARCH_MODULE_FLAG_DISABLED */);
4498 gL1CacheEnabled
= false;
4500 pw
= getpwnam(name
);
4502 si_search_module_set_flags("ds", 0);
4506 pw
= getpwnam(name
);
4511 return getpwnam(name
);
4515 static struct group
*
4516 job_getgrnam(job_t j
, const char *name
)
4518 #if !TARGET_OS_EMBEDDED
4519 struct group
*gr
= NULL
;
4521 if (pid1_magic
&& j
->mgr
== root_jobmgr
) {
4522 si_search_module_set_flags("ds", 1 /* SEARCH_MODULE_FLAG_DISABLED */);
4523 gL1CacheEnabled
= false;
4525 gr
= getgrnam(name
);
4527 si_search_module_set_flags("ds", 0);
4531 gr
= getgrnam(name
);
4537 return getgrnam(name
);
4542 job_postfork_test_user(job_t j
)
4544 /* This function is all about 5201578 */
4546 const char *home_env_var
= getenv("HOME");
4547 const char *user_env_var
= getenv("USER");
4548 const char *logname_env_var
= getenv("LOGNAME");
4549 uid_t tmp_uid
, local_uid
= getuid();
4550 gid_t tmp_gid
, local_gid
= getgid();
4551 char shellpath
[PATH_MAX
];
4552 char homedir
[PATH_MAX
];
4553 char loginname
[2000];
4557 if (!job_assumes(j
, home_env_var
&& user_env_var
&& logname_env_var
4558 && strcmp(user_env_var
, logname_env_var
) == 0)) {
4562 if ((pwe
= job_getpwnam(j
, user_env_var
)) == NULL
) {
4563 job_log(j
, LOG_ERR
, "The account \"%s\" has been deleted out from under us!", user_env_var
);
4568 * We must copy the results of getpw*().
4570 * Why? Because subsequent API calls may call getpw*() as a part of
4571 * their implementation. Since getpw*() returns a [now thread scoped]
4572 * global, we must therefore cache the results before continuing.
4575 tmp_uid
= pwe
->pw_uid
;
4576 tmp_gid
= pwe
->pw_gid
;
4578 strlcpy(shellpath
, pwe
->pw_shell
, sizeof(shellpath
));
4579 strlcpy(loginname
, pwe
->pw_name
, sizeof(loginname
));
4580 strlcpy(homedir
, pwe
->pw_dir
, sizeof(homedir
));
4582 if (strcmp(loginname
, logname_env_var
) != 0) {
4583 job_log(j
, LOG_ERR
, "The %s environmental variable changed out from under us!", "USER");
4586 if (strcmp(homedir
, home_env_var
) != 0) {
4587 job_log(j
, LOG_ERR
, "The %s environmental variable changed out from under us!", "HOME");
4590 if (local_uid
!= tmp_uid
) {
4591 job_log(j
, LOG_ERR
, "The %cID of the account (%u) changed out from under us (%u)!",
4592 'U', tmp_uid
, local_uid
);
4595 if (local_gid
!= tmp_gid
) {
4596 job_log(j
, LOG_ERR
, "The %cID of the account (%u) changed out from under us (%u)!",
4597 'G', tmp_gid
, local_gid
);
4604 (void)job_assumes(j
, runtime_kill(getppid(), SIGTERM
) != -1);
4605 _exit(EXIT_FAILURE
);
4607 job_log(j
, LOG_WARNING
, "In a future build of the OS, this error will be fatal.");
4612 job_postfork_become_user(job_t j
)
4614 char loginname
[2000];
4615 char tmpdirpath
[PATH_MAX
];
4616 char shellpath
[PATH_MAX
];
4617 char homedir
[PATH_MAX
];
4620 gid_t desired_gid
= -1;
4621 uid_t desired_uid
= -1;
4623 if (getuid() != 0) {
4624 return job_postfork_test_user(j
);
4628 * I contend that having UID == 0 and GID != 0 is of dubious value.
4629 * Nevertheless, this used to work in Tiger. See: 5425348
4631 if (j
->groupname
&& !j
->username
) {
4632 j
->username
= "root";
4636 if ((pwe
= job_getpwnam(j
, j
->username
)) == NULL
) {
4637 job_log(j
, LOG_ERR
, "getpwnam(\"%s\") failed", j
->username
);
4638 _exit(EXIT_FAILURE
);
4640 } else if (j
->mach_uid
) {
4641 if ((pwe
= getpwuid(j
->mach_uid
)) == NULL
) {
4642 job_log(j
, LOG_ERR
, "getpwuid(\"%u\") failed", j
->mach_uid
);
4643 job_log_pids_with_weird_uids(j
);
4644 _exit(EXIT_FAILURE
);
4651 * We must copy the results of getpw*().
4653 * Why? Because subsequent API calls may call getpw*() as a part of
4654 * their implementation. Since getpw*() returns a [now thread scoped]
4655 * global, we must therefore cache the results before continuing.
4658 desired_uid
= pwe
->pw_uid
;
4659 desired_gid
= pwe
->pw_gid
;
4661 strlcpy(shellpath
, pwe
->pw_shell
, sizeof(shellpath
));
4662 strlcpy(loginname
, pwe
->pw_name
, sizeof(loginname
));
4663 strlcpy(homedir
, pwe
->pw_dir
, sizeof(homedir
));
4665 if (unlikely(pwe
->pw_expire
&& time(NULL
) >= pwe
->pw_expire
)) {
4666 job_log(j
, LOG_ERR
, "Expired account");
4667 _exit(EXIT_FAILURE
);
4671 if (unlikely(j
->username
&& strcmp(j
->username
, loginname
) != 0)) {
4672 job_log(j
, LOG_WARNING
, "Suspicious setup: User \"%s\" maps to user: %s", j
->username
, loginname
);
4673 } else if (unlikely(j
->mach_uid
&& (j
->mach_uid
!= desired_uid
))) {
4674 job_log(j
, LOG_WARNING
, "Suspicious setup: UID %u maps to UID %u", j
->mach_uid
, desired_uid
);
4680 if (unlikely((gre
= job_getgrnam(j
, j
->groupname
)) == NULL
)) {
4681 job_log(j
, LOG_ERR
, "getgrnam(\"%s\") failed", j
->groupname
);
4682 _exit(EXIT_FAILURE
);
4685 desired_gid
= gre
->gr_gid
;
4688 if (!job_assumes(j
, setlogin(loginname
) != -1)) {
4689 _exit(EXIT_FAILURE
);
4692 if (!job_assumes(j
, setgid(desired_gid
) != -1)) {
4693 _exit(EXIT_FAILURE
);
4697 * The kernel team and the DirectoryServices team want initgroups()
4698 * called after setgid(). See 4616864 for more information.
4701 if (likely(!j
->no_init_groups
)) {
4703 if (!job_assumes(j
, initgroups(loginname
, desired_gid
) != -1)) {
4704 _exit(EXIT_FAILURE
);
4707 /* Do our own little initgroups(). We do this to guarantee that we're
4708 * always opted into dynamic group resolution in the kernel. initgroups(3)
4709 * does not make this guarantee.
4711 int groups
[NGROUPS
], ngroups
;
4713 /* A failure here isn't fatal, and we'll still get data we can use. */
4714 (void)job_assumes(j
, getgrouplist(j
->username
, desired_gid
, groups
, &ngroups
) != -1);
4716 if (!job_assumes(j
, syscall(SYS_initgroups
, ngroups
, groups
, desired_uid
) != -1)) {
4717 _exit(EXIT_FAILURE
);
4722 if (!job_assumes(j
, setuid(desired_uid
) != -1)) {
4723 _exit(EXIT_FAILURE
);
4726 r
= confstr(_CS_DARWIN_USER_TEMP_DIR
, tmpdirpath
, sizeof(tmpdirpath
));
4728 if (likely(r
> 0 && r
< sizeof(tmpdirpath
))) {
4729 setenv("TMPDIR", tmpdirpath
, 0);
4732 setenv("SHELL", shellpath
, 0);
4733 setenv("HOME", homedir
, 0);
4734 setenv("USER", loginname
, 0);
4735 setenv("LOGNAME", loginname
, 0);
4739 job_setup_attributes(job_t j
)
4741 struct limititem
*li
;
4744 if (unlikely(j
->setnice
)) {
4745 (void)job_assumes(j
, setpriority(PRIO_PROCESS
, 0, j
->nice
) != -1);
4748 SLIST_FOREACH(li
, &j
->limits
, sle
) {
4751 if (!job_assumes(j
, getrlimit(li
->which
, &rl
) != -1)) {
4756 rl
.rlim_max
= li
->lim
.rlim_max
;
4759 rl
.rlim_cur
= li
->lim
.rlim_cur
;
4762 if (setrlimit(li
->which
, &rl
) == -1) {
4763 job_log_error(j
, LOG_WARNING
, "setrlimit()");
4767 if (unlikely(!j
->inetcompat
&& j
->session_create
)) {
4768 launchd_SessionCreate();
4771 if (unlikely(j
->low_pri_io
)) {
4772 (void)job_assumes(j
, setiopolicy_np(IOPOL_TYPE_DISK
, IOPOL_SCOPE_PROCESS
, IOPOL_THROTTLE
) != -1);
4774 if (unlikely(j
->rootdir
)) {
4775 (void)job_assumes(j
, chroot(j
->rootdir
) != -1);
4776 (void)job_assumes(j
, chdir(".") != -1);
4779 job_postfork_become_user(j
);
4781 if (unlikely(j
->workingdir
)) {
4782 (void)job_assumes(j
, chdir(j
->workingdir
) != -1);
4785 if (unlikely(j
->setmask
)) {
4790 (void)job_assumes(j
, dup2(j
->stdin_fd
, STDIN_FILENO
) != -1);
4792 job_setup_fd(j
, STDIN_FILENO
, j
->stdinpath
, O_RDONLY
|O_CREAT
);
4794 job_setup_fd(j
, STDOUT_FILENO
, j
->stdoutpath
, O_WRONLY
|O_CREAT
|O_APPEND
);
4795 job_setup_fd(j
, STDERR_FILENO
, j
->stderrpath
, O_WRONLY
|O_CREAT
|O_APPEND
);
4797 jobmgr_setup_env_from_other_jobs(j
->mgr
);
4799 SLIST_FOREACH(ei
, &j
->env
, sle
) {
4800 setenv(ei
->key
, ei
->value
, 1);
4803 if (do_apple_internal_logging
) {
4804 setenv(LAUNCHD_DO_APPLE_INTERNAL_LOGGING
, "true", 1);
4807 #if !TARGET_OS_EMBEDDED
4808 if (j
->jetsam_properties
) {
4809 (void)job_assumes(j
, proc_setpcontrol(PROC_SETPC_TERMINATE
) == 0);
4813 #if TARGET_OS_EMBEDDED
4814 if (j
->main_thread_priority
!= 0) {
4815 struct sched_param params
;
4816 bzero(¶ms
, sizeof(params
));
4817 params
.sched_priority
= j
->main_thread_priority
;
4818 (void)job_assumes(j
, pthread_setschedparam(pthread_self(), SCHED_OTHER
, ¶ms
) != -1);
4823 * We'd like to call setsid() unconditionally, but we have reason to
4824 * believe that prevents launchd from being able to send signals to
4825 * setuid children. We'll settle for process-groups.
4827 if (getppid() != 1) {
4828 (void)job_assumes(j
, setpgid(0, 0) != -1);
4830 (void)job_assumes(j
, setsid() != -1);
4835 job_setup_fd(job_t j
, int target_fd
, const char *path
, int flags
)
4843 if ((fd
= open(path
, flags
|O_NOCTTY
, DEFFILEMODE
)) == -1) {
4844 job_log_error(j
, LOG_WARNING
, "open(\"%s\", ...)", path
);
4848 (void)job_assumes(j
, dup2(fd
, target_fd
) != -1);
4849 (void)job_assumes(j
, runtime_close(fd
) == 0);
4853 dir_has_files(job_t j
, const char *path
)
4855 DIR *dd
= opendir(path
);
4859 if (unlikely(!dd
)) {
4863 while ((de
= readdir(dd
))) {
4864 if (strcmp(de
->d_name
, ".") && strcmp(de
->d_name
, "..")) {
4870 (void)job_assumes(j
, closedir(dd
) == 0);
4875 calendarinterval_setalarm(job_t j
, struct calendarinterval
*ci
)
4877 struct calendarinterval
*ci_iter
, *ci_prev
= NULL
;
4878 time_t later
, head_later
;
4880 later
= cronemu(ci
->when
.tm_mon
, ci
->when
.tm_mday
, ci
->when
.tm_hour
, ci
->when
.tm_min
);
4882 if (ci
->when
.tm_wday
!= -1) {
4883 time_t otherlater
= cronemu_wday(ci
->when
.tm_wday
, ci
->when
.tm_hour
, ci
->when
.tm_min
);
4885 if (ci
->when
.tm_mday
== -1) {
4888 later
= later
< otherlater
? later
: otherlater
;
4892 ci
->when_next
= later
;
4894 LIST_FOREACH(ci_iter
, &sorted_calendar_events
, global_sle
) {
4895 if (ci
->when_next
< ci_iter
->when_next
) {
4896 LIST_INSERT_BEFORE(ci_iter
, ci
, global_sle
);
4903 if (ci_iter
== NULL
) {
4904 /* ci must want to fire after every other timer, or there are no timers */
4906 if (LIST_EMPTY(&sorted_calendar_events
)) {
4907 LIST_INSERT_HEAD(&sorted_calendar_events
, ci
, global_sle
);
4909 LIST_INSERT_AFTER(ci_prev
, ci
, global_sle
);
4913 head_later
= LIST_FIRST(&sorted_calendar_events
)->when_next
;
4915 if (job_assumes(j
, kevent_mod((uintptr_t)&sorted_calendar_events
, EVFILT_TIMER
, EV_ADD
, NOTE_ABSOLUTE
|NOTE_SECONDS
, head_later
, root_jobmgr
) != -1)) {
4916 char time_string
[100];
4917 size_t time_string_len
;
4919 ctime_r(&later
, time_string
);
4920 time_string_len
= strlen(time_string
);
4922 if (likely(time_string_len
&& time_string
[time_string_len
- 1] == '\n')) {
4923 time_string
[time_string_len
- 1] = '\0';
4926 job_log(j
, LOG_INFO
, "Scheduled to run again at %s", time_string
);
4931 extract_rcsid_substr(const char *i
, char *o
, size_t osz
)
4933 char *rcs_rev_tmp
= strchr(i
, ' ');
4938 strlcpy(o
, rcs_rev_tmp
+ 1, osz
);
4939 rcs_rev_tmp
= strchr(o
, ' ');
4941 *rcs_rev_tmp
= '\0';
4947 jobmgr_log_bug(jobmgr_t jm
, unsigned int line
)
4949 static const char *file
;
4950 int saved_errno
= errno
;
4953 runtime_ktrace1(RTKT_LAUNCHD_BUG
);
4955 extract_rcsid_substr(__rcs_file_version__
, buf
, sizeof(buf
));
4958 file
= strrchr(__FILE__
, '/');
4966 /* the only time 'jm' should not be set is if setting up the first bootstrap fails for some reason */
4968 jobmgr_log(jm
, LOG_NOTICE
, "Bug: %s:%u (%s):%u", file
, line
, buf
, saved_errno
);
4970 runtime_syslog(LOG_NOTICE
, "Bug: %s:%u (%s):%u", file
, line
, buf
, saved_errno
);
4975 job_log_bug(job_t j
, unsigned int line
)
4977 static const char *file
;
4978 int saved_errno
= errno
;
4981 runtime_ktrace1(RTKT_LAUNCHD_BUG
);
4983 extract_rcsid_substr(__rcs_file_version__
, buf
, sizeof(buf
));
4986 file
= strrchr(__FILE__
, '/');
4995 job_log(j
, LOG_NOTICE
, "Bug: %s:%u (%s):%u", file
, line
, buf
, saved_errno
);
4997 runtime_syslog(LOG_NOTICE
, "Bug: %s:%u (%s):%u", file
, line
, buf
, saved_errno
);
5002 job_logv(job_t j
, int pri
, int err
, const char *msg
, va_list ap
)
5004 const char *label2use
= j
? j
->label
: "com.apple.launchd.NULL";
5005 const char *mgr2use
= j
? j
->mgr
->name
: "NULL";
5006 struct runtime_syslog_attr attr
= { g_my_label
, label2use
, mgr2use
, pri
, getuid(), getpid(), j
? j
->p
: 0 };
5012 * Hack: If bootstrap_port is set, we must be on the child side of a
5013 * fork(), but before the exec*(). Let's route the log message back to
5016 if (bootstrap_port
) {
5017 return _vproc_logv(pri
, err
, msg
, ap
);
5020 newmsgsz
= strlen(msg
) + 200;
5021 newmsg
= alloca(newmsgsz
);
5024 #if !TARGET_OS_EMBEDDED
5025 snprintf(newmsg
, newmsgsz
, "%s: %s", msg
, strerror(err
));
5027 snprintf(newmsg
, newmsgsz
, "(%s) %s: %s", label2use
, msg
, strerror(err
));
5030 #if !TARGET_OS_EMBEDDED
5031 snprintf(newmsg
, newmsgsz
, "%s", msg
);
5033 snprintf(newmsg
, newmsgsz
, "(%s) %s", label2use
, msg
);
5037 if (j
&& unlikely(j
->debug
)) {
5038 oldmask
= setlogmask(LOG_UPTO(LOG_DEBUG
));
5041 runtime_vsyslog(&attr
, newmsg
, ap
);
5043 if (j
&& unlikely(j
->debug
)) {
5044 setlogmask(oldmask
);
5049 job_log_error(job_t j
, int pri
, const char *msg
, ...)
5054 job_logv(j
, pri
, errno
, msg
, ap
);
5059 job_log(job_t j
, int pri
, const char *msg
, ...)
5064 job_logv(j
, pri
, 0, msg
, ap
);
5070 jobmgr_log_error(jobmgr_t jm
, int pri
, const char *msg
, ...)
5075 jobmgr_logv(jm
, pri
, errno
, msg
, ap
);
5081 jobmgr_log(jobmgr_t jm
, int pri
, const char *msg
, ...)
5086 jobmgr_logv(jm
, pri
, 0, msg
, ap
);
5091 jobmgr_logv(jobmgr_t jm
, int pri
, int err
, const char *msg
, va_list ap
)
5095 size_t i
, o
, jmname_len
= strlen(jm
->name
), newmsgsz
;
5097 newname
= alloca((jmname_len
+ 1) * 2);
5098 newmsgsz
= (jmname_len
+ 1) * 2 + strlen(msg
) + 100;
5099 newmsg
= alloca(newmsgsz
);
5101 for (i
= 0, o
= 0; i
< jmname_len
; i
++, o
++) {
5102 if (jm
->name
[i
] == '%') {
5106 newname
[o
] = jm
->name
[i
];
5111 snprintf(newmsg
, newmsgsz
, "%s: %s: %s", newname
, msg
, strerror(err
));
5113 snprintf(newmsg
, newmsgsz
, "%s: %s", newname
, msg
);
5116 if (jm
->parentmgr
) {
5117 jobmgr_logv(jm
->parentmgr
, pri
, 0, newmsg
, ap
);
5119 struct runtime_syslog_attr attr
= { g_my_label
, g_my_label
, jm
->name
, pri
, getuid(), getpid(), getpid() };
5121 runtime_vsyslog(&attr
, newmsg
, ap
);
5126 semaphoreitem_ignore(job_t j
, struct semaphoreitem
*si
)
5129 job_log(j
, LOG_DEBUG
, "Ignoring Vnode: %d", si
->fd
);
5130 (void)job_assumes(j
, kevent_mod(si
->fd
, EVFILT_VNODE
, EV_DELETE
, 0, 0, NULL
) != -1);
5135 semaphoreitem_watch(job_t j
, struct semaphoreitem
*si
)
5137 char *parentdir
, tmp_path
[PATH_MAX
];
5138 int saved_errno
= 0;
5139 int fflags
= NOTE_DELETE
|NOTE_RENAME
;
5144 fflags
|= NOTE_ATTRIB
|NOTE_LINK
;
5147 fflags
|= NOTE_REVOKE
|NOTE_EXTEND
|NOTE_WRITE
;
5155 /* dirname() may modify tmp_path */
5156 strlcpy(tmp_path
, si
->what
, sizeof(tmp_path
));
5158 if (!job_assumes(j
, (parentdir
= dirname(tmp_path
)))) {
5162 /* See 5321044 for why we do the do-while loop and 5415523 for why ENOENT is checked */
5166 if (stat(si
->what
, &sb
) == 0) {
5167 /* If we're watching a character or block device, only watch the parent directory.
5168 * See rdar://problem/6489900 for the gory details. Basically, holding an open file
5169 * descriptor to a devnode could end up (a) blocking us on open(2) until someone else
5170 * open(2)s the file (like a character device that waits for a carrier signal) or
5171 * (b) preventing other processes from obtaining an exclusive lock on the file, even
5172 * though we're opening it with O_EVTONLY.
5174 * The main point of contention is that O_EVTONLY doesn't actually mean "event only".
5175 * It means "Don't prevent unmounts of this descriptor's volume". We work around this
5176 * for dev nodes by only watching the parent directory and stat(2)ing our desired file
5177 * each time the parent changes to see if it appeared or disappeared.
5179 if (S_ISREG(sb
.st_mode
) || S_ISDIR(sb
.st_mode
)) {
5180 si
->fd
= _fd(open(si
->what
, O_EVTONLY
| O_NOCTTY
| O_NONBLOCK
));
5185 si
->watching_parent
= job_assumes(j
, (si
->fd
= _fd(open(parentdir
, O_EVTONLY
| O_NOCTTY
| O_NONBLOCK
))) != -1);
5187 si
->watching_parent
= false;
5192 return job_log_error(j
, LOG_ERR
, "Path monitoring failed on \"%s\"", si
->what
);
5195 job_log(j
, LOG_DEBUG
, "Watching %svnode (%s): %d", si
->watching_parent
? "parent ": "", si
->what
, si
->fd
);
5197 if (kevent_mod(si
->fd
, EVFILT_VNODE
, EV_ADD
, fflags
, 0, j
) == -1) {
5198 saved_errno
= errno
;
5200 * The FD can be revoked between the open() and kevent().
5201 * This is similar to the inability for kevents to be
5202 * attached to short lived zombie processes after fork()
5203 * but before kevent().
5205 (void)job_assumes(j
, runtime_close(si
->fd
) == 0);
5208 } while (unlikely((si
->fd
== -1) && (saved_errno
== ENOENT
)));
5210 if (saved_errno
== ENOTSUP
) {
5212 * 3524219 NFS needs kqueue support
5213 * 4124079 VFS needs generic kqueue support
5214 * 5226811 EVFILT: Launchd EVFILT_VNODE doesn't work on /dev
5216 job_log(j
, LOG_DEBUG
, "Falling back to polling for path: %s", si
->what
);
5218 if (!j
->poll_for_vfs_changes
) {
5219 j
->poll_for_vfs_changes
= true;
5220 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->semaphores
, EVFILT_TIMER
, EV_ADD
, NOTE_SECONDS
, 3, j
) != -1);
5226 semaphoreitem_callback(job_t j
, struct kevent
*kev
)
5228 char invalidation_reason
[100] = "";
5229 struct semaphoreitem
*si
;
5231 SLIST_FOREACH(si
, &j
->semaphores
, sle
) {
5237 job_log(j
, LOG_DEBUG
, "P%s changed (%u): %s", si
->watching_parent
? "arent path" : "ath", si
->why
, si
->what
);
5243 if (si
->fd
== (int)kev
->ident
) {
5248 if (!job_assumes(j
, si
!= NULL
)) {
5252 if (NOTE_DELETE
& kev
->fflags
) {
5253 strcat(invalidation_reason
, "deleted");
5256 if (NOTE_RENAME
& kev
->fflags
) {
5257 if (invalidation_reason
[0]) {
5258 strcat(invalidation_reason
, "/renamed");
5260 strcat(invalidation_reason
, "renamed");
5264 if (NOTE_REVOKE
& kev
->fflags
) {
5265 if (invalidation_reason
[0]) {
5266 strcat(invalidation_reason
, "/revoked");
5268 strcat(invalidation_reason
, "revoked");
5272 if (invalidation_reason
[0]) {
5273 job_log(j
, LOG_DEBUG
, "Path %s: %s", invalidation_reason
, si
->what
);
5274 (void)job_assumes(j
, runtime_close(si
->fd
) == 0);
5275 si
->fd
= -1; /* this will get fixed in semaphoreitem_watch() */
5278 if (!si
->watching_parent
) {
5279 if (si
->why
== PATH_CHANGES
) {
5280 j
->start_pending
= true;
5282 semaphoreitem_watch(j
, si
);
5284 } else { /* Something happened to the parent directory. See if our target file appeared. */
5285 if (!invalidation_reason
[0]) {
5286 (void)job_assumes(j
, runtime_close(si
->fd
) == 0);
5287 si
->fd
= -1; /* this will get fixed in semaphoreitem_watch() */
5288 semaphoreitem_watch(j
, si
);
5290 /* Need to think about what should happen if the parent directory goes invalid. */
5293 job_dispatch(j
, false);
5296 struct cal_dict_walk
{
5302 calendarinterval_new_from_obj_dict_walk(launch_data_t obj
, const char *key
, void *context
)
5304 struct cal_dict_walk
*cdw
= context
;
5305 struct tm
*tmptm
= &cdw
->tmptm
;
5309 if (unlikely(LAUNCH_DATA_INTEGER
!= launch_data_get_type(obj
))) {
5310 /* hack to let caller know something went wrong */
5315 val
= launch_data_get_integer(obj
);
5318 job_log(j
, LOG_WARNING
, "The interval for key \"%s\" is less than zero.", key
);
5319 } else if (strcasecmp(key
, LAUNCH_JOBKEY_CAL_MINUTE
) == 0) {
5321 job_log(j
, LOG_WARNING
, "The interval for key \"%s\" is not between 0 and 59 (inclusive).", key
);
5324 tmptm
->tm_min
= (typeof(tmptm
->tm_min
)) val
;
5326 } else if (strcasecmp(key
, LAUNCH_JOBKEY_CAL_HOUR
) == 0) {
5328 job_log(j
, LOG_WARNING
, "The interval for key \"%s\" is not between 0 and 23 (inclusive).", key
);
5331 tmptm
->tm_hour
= (typeof(tmptm
->tm_hour
)) val
;
5333 } else if (strcasecmp(key
, LAUNCH_JOBKEY_CAL_DAY
) == 0) {
5334 if (val
< 1 || val
> 31) {
5335 job_log(j
, LOG_WARNING
, "The interval for key \"%s\" is not between 1 and 31 (inclusive).", key
);
5338 tmptm
->tm_mday
= (typeof(tmptm
->tm_mday
)) val
;
5340 } else if (strcasecmp(key
, LAUNCH_JOBKEY_CAL_WEEKDAY
) == 0) {
5342 job_log(j
, LOG_WARNING
, "The interval for key \"%s\" is not between 0 and 7 (inclusive).", key
);
5345 tmptm
->tm_wday
= (typeof(tmptm
->tm_wday
)) val
;
5347 } else if (strcasecmp(key
, LAUNCH_JOBKEY_CAL_MONTH
) == 0) {
5349 job_log(j
, LOG_WARNING
, "The interval for key \"%s\" is not between 0 and 12 (inclusive).", key
);
5352 tmptm
->tm_mon
= (typeof(tmptm
->tm_mon
)) val
;
5353 tmptm
->tm_mon
-= 1; /* 4798263 cron compatibility */
5359 calendarinterval_new_from_obj(job_t j
, launch_data_t obj
)
5361 struct cal_dict_walk cdw
;
5364 memset(&cdw
.tmptm
, 0, sizeof(0));
5366 cdw
.tmptm
.tm_min
= -1;
5367 cdw
.tmptm
.tm_hour
= -1;
5368 cdw
.tmptm
.tm_mday
= -1;
5369 cdw
.tmptm
.tm_wday
= -1;
5370 cdw
.tmptm
.tm_mon
= -1;
5372 if (!job_assumes(j
, obj
!= NULL
)) {
5376 if (unlikely(LAUNCH_DATA_DICTIONARY
!= launch_data_get_type(obj
))) {
5380 launch_data_dict_iterate(obj
, calendarinterval_new_from_obj_dict_walk
, &cdw
);
5382 if (unlikely(cdw
.tmptm
.tm_sec
== -1)) {
5386 return calendarinterval_new(j
, &cdw
.tmptm
);
5390 calendarinterval_new(job_t j
, struct tm
*w
)
5392 struct calendarinterval
*ci
= calloc(1, sizeof(struct calendarinterval
));
5394 if (!job_assumes(j
, ci
!= NULL
)) {
5401 SLIST_INSERT_HEAD(&j
->cal_intervals
, ci
, sle
);
5403 calendarinterval_setalarm(j
, ci
);
5405 runtime_add_weak_ref();
5411 calendarinterval_delete(job_t j
, struct calendarinterval
*ci
)
5413 SLIST_REMOVE(&j
->cal_intervals
, ci
, calendarinterval
, sle
);
5414 LIST_REMOVE(ci
, global_sle
);
5418 runtime_del_weak_ref();
5422 calendarinterval_sanity_check(void)
5424 struct calendarinterval
*ci
= LIST_FIRST(&sorted_calendar_events
);
5425 time_t now
= time(NULL
);
5427 if (unlikely(ci
&& (ci
->when_next
< now
))) {
5428 (void)jobmgr_assumes(root_jobmgr
, raise(SIGUSR1
) != -1);
5433 calendarinterval_callback(void)
5435 struct calendarinterval
*ci
, *ci_next
;
5436 time_t now
= time(NULL
);
5438 LIST_FOREACH_SAFE(ci
, &sorted_calendar_events
, global_sle
, ci_next
) {
5441 if (ci
->when_next
> now
) {
5445 LIST_REMOVE(ci
, global_sle
);
5446 calendarinterval_setalarm(j
, ci
);
5448 j
->start_pending
= true;
5449 job_dispatch(j
, false);
5454 socketgroup_new(job_t j
, const char *name
, int *fds
, size_t fd_cnt
, bool junkfds
)
5456 struct socketgroup
*sg
= calloc(1, sizeof(struct socketgroup
) + strlen(name
) + 1);
5458 if (!job_assumes(j
, sg
!= NULL
)) {
5462 sg
->fds
= calloc(1, fd_cnt
* sizeof(int));
5463 sg
->fd_cnt
= fd_cnt
;
5464 sg
->junkfds
= junkfds
;
5466 if (!job_assumes(j
, sg
->fds
!= NULL
)) {
5471 memcpy(sg
->fds
, fds
, fd_cnt
* sizeof(int));
5472 strcpy(sg
->name_init
, name
);
5474 SLIST_INSERT_HEAD(&j
->sockets
, sg
, sle
);
5476 runtime_add_weak_ref();
5482 socketgroup_delete(job_t j
, struct socketgroup
*sg
)
5486 for (i
= 0; i
< sg
->fd_cnt
; i
++) {
5488 struct sockaddr_storage ss
;
5489 struct sockaddr_un
*sun
= (struct sockaddr_un
*)&ss
;
5490 socklen_t ss_len
= sizeof(ss
);
5493 if (job_assumes(j
, getsockname(sg
->fds
[i
], (struct sockaddr
*)&ss
, &ss_len
) != -1)
5494 && job_assumes(j
, ss_len
> 0) && (ss
.ss_family
== AF_UNIX
)) {
5495 (void)job_assumes(j
, unlink(sun
->sun_path
) != -1);
5496 /* We might conditionally need to delete a directory here */
5499 (void)job_assumes(j
, runtime_close(sg
->fds
[i
]) != -1);
5502 SLIST_REMOVE(&j
->sockets
, sg
, socketgroup
, sle
);
5507 runtime_del_weak_ref();
5511 socketgroup_kevent_mod(job_t j
, struct socketgroup
*sg
, bool do_add
)
5513 struct kevent kev
[sg
->fd_cnt
];
5515 unsigned int i
, buf_off
= 0;
5517 if (unlikely(sg
->junkfds
)) {
5521 for (i
= 0; i
< sg
->fd_cnt
; i
++) {
5522 EV_SET(&kev
[i
], sg
->fds
[i
], EVFILT_READ
, do_add
? EV_ADD
: EV_DELETE
, 0, 0, j
);
5523 buf_off
+= snprintf(buf
+ buf_off
, sizeof(buf
) - buf_off
, " %d", sg
->fds
[i
]);
5526 job_log(j
, LOG_DEBUG
, "%s Sockets:%s", do_add
? "Watching" : "Ignoring", buf
);
5528 (void)job_assumes(j
, kevent_bulk_mod(kev
, sg
->fd_cnt
) != -1);
5530 for (i
= 0; i
< sg
->fd_cnt
; i
++) {
5531 (void)job_assumes(j
, kev
[i
].flags
& EV_ERROR
);
5532 errno
= (typeof(errno
)) kev
[i
].data
;
5533 (void)job_assumes(j
, kev
[i
].data
== 0);
5538 socketgroup_ignore(job_t j
, struct socketgroup
*sg
)
5540 socketgroup_kevent_mod(j
, sg
, false);
5544 socketgroup_watch(job_t j
, struct socketgroup
*sg
)
5546 socketgroup_kevent_mod(j
, sg
, true);
5550 socketgroup_callback(job_t j
)
5552 job_dispatch(j
, true);
5556 envitem_new(job_t j
, const char *k
, const char *v
, bool global
, bool one_shot
)
5558 struct envitem
*ei
= calloc(1, sizeof(struct envitem
) + strlen(k
) + 1 + strlen(v
) + 1);
5560 if (!job_assumes(j
, ei
!= NULL
)) {
5564 strcpy(ei
->key_init
, k
);
5565 ei
->value
= ei
->key_init
+ strlen(k
) + 1;
5566 strcpy(ei
->value
, v
);
5567 ei
->one_shot
= one_shot
;
5570 if (SLIST_EMPTY(&j
->global_env
)) {
5571 LIST_INSERT_HEAD(&j
->mgr
->global_env_jobs
, j
, global_env_sle
);
5573 SLIST_INSERT_HEAD(&j
->global_env
, ei
, sle
);
5575 SLIST_INSERT_HEAD(&j
->env
, ei
, sle
);
5578 job_log(j
, LOG_DEBUG
, "Added environmental variable: %s=%s", k
, v
);
5584 envitem_delete(job_t j
, struct envitem
*ei
, bool global
)
5587 SLIST_REMOVE(&j
->global_env
, ei
, envitem
, sle
);
5588 if (SLIST_EMPTY(&j
->global_env
)) {
5589 LIST_REMOVE(j
, global_env_sle
);
5592 SLIST_REMOVE(&j
->env
, ei
, envitem
, sle
);
5599 envitem_setup(launch_data_t obj
, const char *key
, void *context
)
5603 if (launch_data_get_type(obj
) != LAUNCH_DATA_STRING
) {
5607 if (strncmp(LAUNCHD_TRUSTED_FD_ENV
, key
, sizeof(LAUNCHD_TRUSTED_FD_ENV
) - 1) != 0) {
5608 envitem_new(j
, key
, launch_data_get_string(obj
), j
->importing_global_env
, false);
5610 job_log(j
, LOG_DEBUG
, "Ignoring reserved environmental variable: %s", key
);
5615 envitem_setup_one_shot(launch_data_t obj
, const char *key
, void *context
)
5619 if (launch_data_get_type(obj
) != LAUNCH_DATA_STRING
) {
5623 if (strncmp(LAUNCHD_TRUSTED_FD_ENV
, key
, sizeof(LAUNCHD_TRUSTED_FD_ENV
) - 1) != 0) {
5624 envitem_new(j
, key
, launch_data_get_string(obj
), j
->importing_global_env
, true);
5626 job_log(j
, LOG_DEBUG
, "Ignoring reserved environmental variable: %s", key
);
5631 limititem_update(job_t j
, int w
, rlim_t r
)
5633 struct limititem
*li
;
5635 SLIST_FOREACH(li
, &j
->limits
, sle
) {
5636 if (li
->which
== w
) {
5642 li
= calloc(1, sizeof(struct limititem
));
5644 if (!job_assumes(j
, li
!= NULL
)) {
5648 SLIST_INSERT_HEAD(&j
->limits
, li
, sle
);
5653 if (j
->importing_hard_limits
) {
5654 li
->lim
.rlim_max
= r
;
5657 li
->lim
.rlim_cur
= r
;
5665 limititem_delete(job_t j
, struct limititem
*li
)
5667 SLIST_REMOVE(&j
->limits
, li
, limititem
, sle
);
5674 seatbelt_setup_flags(launch_data_t obj
, const char *key
, void *context
)
5678 if (launch_data_get_type(obj
) != LAUNCH_DATA_BOOL
) {
5679 job_log(j
, LOG_WARNING
, "Sandbox flag value must be boolean: %s", key
);
5683 if (launch_data_get_bool(obj
) == false) {
5687 if (strcasecmp(key
, LAUNCH_JOBKEY_SANDBOX_NAMED
) == 0) {
5688 j
->seatbelt_flags
|= SANDBOX_NAMED
;
5694 limititem_setup(launch_data_t obj
, const char *key
, void *context
)
5697 size_t i
, limits_cnt
= (sizeof(launchd_keys2limits
) / sizeof(launchd_keys2limits
[0]));
5700 if (launch_data_get_type(obj
) != LAUNCH_DATA_INTEGER
) {
5704 rl
= launch_data_get_integer(obj
);
5706 for (i
= 0; i
< limits_cnt
; i
++) {
5707 if (strcasecmp(launchd_keys2limits
[i
].key
, key
) == 0) {
5712 if (i
== limits_cnt
) {
5716 limititem_update(j
, launchd_keys2limits
[i
].val
, rl
);
5720 job_useless(job_t j
)
5722 if ((j
->legacy_LS_job
|| j
->only_once
) && j
->start_time
!= 0) {
5723 if (j
->legacy_LS_job
&& j
->j_port
) {
5726 job_log(j
, LOG_INFO
, "Exited. Was only configured to run once.");
5728 } else if (j
->removal_pending
) {
5729 job_log(j
, LOG_DEBUG
, "Exited while removal was pending.");
5731 } else if (j
->shutdown_monitor
) {
5733 } else if (j
->mgr
->shutting_down
) {
5734 job_log(j
, LOG_DEBUG
, "Exited while shutdown in progress. Processes remaining: %lu/%lu", total_children
, total_anon_children
);
5735 if (total_children
== 0 && !j
->anonymous
) {
5736 job_log(j
, LOG_DEBUG
| LOG_CONSOLE
, "Job was last to exit during shutdown of: %s.", j
->mgr
->name
);
5739 } else if (j
->legacy_mach_job
) {
5740 if (SLIST_EMPTY(&j
->machservices
)) {
5741 job_log(j
, LOG_INFO
, "Garbage collecting");
5743 } else if (!j
->checkedin
) {
5744 job_log(j
, LOG_WARNING
, "Failed to check-in!");
5748 /* If the job's executable does not have any valid architectures (for
5749 * example, if it's a PowerPC-only job), then we don't even bother
5750 * trying to relaunch it, as we have no reasonable expectation that
5751 * the situation will change.
5753 * <rdar://problem/9106979>
5755 if (!j
->did_exec
&& WEXITSTATUS(j
->last_exit_status
) == EBADARCH
) {
5756 job_log(j
, LOG_ERR
, "Job executable does not contain supported architectures. Unloading it. Its plist should be removed.");
5765 job_keepalive(job_t j
)
5767 mach_msg_type_number_t statusCnt
;
5768 mach_port_status_t status
;
5769 struct semaphoreitem
*si
;
5770 struct machservice
*ms
;
5772 bool good_exit
= (WIFEXITED(j
->last_exit_status
) && WEXITSTATUS(j
->last_exit_status
) == 0);
5773 bool is_not_kextd
= (do_apple_internal_logging
|| (strcmp(j
->label
, "com.apple.kextd") != 0));
5775 if (unlikely(j
->mgr
->shutting_down
)) {
5782 * We definitely need to revisit this after Leopard ships. Please see
5783 * launchctl.c for the other half of this hack.
5785 if (unlikely((j
->mgr
->global_on_demand_cnt
> 0) && is_not_kextd
)) {
5789 if (unlikely(j
->needs_kickoff
)) {
5790 job_log(j
, LOG_DEBUG
, "KeepAlive check: Job needs to be kicked off on-demand before KeepAlive sets in.");
5794 if (j
->start_pending
) {
5795 job_log(j
, LOG_DEBUG
, "KeepAlive check: Pent-up non-IPC launch criteria.");
5800 job_log(j
, LOG_DEBUG
, "KeepAlive check: job configured to run continuously.");
5804 SLIST_FOREACH(ms
, &j
->machservices
, sle
) {
5805 statusCnt
= MACH_PORT_RECEIVE_STATUS_COUNT
;
5806 if (mach_port_get_attributes(mach_task_self(), ms
->port
, MACH_PORT_RECEIVE_STATUS
,
5807 (mach_port_info_t
)&status
, &statusCnt
) != KERN_SUCCESS
) {
5810 if (status
.mps_msgcount
) {
5811 job_log(j
, LOG_DEBUG
, "KeepAlive check: %d queued Mach messages on service: %s",
5812 status
.mps_msgcount
, ms
->name
);
5817 /* TODO: Coalesce external events and semaphore items, since they're basically
5820 struct externalevent
*ei
= NULL
;
5821 LIST_FOREACH(ei
, &j
->events
, job_le
) {
5822 if (ei
->state
== ei
->wanted_state
) {
5827 SLIST_FOREACH(si
, &j
->semaphores
, sle
) {
5828 bool wanted_state
= false;
5834 wanted_state
= true;
5836 if (network_up
== wanted_state
) {
5837 job_log(j
, LOG_DEBUG
, "KeepAlive: The network is %s.", wanted_state
? "up" : "down");
5841 case SUCCESSFUL_EXIT
:
5842 wanted_state
= true;
5844 if (good_exit
== wanted_state
) {
5845 job_log(j
, LOG_DEBUG
, "KeepAlive: The exit state was %s.", wanted_state
? "successful" : "failure");
5850 wanted_state
= true;
5852 if (j
->crashed
== wanted_state
) {
5856 case OTHER_JOB_ENABLED
:
5857 wanted_state
= true;
5858 case OTHER_JOB_DISABLED
:
5859 if ((bool)job_find(NULL
, si
->what
) == wanted_state
) {
5860 job_log(j
, LOG_DEBUG
, "KeepAlive: The following job is %s: %s", wanted_state
? "enabled" : "disabled", si
->what
);
5864 case OTHER_JOB_ACTIVE
:
5865 wanted_state
= true;
5866 case OTHER_JOB_INACTIVE
:
5867 if ((other_j
= job_find(NULL
, si
->what
))) {
5868 if ((bool)other_j
->p
== wanted_state
) {
5869 job_log(j
, LOG_DEBUG
, "KeepAlive: The following job is %s: %s", wanted_state
? "active" : "inactive", si
->what
);
5875 wanted_state
= true;
5877 if ((bool)(stat(si
->what
, &sb
) == 0) == wanted_state
) {
5878 job_log(j
, LOG_DEBUG
, "KeepAlive: The following path %s: %s", wanted_state
? "exists" : "is missing", si
->what
);
5881 if (wanted_state
) { /* File is not there but we wish it was. */
5882 if (si
->fd
!= -1 && !si
->watching_parent
) { /* Need to be watching the parent now. */
5883 (void)job_assumes(j
, runtime_close(si
->fd
) == 0);
5885 semaphoreitem_watch(j
, si
);
5887 } else { /* File is there but we wish it wasn't. */
5888 if (si
->fd
!= -1 && si
->watching_parent
) { /* Need to watch the file now. */
5889 (void)job_assumes(j
, runtime_close(si
->fd
) == 0);
5891 semaphoreitem_watch(j
, si
);
5899 if (-1 == (qdir_file_cnt
= dir_has_files(j
, si
->what
))) {
5900 job_log_error(j
, LOG_ERR
, "Failed to count the number of files in \"%s\"", si
->what
);
5901 } else if (qdir_file_cnt
> 0) {
5902 job_log(j
, LOG_DEBUG
, "KeepAlive: Directory is not empty: %s", si
->what
);
5915 struct machservice
*ms
;
5916 if (j
->p
&& j
->shutdown_monitor
) {
5917 return "Monitoring shutdown";
5920 return "PID is still valid";
5923 if (j
->mgr
->shutting_down
&& j
->log_redirect_fd
) {
5924 (void)job_assumes(j
, runtime_close(j
->log_redirect_fd
) != -1);
5925 j
->log_redirect_fd
= 0;
5928 if (j
->log_redirect_fd
) {
5929 if (job_assumes(j
, j
->legacy_LS_job
)) {
5930 return "Standard out/error is still valid";
5932 (void)job_assumes(j
, runtime_close(j
->log_redirect_fd
) != -1);
5933 j
->log_redirect_fd
= 0;
5937 if (j
->priv_port_has_senders
) {
5938 return "Privileged Port still has outstanding senders";
5941 SLIST_FOREACH(ms
, &j
->machservices
, sle
) {
5942 if (ms
->recv
&& machservice_active(ms
)) {
5943 return "Mach service is still active";
5951 machservice_watch(job_t j
, struct machservice
*ms
)
5954 (void)job_assumes(j
, runtime_add_mport(ms
->port
, NULL
, 0) == KERN_SUCCESS
);
5959 machservice_ignore(job_t j
, struct machservice
*ms
)
5961 (void)job_assumes(j
, runtime_remove_mport(ms
->port
) == KERN_SUCCESS
);
5965 machservice_resetport(job_t j
, struct machservice
*ms
)
5967 LIST_REMOVE(ms
, port_hash_sle
);
5968 (void)job_assumes(j
, launchd_mport_close_recv(ms
->port
) == KERN_SUCCESS
);
5969 (void)job_assumes(j
, launchd_mport_deallocate(ms
->port
) == KERN_SUCCESS
);
5971 (void)job_assumes(j
, launchd_mport_create_recv(&ms
->port
) == KERN_SUCCESS
);
5972 (void)job_assumes(j
, launchd_mport_make_send(ms
->port
) == KERN_SUCCESS
);
5973 LIST_INSERT_HEAD(&port_hash
[HASH_PORT(ms
->port
)], ms
, port_hash_sle
);
5976 struct machservice
*
5977 machservice_new(job_t j
, const char *name
, mach_port_t
*serviceport
, bool pid_local
)
5979 struct machservice
*ms
= calloc(1, sizeof(struct machservice
) + strlen(name
) + 1);
5981 if (!job_assumes(j
, ms
!= NULL
)) {
5985 strcpy((char *)ms
->name
, name
);
5988 ms
->per_pid
= pid_local
;
5990 if (likely(*serviceport
== MACH_PORT_NULL
)) {
5991 if (!job_assumes(j
, launchd_mport_create_recv(&ms
->port
) == KERN_SUCCESS
)) {
5995 if (!job_assumes(j
, launchd_mport_make_send(ms
->port
) == KERN_SUCCESS
)) {
5998 *serviceport
= ms
->port
;
6001 ms
->port
= *serviceport
;
6002 ms
->isActive
= true;
6005 SLIST_INSERT_HEAD(&j
->machservices
, ms
, sle
);
6007 jobmgr_t where2put
= j
->mgr
;
6008 /* XPC domains are separate from Mach bootstraps. */
6009 if (!(j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
)) {
6010 if (g_flat_mach_namespace
&& !(j
->mgr
->properties
& BOOTSTRAP_PROPERTY_EXPLICITSUBSET
)) {
6011 where2put
= root_jobmgr
;
6015 /* Don't allow MachServices added by multiple-instance jobs to be looked up by others.
6016 * We could just do this with a simple bit, but then we'd have to uniquify the
6017 * names ourselves to avoid collisions. This is just easier.
6019 if (!j
->dedicated_instance
) {
6020 LIST_INSERT_HEAD(&where2put
->ms_hash
[hash_ms(ms
->name
)], ms
, name_hash_sle
);
6022 LIST_INSERT_HEAD(&port_hash
[HASH_PORT(ms
->port
)], ms
, port_hash_sle
);
6024 job_log(j
, LOG_DEBUG
, "Mach service added%s: %s", (j
->mgr
->properties
& BOOTSTRAP_PROPERTY_EXPLICITSUBSET
) ? " to private namespace" : "", name
);
6028 (void)job_assumes(j
, launchd_mport_close_recv(ms
->port
) == KERN_SUCCESS
);
6034 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
6035 struct machservice
*
6036 machservice_new_alias(job_t j
, struct machservice
*orig
)
6038 struct machservice
*ms
= calloc(1, sizeof(struct machservice
) + strlen(orig
->name
) + 1);
6039 if (job_assumes(j
, ms
!= NULL
)) {
6040 strcpy((char *)ms
->name
, orig
->name
);
6044 LIST_INSERT_HEAD(&j
->mgr
->ms_hash
[hash_ms(ms
->name
)], ms
, name_hash_sle
);
6045 SLIST_INSERT_HEAD(&j
->machservices
, ms
, sle
);
6046 jobmgr_log(j
->mgr
, LOG_DEBUG
, "Service aliased into job manager: %s", orig
->name
);
6051 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
6054 machservice_status(struct machservice
*ms
)
6056 ms
= ms
->alias
? ms
->alias
: ms
;
6058 return BOOTSTRAP_STATUS_ACTIVE
;
6059 } else if (ms
->job
->ondemand
) {
6060 return BOOTSTRAP_STATUS_ON_DEMAND
;
6062 return BOOTSTRAP_STATUS_INACTIVE
;
6067 job_setup_exception_port(job_t j
, task_t target_task
)
6069 struct machservice
*ms
;
6070 thread_state_flavor_t f
= 0;
6071 mach_port_t exc_port
= the_exception_server
;
6073 if (unlikely(j
->alt_exc_handler
)) {
6074 ms
= jobmgr_lookup_service(j
->mgr
, j
->alt_exc_handler
, true, 0);
6076 exc_port
= machservice_port(ms
);
6078 job_log(j
, LOG_WARNING
, "Falling back to default Mach exception handler. Could not find: %s", j
->alt_exc_handler
);
6080 } else if (unlikely(j
->internal_exc_handler
)) {
6081 exc_port
= runtime_get_kernel_port();
6082 } else if (unlikely(!exc_port
)) {
6086 #if defined (__ppc__) || defined(__ppc64__)
6087 f
= PPC_THREAD_STATE64
;
6088 #elif defined(__i386__) || defined(__x86_64__)
6089 f
= x86_THREAD_STATE
;
6090 #elif defined(__arm__)
6091 f
= ARM_THREAD_STATE
;
6093 #error "unknown architecture"
6096 if (likely(target_task
)) {
6097 (void)job_assumes(j
, task_set_exception_ports(target_task
, EXC_MASK_CRASH
, exc_port
, EXCEPTION_STATE_IDENTITY
| MACH_EXCEPTION_CODES
, f
) == KERN_SUCCESS
);
6098 } else if (pid1_magic
&& the_exception_server
) {
6099 mach_port_t mhp
= mach_host_self();
6100 (void)job_assumes(j
, host_set_exception_ports(mhp
, EXC_MASK_CRASH
, the_exception_server
, EXCEPTION_STATE_IDENTITY
| MACH_EXCEPTION_CODES
, f
) == KERN_SUCCESS
);
6101 job_assumes(j
, launchd_mport_deallocate(mhp
) == KERN_SUCCESS
);
6106 job_set_exception_port(job_t j
, mach_port_t port
)
6108 if (unlikely(!the_exception_server
)) {
6109 the_exception_server
= port
;
6110 job_setup_exception_port(j
, 0);
6112 job_log(j
, LOG_WARNING
, "The exception server is already claimed!");
6117 machservice_setup_options(launch_data_t obj
, const char *key
, void *context
)
6119 struct machservice
*ms
= context
;
6120 mach_port_t mhp
= mach_host_self();
6124 if (!job_assumes(ms
->job
, mhp
!= MACH_PORT_NULL
)) {
6128 switch (launch_data_get_type(obj
)) {
6129 case LAUNCH_DATA_INTEGER
:
6130 which_port
= (int)launch_data_get_integer(obj
); /* XXX we should bound check this... */
6131 if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_TASKSPECIALPORT
) == 0) {
6132 switch (which_port
) {
6133 case TASK_KERNEL_PORT
:
6134 case TASK_HOST_PORT
:
6135 case TASK_NAME_PORT
:
6136 case TASK_BOOTSTRAP_PORT
:
6137 /* I find it a little odd that zero isn't reserved in the header.
6138 * Normally Mach is fairly good about this convention... */
6140 job_log(ms
->job
, LOG_WARNING
, "Tried to set a reserved task special port: %d", which_port
);
6143 ms
->special_port_num
= which_port
;
6144 SLIST_INSERT_HEAD(&special_ports
, ms
, special_port_sle
);
6147 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_HOSTSPECIALPORT
) == 0 && pid1_magic
) {
6148 if (which_port
> HOST_MAX_SPECIAL_KERNEL_PORT
) {
6149 (void)job_assumes(ms
->job
, (errno
= host_set_special_port(mhp
, which_port
, ms
->port
)) == KERN_SUCCESS
);
6151 job_log(ms
->job
, LOG_WARNING
, "Tried to set a reserved host special port: %d", which_port
);
6154 case LAUNCH_DATA_BOOL
:
6155 b
= launch_data_get_bool(obj
);
6156 if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_ENTERKERNELDEBUGGERONCLOSE
) == 0) {
6157 ms
->debug_on_close
= b
;
6158 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_RESETATCLOSE
) == 0) {
6160 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_HIDEUNTILCHECKIN
) == 0) {
6162 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_EXCEPTIONSERVER
) == 0) {
6163 job_set_exception_port(ms
->job
, ms
->port
);
6164 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_KUNCSERVER
) == 0) {
6166 (void)job_assumes(ms
->job
, host_set_UNDServer(mhp
, ms
->port
) == KERN_SUCCESS
);
6167 } else if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_PINGEVENTUPDATES
) == 0) {
6168 ms
->event_update_port
= b
;
6171 case LAUNCH_DATA_STRING
:
6172 if (strcasecmp(key
, LAUNCH_JOBKEY_MACH_DRAINMESSAGESONCRASH
) == 0) {
6173 const char *option
= launch_data_get_string(obj
);
6174 if (strcasecmp(option
, "One") == 0) {
6175 ms
->drain_one_on_crash
= true;
6176 } else if (strcasecmp(option
, "All") == 0) {
6177 ms
->drain_all_on_crash
= true;
6181 case LAUNCH_DATA_DICTIONARY
:
6182 job_set_exception_port(ms
->job
, ms
->port
);
6188 job_assumes(ms
->job
, launchd_mport_deallocate(mhp
) == KERN_SUCCESS
);
6192 machservice_setup(launch_data_t obj
, const char *key
, void *context
)
6195 struct machservice
*ms
;
6196 mach_port_t p
= MACH_PORT_NULL
;
6198 if (unlikely(ms
= jobmgr_lookup_service(j
->mgr
, key
, false, 0))) {
6199 job_log(j
, LOG_WARNING
, "Conflict with job: %s over Mach service: %s", ms
->job
->label
, key
);
6203 if (!job_assumes(j
, (ms
= machservice_new(j
, key
, &p
, false)) != NULL
)) {
6207 ms
->isActive
= false;
6210 if (launch_data_get_type(obj
) == LAUNCH_DATA_DICTIONARY
) {
6211 launch_data_dict_iterate(obj
, machservice_setup_options
, ms
);
6216 jobmgr_do_garbage_collection(jobmgr_t jm
)
6218 jobmgr_t jmi
= NULL
, jmn
= NULL
;
6219 SLIST_FOREACH_SAFE(jmi
, &jm
->submgrs
, sle
, jmn
) {
6220 jobmgr_do_garbage_collection(jmi
);
6223 if (!jm
->shutting_down
) {
6227 if (SLIST_EMPTY(&jm
->submgrs
)) {
6228 jobmgr_log(jm
, LOG_DEBUG
, "No submanagers left.");
6230 jobmgr_log(jm
, LOG_DEBUG
, "Still have submanagers.");
6231 SLIST_FOREACH(jmi
, &jm
->submgrs
, sle
) {
6232 jobmgr_log(jm
, LOG_DEBUG
, "Submanager: %s", jmi
->name
);
6237 job_t ji
= NULL
, jn
= NULL
;
6238 LIST_FOREACH_SAFE(ji
, &jm
->jobs
, sle
, jn
) {
6239 if (ji
->anonymous
) {
6243 /* Let the shutdown monitor be up until the very end. */
6244 if (ji
->shutdown_monitor
) {
6248 /* On our first pass through, open a transaction for all the jobs that
6249 * need to be dirty at shutdown. We'll close these transactions once the
6250 * jobs that do not need to be dirty at shutdown have all exited.
6252 if (ji
->dirty_at_shutdown
&& !jm
->shutdown_jobs_dirtied
) {
6253 job_open_shutdown_transaction(ji
);
6256 const char *active
= job_active(ji
);
6260 job_log(ji
, LOG_DEBUG
, "Job is active: %s", active
);
6263 if (ji
->p
&& !ji
->dirty_at_shutdown
) {
6264 /* We really only care if the job has not yet been reaped.
6265 * There's no reason to delay shutdown if a Mach port has not
6266 * yet been sent back to us, for example. While we're shutting
6267 * all the "normal" jobs down, do not count the
6268 * dirty-at-shutdown jobs toward the total of actives.
6270 * Note that there's a potential race here where we may not get
6271 * a port back in time, so that when we hit jobmgr_remove(), we
6272 * end up removing the job and then our attempt to close the
6273 * Mach port will fail. But at that point, the failure won't
6274 * even make it to the syslog, so not a big deal.
6279 if (ji
->clean_kill
) {
6280 job_log(ji
, LOG_DEBUG
, "Job was killed cleanly.");
6282 job_log(ji
, LOG_DEBUG
, "Job was sent SIGTERM%s.", ji
->sent_sigkill
? " and SIGKILL" : "");
6287 jm
->shutdown_jobs_dirtied
= true;
6289 if (!jm
->shutdown_jobs_cleaned
) {
6290 LIST_FOREACH(ji
, &jm
->jobs
, sle
) {
6291 if (!ji
->anonymous
) {
6292 job_close_shutdown_transaction(ji
);
6297 jm
->shutdown_jobs_cleaned
= true;
6298 } else if (jm
->monitor_shutdown
&& _s_shutdown_monitor
) {
6299 /* The rest of shutdown has completed, so we can kill the shutdown
6300 * monitor now like it was any other job.
6302 _s_shutdown_monitor
->shutdown_monitor
= false;
6305 job_log(_s_shutdown_monitor
, LOG_NOTICE
| LOG_CONSOLE
, "Stopping shutdown monitor.");
6306 job_stop(_s_shutdown_monitor
);
6307 _s_shutdown_monitor
= NULL
;
6312 if (SLIST_EMPTY(&jm
->submgrs
) && actives
== 0) {
6313 jobmgr_log(jm
, LOG_DEBUG
, "Removing.");
6322 jobmgr_kill_stray_children(jobmgr_t jm
, pid_t
*p
, size_t np
)
6324 /* I maintain that stray processes should be at the mercy of launchd during shutdown,
6325 * but nevertheless, things like diskimages-helper can stick around, and SIGKILLing
6326 * them can result in data loss. So we send SIGTERM to all the strays and don't wait
6327 * for them to exit before moving on.
6329 * See rdar://problem/6562592
6332 for (i
= 0; i
< np
; i
++) {
6334 jobmgr_log(jm
, LOG_DEBUG
| LOG_CONSOLE
, "Sending SIGTERM to PID %u and continuing...", p
[i
]);
6335 (void)jobmgr_assumes(jm
, runtime_kill(p
[i
], SIGTERM
) != -1);
6341 jobmgr_log_stray_children(jobmgr_t jm
, bool kill_strays
)
6343 size_t kp_skipped
= 0, len
= sizeof(pid_t
) * get_kern_max_proc();
6345 int i
= 0, kp_cnt
= 0;
6347 if (likely(jm
->parentmgr
|| !pid1_magic
)) {
6351 if (!jobmgr_assumes(jm
, (pids
= malloc(len
)) != NULL
)) {
6355 runtime_ktrace0(RTKT_LAUNCHD_FINDING_ALL_STRAYS
);
6357 if (!jobmgr_assumes(jm
, (kp_cnt
= proc_listallpids(pids
, len
)) != -1)) {
6361 pid_t
*ps
= (pid_t
*)calloc(sizeof(pid_t
), kp_cnt
);
6362 for (i
= 0; i
< kp_cnt
; i
++) {
6363 struct proc_bsdshortinfo proc
;
6364 if (proc_pidinfo(pids
[i
], PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
6365 if (errno
!= ESRCH
) {
6366 jobmgr_assumes(jm
, errno
== 0);
6373 pid_t p_i
= pids
[i
];
6374 pid_t pp_i
= proc
.pbsi_ppid
;
6375 pid_t pg_i
= proc
.pbsi_pgid
;
6376 const char *z
= (proc
.pbsi_status
== SZOMB
) ? "zombie " : "";
6377 const char *n
= proc
.pbsi_comm
;
6379 if (unlikely(p_i
== 0 || p_i
== 1)) {
6384 if (_s_shutdown_monitor
&& pp_i
== _s_shutdown_monitor
->p
) {
6389 /* We might have some jobs hanging around that we've decided to shut down in spite of. */
6390 job_t j
= jobmgr_find_by_pid(jm
, p_i
, false);
6391 if (!j
|| (j
&& j
->anonymous
)) {
6392 jobmgr_log(jm
, LOG_INFO
| LOG_CONSOLE
, "Stray %s%s at shutdown: PID %u PPID %u PGID %u %s", z
, j
? "anonymous job" : "process", p_i
, pp_i
, pg_i
, n
);
6395 if (pp_i
== getpid() && !jobmgr_assumes(jm
, proc
.pbsi_status
!= SZOMB
)) {
6396 if (jobmgr_assumes(jm
, waitpid(p_i
, &status
, WNOHANG
) == 0)) {
6397 jobmgr_log(jm
, LOG_INFO
| LOG_CONSOLE
, "Unreaped zombie stray exited with status %i.", WEXITSTATUS(status
));
6401 job_t leader
= jobmgr_find_by_pid(jm
, pg_i
, false);
6402 /* See rdar://problem/6745714. Some jobs have child processes that back kernel state,
6403 * so we don't want to terminate them. Long-term, I'd really like to provide shutdown
6404 * hints to the kernel along the way, so that it could shutdown certain subsystems when
6405 * their userspace emissaries go away, before the call to reboot(2).
6407 if (leader
&& leader
->ignore_pg_at_shutdown
) {
6418 if ((kp_cnt
- kp_skipped
> 0) && kill_strays
) {
6419 jobmgr_kill_stray_children(jm
, ps
, kp_cnt
- kp_skipped
);
6428 jobmgr_parent(jobmgr_t jm
)
6430 return jm
->parentmgr
;
6434 job_uncork_fork(job_t j
)
6438 job_log(j
, LOG_DEBUG
, "Uncorking the fork().");
6439 /* this unblocks the child and avoids a race
6440 * between the above fork() and the kevent_mod() */
6441 (void)job_assumes(j
, write(j
->fork_fd
, &c
, sizeof(c
)) == sizeof(c
));
6442 (void)job_assumes(j
, runtime_close(j
->fork_fd
) != -1);
6447 jobmgr_new(jobmgr_t jm
, mach_port_t requestorport
, mach_port_t transfer_port
, bool sflag
, const char *name
, bool skip_init
, mach_port_t asport
)
6449 mach_msg_size_t mxmsgsz
;
6450 job_t bootstrapper
= NULL
;
6453 launchd_assert(offsetof(struct jobmgr_s
, kqjobmgr_callback
) == 0);
6455 if (unlikely(jm
&& requestorport
== MACH_PORT_NULL
)) {
6456 jobmgr_log(jm
, LOG_ERR
, "Mach sub-bootstrap create request requires a requester port");
6460 jmr
= calloc(1, sizeof(struct jobmgr_s
) + (name
? (strlen(name
) + 1) : NAME_MAX
+ 1));
6462 if (!jobmgr_assumes(jm
, jmr
!= NULL
)) {
6470 jmr
->kqjobmgr_callback
= jobmgr_callback
;
6471 strcpy(jmr
->name_init
, name
? name
: "Under construction");
6473 jmr
->req_port
= requestorport
;
6475 if ((jmr
->parentmgr
= jm
)) {
6476 SLIST_INSERT_HEAD(&jm
->submgrs
, jmr
, sle
);
6479 if (jm
&& !jobmgr_assumes(jmr
, launchd_mport_notify_req(jmr
->req_port
, MACH_NOTIFY_DEAD_NAME
) == KERN_SUCCESS
)) {
6483 if (transfer_port
!= MACH_PORT_NULL
) {
6484 (void)jobmgr_assumes(jmr
, jm
!= NULL
);
6485 jmr
->jm_port
= transfer_port
;
6486 } else if (!jm
&& !pid1_magic
) {
6487 char *trusted_fd
= getenv(LAUNCHD_TRUSTED_FD_ENV
);
6490 snprintf(service_buf
, sizeof(service_buf
), "com.apple.launchd.peruser.%u", getuid());
6492 if (!jobmgr_assumes(jmr
, bootstrap_check_in(bootstrap_port
, service_buf
, &jmr
->jm_port
) == 0)) {
6497 int dfd
, lfd
= (int) strtol(trusted_fd
, NULL
, 10);
6499 if ((dfd
= dup(lfd
)) >= 0) {
6500 (void)jobmgr_assumes(jmr
, runtime_close(dfd
) != -1);
6501 (void)jobmgr_assumes(jmr
, runtime_close(lfd
) != -1);
6504 unsetenv(LAUNCHD_TRUSTED_FD_ENV
);
6507 /* cut off the Libc cache, we don't want to deadlock against ourself */
6508 inherited_bootstrap_port
= bootstrap_port
;
6509 bootstrap_port
= MACH_PORT_NULL
;
6510 launchd_assert(launchd_mport_notify_req(inherited_bootstrap_port
, MACH_NOTIFY_DEAD_NAME
) == KERN_SUCCESS
);
6512 /* We set this explicitly as we start each child */
6513 launchd_assert(launchd_set_bport(MACH_PORT_NULL
) == KERN_SUCCESS
);
6514 } else if (!jobmgr_assumes(jmr
, launchd_mport_create_recv(&jmr
->jm_port
) == KERN_SUCCESS
)) {
6519 sprintf(jmr
->name_init
, "%u", MACH_PORT_INDEX(jmr
->jm_port
));
6522 /* Sigh... at the moment, MIG has maxsize == sizeof(reply union) */
6523 mxmsgsz
= (typeof(mxmsgsz
)) sizeof(union __RequestUnion__job_mig_protocol_vproc_subsystem
);
6524 if (job_mig_protocol_vproc_subsystem
.maxsize
> mxmsgsz
) {
6525 mxmsgsz
= job_mig_protocol_vproc_subsystem
.maxsize
;
6528 /* Total hacks. But the MIG server loop is too generic, and the more dynamic
6529 * parts of it haven't been tested, or if they have, it was a very long time
6532 if (xpc_events_xpc_events_subsystem
.maxsize
> mxmsgsz
) {
6533 mxmsgsz
= xpc_events_xpc_events_subsystem
.maxsize
;
6535 if (xpc_domain_xpc_domain_subsystem
.maxsize
> mxmsgsz
) {
6536 mxmsgsz
= xpc_domain_xpc_domain_subsystem
.maxsize
;
6540 (void)jobmgr_assumes(jmr
, kevent_mod(SIGTERM
, EVFILT_SIGNAL
, EV_ADD
, 0, 0, jmr
) != -1);
6541 (void)jobmgr_assumes(jmr
, kevent_mod(SIGUSR1
, EVFILT_SIGNAL
, EV_ADD
, 0, 0, jmr
) != -1);
6542 (void)jobmgr_assumes(jmr
, kevent_mod(SIGUSR2
, EVFILT_SIGNAL
, EV_ADD
, 0, 0, jmr
) != -1);
6543 (void)jobmgr_assumes(jmr
, kevent_mod(0, EVFILT_FS
, EV_ADD
, VQ_MOUNT
|VQ_UNMOUNT
|VQ_UPDATE
, 0, jmr
) != -1);
6546 if (name
&& !skip_init
) {
6547 bootstrapper
= jobmgr_init_session(jmr
, name
, sflag
);
6550 if (!bootstrapper
|| !bootstrapper
->weird_bootstrap
) {
6551 if (!jobmgr_assumes(jmr
, runtime_add_mport(jmr
->jm_port
, protocol_vproc_server
, mxmsgsz
) == KERN_SUCCESS
)) {
6556 jobmgr_log(jmr
, LOG_DEBUG
, "Created job manager%s%s", jm
? " with parent: " : ".", jm
? jm
->name
: "");
6559 bootstrapper
->asport
= asport
;
6561 jobmgr_log(jmr
, LOG_DEBUG
, "Bootstrapping new job manager with audit session %u", asport
);
6562 (void)jobmgr_assumes(jmr
, job_dispatch(bootstrapper
, true) != NULL
);
6564 jmr
->req_asport
= asport
;
6567 if (asport
!= MACH_PORT_NULL
) {
6568 (void)jobmgr_assumes(jmr
, launchd_mport_copy_send(asport
) == KERN_SUCCESS
);
6571 if (jmr
->parentmgr
) {
6572 runtime_add_weak_ref();
6587 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
6589 jobmgr_new_xpc_singleton_domain(jobmgr_t jm
, name_t name
)
6591 jobmgr_t
new = NULL
;
6593 /* These job managers are basically singletons, so we use the root Mach
6594 * bootstrap port as their requestor ports so they'll never go away.
6596 mach_port_t req_port
= root_jobmgr
->jm_port
;
6597 if (jobmgr_assumes(jm
, launchd_mport_make_send(req_port
) == KERN_SUCCESS
)) {
6598 new = jobmgr_new(root_jobmgr
, req_port
, MACH_PORT_NULL
, false, name
, true, MACH_PORT_NULL
);
6600 new->properties
|= BOOTSTRAP_PROPERTY_XPC_SINGLETON
;
6601 new->properties
|= BOOTSTRAP_PROPERTY_XPC_DOMAIN
;
6602 new->xpc_singleton
= true;
6610 jobmgr_find_xpc_per_user_domain(jobmgr_t jm
, uid_t uid
)
6612 jobmgr_t jmi
= NULL
;
6613 LIST_FOREACH(jmi
, &_s_xpc_user_domains
, xpc_le
) {
6614 if (jmi
->req_euid
== uid
) {
6620 (void)snprintf(name
, sizeof(name
), "com.apple.xpc.domain.peruser.%u", uid
);
6621 jmi
= jobmgr_new_xpc_singleton_domain(jm
, name
);
6622 if (jobmgr_assumes(jm
, jmi
!= NULL
)) {
6623 /* We need to create a per-user launchd for this UID if there isn't one
6624 * already so we can grab the bootstrap port.
6626 job_t puj
= jobmgr_lookup_per_user_context_internal(NULL
, uid
, &jmi
->req_bsport
);
6627 if (jobmgr_assumes(jmi
, puj
!= NULL
)) {
6628 (void)jobmgr_assumes(jmi
, launchd_mport_copy_send(puj
->asport
) == KERN_SUCCESS
);
6629 (void)jobmgr_assumes(jmi
, launchd_mport_copy_send(jmi
->req_bsport
) == KERN_SUCCESS
);
6630 jmi
->shortdesc
= "per-user";
6631 jmi
->req_asport
= puj
->asport
;
6632 jmi
->req_asid
= puj
->asid
;
6633 jmi
->req_euid
= uid
;
6636 LIST_INSERT_HEAD(&_s_xpc_user_domains
, jmi
, xpc_le
);
6646 jobmgr_find_xpc_per_session_domain(jobmgr_t jm
, au_asid_t asid
)
6648 jobmgr_t jmi
= NULL
;
6649 LIST_FOREACH(jmi
, &_s_xpc_session_domains
, xpc_le
) {
6650 if (jmi
->req_asid
== asid
) {
6656 (void)snprintf(name
, sizeof(name
), "com.apple.xpc.domain.persession.%i", asid
);
6657 jmi
= jobmgr_new_xpc_singleton_domain(jm
, name
);
6658 if (jobmgr_assumes(jm
, jmi
!= NULL
)) {
6659 (void)jobmgr_assumes(jmi
, launchd_mport_make_send(root_jobmgr
->jm_port
) == KERN_SUCCESS
);
6660 jmi
->shortdesc
= "per-session";
6661 jmi
->req_bsport
= root_jobmgr
->jm_port
;
6662 (void)jobmgr_assumes(jmi
, audit_session_port(asid
, &jmi
->req_asport
) == 0);
6663 jmi
->req_asid
= asid
;
6667 LIST_INSERT_HEAD(&_s_xpc_session_domains
, jmi
, xpc_le
);
6674 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
6677 jobmgr_init_session(jobmgr_t jm
, const char *session_type
, bool sflag
)
6679 const char *bootstrap_tool
[] = { "/bin/launchctl", "bootstrap", "-S", session_type
, sflag
? "-s" : NULL
, NULL
};
6680 char thelabel
[1000];
6683 snprintf(thelabel
, sizeof(thelabel
), "com.apple.launchctl.%s", session_type
);
6684 bootstrapper
= job_new(jm
, thelabel
, NULL
, bootstrap_tool
);
6686 if (jobmgr_assumes(jm
, bootstrapper
!= NULL
) && (jm
->parentmgr
|| !pid1_magic
)) {
6687 bootstrapper
->is_bootstrapper
= true;
6690 /* <rdar://problem/5042202> launchd-201: can't ssh in with AFP OD account (hangs) */
6691 snprintf(buf
, sizeof(buf
), "0x%X:0:0", getuid());
6692 envitem_new(bootstrapper
, "__CF_USER_TEXT_ENCODING", buf
, false, false);
6693 bootstrapper
->weird_bootstrap
= true;
6694 (void)jobmgr_assumes(jm
, job_setup_machport(bootstrapper
));
6695 } else if (bootstrapper
&& strncmp(session_type
, VPROCMGR_SESSION_SYSTEM
, sizeof(VPROCMGR_SESSION_SYSTEM
)) == 0) {
6696 bootstrapper
->is_bootstrapper
= true;
6697 if (jobmgr_assumes(jm
, pid1_magic
)) {
6698 /* Have our system bootstrapper print out to the console. */
6699 bootstrapper
->stdoutpath
= strdup(_PATH_CONSOLE
);
6700 bootstrapper
->stderrpath
= strdup(_PATH_CONSOLE
);
6703 (void)jobmgr_assumes(jm
, kevent_mod((uintptr_t)fileno(g_console
), EVFILT_VNODE
, EV_ADD
| EV_ONESHOT
, NOTE_REVOKE
, 0, jm
) != -1);
6708 jm
->session_initialized
= true;
6709 return bootstrapper
;
6713 jobmgr_delete_anything_with_port(jobmgr_t jm
, mach_port_t port
)
6715 struct machservice
*ms
, *next_ms
;
6718 /* Mach ports, unlike Unix descriptors, are reference counted. In other
6719 * words, when some program hands us a second or subsequent send right
6720 * to a port we already have open, the Mach kernel gives us the same
6721 * port number back and increments an reference count associated with
6722 * the port. This forces us, when discovering that a receive right at
6723 * the other end has been deleted, to wander all of our objects to see
6724 * what weird places clients might have handed us the same send right
6728 if (jm
== root_jobmgr
) {
6729 if (port
== inherited_bootstrap_port
) {
6730 (void)jobmgr_assumes(jm
, launchd_mport_deallocate(port
) == KERN_SUCCESS
);
6731 inherited_bootstrap_port
= MACH_PORT_NULL
;
6733 return jobmgr_shutdown(jm
);
6736 LIST_FOREACH_SAFE(ms
, &port_hash
[HASH_PORT(port
)], port_hash_sle
, next_ms
) {
6737 if (ms
->port
== port
&& !ms
->recv
) {
6738 machservice_delete(ms
->job
, ms
, true);
6743 SLIST_FOREACH_SAFE(jmi
, &jm
->submgrs
, sle
, jmn
) {
6744 jobmgr_delete_anything_with_port(jmi
, port
);
6747 if (jm
->req_port
== port
) {
6748 jobmgr_log(jm
, LOG_DEBUG
, "Request port died: %i", MACH_PORT_INDEX(port
));
6749 return jobmgr_shutdown(jm
);
6755 struct machservice
*
6756 jobmgr_lookup_service(jobmgr_t jm
, const char *name
, bool check_parent
, pid_t target_pid
)
6758 struct machservice
*ms
;
6761 jobmgr_log(jm
, LOG_DEBUG
, "Looking up %sservice %s", target_pid
? "per-PID " : "", name
);
6764 /* This is a hack to let FileSyncAgent look up per-PID Mach services from the Background
6765 * bootstrap in other bootstraps.
6768 /* Start in the given bootstrap. */
6769 if (unlikely((target_j
= jobmgr_find_by_pid(jm
, target_pid
, false)) == NULL
)) {
6770 /* If we fail, do a deep traversal. */
6771 if (unlikely((target_j
= jobmgr_find_by_pid_deep(root_jobmgr
, target_pid
, true)) == NULL
)) {
6772 jobmgr_log(jm
, LOG_DEBUG
, "Didn't find PID %i", target_pid
);
6777 SLIST_FOREACH(ms
, &target_j
->machservices
, sle
) {
6778 if (ms
->per_pid
&& strcmp(name
, ms
->name
) == 0) {
6783 job_log(target_j
, LOG_DEBUG
, "Didn't find per-PID Mach service: %s", name
);
6787 jobmgr_t where2look
= jm
;
6788 /* XPC domains are separate from Mach bootstraps. */
6789 if (!(jm
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
)) {
6790 if (g_flat_mach_namespace
&& !(jm
->properties
& BOOTSTRAP_PROPERTY_EXPLICITSUBSET
)) {
6791 where2look
= root_jobmgr
;
6795 LIST_FOREACH(ms
, &where2look
->ms_hash
[hash_ms(name
)], name_hash_sle
) {
6796 if (!ms
->per_pid
&& strcmp(name
, ms
->name
) == 0) {
6801 if (jm
->parentmgr
== NULL
|| !check_parent
) {
6805 return jobmgr_lookup_service(jm
->parentmgr
, name
, true, 0);
6809 machservice_port(struct machservice
*ms
)
6815 machservice_job(struct machservice
*ms
)
6821 machservice_hidden(struct machservice
*ms
)
6827 machservice_active(struct machservice
*ms
)
6829 return ms
->isActive
;
6833 machservice_name(struct machservice
*ms
)
6839 machservice_drain_port(struct machservice
*ms
)
6841 bool drain_one
= ms
->drain_one_on_crash
;
6842 bool drain_all
= ms
->drain_all_on_crash
;
6844 if (!job_assumes(ms
->job
, (drain_one
|| drain_all
) == true)) {
6848 job_log(ms
->job
, LOG_INFO
, "Draining %s...", ms
->name
);
6850 char req_buff
[sizeof(union __RequestUnion__catch_mach_exc_subsystem
) * 2];
6851 char rep_buff
[sizeof(union __ReplyUnion__catch_mach_exc_subsystem
)];
6852 mig_reply_error_t
*req_hdr
= (mig_reply_error_t
*)&req_buff
;
6853 mig_reply_error_t
*rep_hdr
= (mig_reply_error_t
*)&rep_buff
;
6855 mach_msg_return_t mr
= ~MACH_MSG_SUCCESS
;
6858 /* This should be a direct check on the Mach service to see if it's an exception-handling
6859 * port, and it will break things if ReportCrash or SafetyNet start advertising other
6860 * Mach services. But for now, it should be okay.
6862 if (ms
->job
->alt_exc_handler
|| ms
->job
->internal_exc_handler
) {
6863 mr
= launchd_exc_runtime_once(ms
->port
, sizeof(req_buff
), sizeof(rep_buff
), req_hdr
, rep_hdr
, 0);
6865 mach_msg_options_t options
= MACH_RCV_MSG
|
6868 mr
= mach_msg((mach_msg_header_t
*)req_hdr
, options
, 0, sizeof(req_buff
), ms
->port
, 0, MACH_PORT_NULL
);
6870 case MACH_MSG_SUCCESS
:
6871 mach_msg_destroy((mach_msg_header_t
*)req_hdr
);
6873 case MACH_RCV_TIMED_OUT
:
6875 case MACH_RCV_TOO_LARGE
:
6876 runtime_syslog(LOG_WARNING
, "Tried to receive message that was larger than %lu bytes", sizeof(req_buff
));
6882 } while (drain_all
&& mr
!= MACH_RCV_TIMED_OUT
);
6886 machservice_delete(job_t j
, struct machservice
*ms
, bool port_died
)
6889 /* HACK: Egregious code duplication. But dealing with aliases is a
6890 * pretty simple affair since they can't and shouldn't have any complex
6891 * behaviors associated with them.
6893 LIST_REMOVE(ms
, name_hash_sle
);
6894 SLIST_REMOVE(&j
->machservices
, ms
, machservice
, sle
);
6899 if (unlikely(ms
->debug_on_close
)) {
6900 job_log(j
, LOG_NOTICE
, "About to enter kernel debugger because of Mach port: 0x%x", ms
->port
);
6901 (void)job_assumes(j
, host_reboot(mach_host_self(), HOST_REBOOT_DEBUGGER
) == KERN_SUCCESS
);
6904 if (ms
->recv
&& job_assumes(j
, !machservice_active(ms
))) {
6905 job_log(j
, LOG_DEBUG
, "Closing receive right for %s", ms
->name
);
6906 (void)job_assumes(j
, launchd_mport_close_recv(ms
->port
) == KERN_SUCCESS
);
6909 (void)job_assumes(j
, launchd_mport_deallocate(ms
->port
) == KERN_SUCCESS
);
6911 if (unlikely(ms
->port
== the_exception_server
)) {
6912 the_exception_server
= 0;
6915 job_log(j
, LOG_DEBUG
, "Mach service deleted%s: %s", port_died
? " (port died)" : "", ms
->name
);
6917 if (ms
->special_port_num
) {
6918 SLIST_REMOVE(&special_ports
, ms
, machservice
, special_port_sle
);
6920 SLIST_REMOVE(&j
->machservices
, ms
, machservice
, sle
);
6922 if (!(j
->dedicated_instance
|| ms
->event_channel
)) {
6923 LIST_REMOVE(ms
, name_hash_sle
);
6925 LIST_REMOVE(ms
, port_hash_sle
);
6931 machservice_request_notifications(struct machservice
*ms
)
6933 mach_msg_id_t which
= MACH_NOTIFY_DEAD_NAME
;
6935 ms
->isActive
= true;
6938 which
= MACH_NOTIFY_PORT_DESTROYED
;
6939 job_checkin(ms
->job
);
6942 (void)job_assumes(ms
->job
, launchd_mport_notify_req(ms
->port
, which
) == KERN_SUCCESS
);
6945 #define NELEM(x) (sizeof(x)/sizeof(x[0]))
6946 #define END_OF(x) (&(x)[NELEM(x)])
6949 mach_cmd2argv(const char *string
)
6951 char *argv
[100], args
[1000];
6953 char *argp
= args
, term
, **argv_ret
, *co
;
6954 unsigned int nargs
= 0, i
;
6956 for (cp
= string
; *cp
;) {
6957 while (isspace(*cp
))
6959 term
= (*cp
== '"') ? *cp
++ : '\0';
6960 if (nargs
< NELEM(argv
)) {
6961 argv
[nargs
++] = argp
;
6963 while (*cp
&& (term
? *cp
!= term
: !isspace(*cp
)) && argp
< END_OF(args
)) {
6980 argv_ret
= malloc((nargs
+ 1) * sizeof(char *) + strlen(string
) + 1);
6982 if (!launchd_assumes(argv_ret
!= NULL
)) {
6986 co
= (char *)argv_ret
+ (nargs
+ 1) * sizeof(char *);
6988 for (i
= 0; i
< nargs
; i
++) {
6989 strcpy(co
, argv
[i
]);
6991 co
+= strlen(argv
[i
]) + 1;
6999 job_checkin(job_t j
)
7001 j
->checkedin
= true;
7004 bool job_is_god(job_t j
)
7006 return j
->embedded_special_privileges
;
7010 job_ack_port_destruction(mach_port_t p
)
7012 struct machservice
*ms
;
7015 LIST_FOREACH(ms
, &port_hash
[HASH_PORT(p
)], port_hash_sle
) {
7016 if (ms
->recv
&& (ms
->port
== p
)) {
7021 if (!jobmgr_assumes(root_jobmgr
, ms
!= NULL
)) {
7027 jobmgr_log(root_jobmgr
, LOG_DEBUG
, "Receive right returned to us: %s", ms
->name
);
7029 /* Without being the exception handler, NOTE_EXIT is our only way to tell if the job
7030 * crashed, and we can't rely on NOTE_EXIT always being processed after all the job's
7031 * receive rights have been returned.
7033 * So when we get receive rights back, check to see if the job has been reaped yet. If
7034 * not, then we add this service to a list of services to be drained on crash if it's
7035 * requested that behavior. So, for a job with N receive rights all requesting that they
7036 * be drained on crash, we can safely handle the following sequence of events.
7038 * ReceiveRight0Returned
7039 * ReceiveRight1Returned
7040 * ReceiveRight2Returned
7041 * NOTE_EXIT (reap, get exit status)
7042 * ReceiveRight3Returned
7046 * ReceiveRight(N - 1)Returned
7049 if (ms
->drain_one_on_crash
|| ms
->drain_all_on_crash
) {
7050 if (j
->crashed
&& j
->reaped
) {
7051 job_log(j
, LOG_DEBUG
, "Job has crashed. Draining port...");
7052 machservice_drain_port(ms
);
7053 } else if (!(j
->crashed
|| j
->reaped
)) {
7054 job_log(j
, LOG_DEBUG
, "Job's exit status is still unknown. Deferring drain.");
7058 /* If we get this notification after the job has been reaped, then we want to ping
7059 * the event port to keep things going.
7061 if (ms
->event_update_port
&& !j
->p
&& job_assumes(j
, j
->event_monitor
)) {
7062 if (_s_event_update_port
== MACH_PORT_NULL
) {
7063 (void)job_assumes(j
, launchd_mport_make_send_once(ms
->port
, &_s_event_update_port
) == KERN_SUCCESS
);
7068 ms
->isActive
= false;
7069 if (ms
->delete_on_destruction
) {
7070 machservice_delete(j
, ms
, false);
7071 } else if (ms
->reset
) {
7072 machservice_resetport(j
, ms
);
7075 job_dispatch(j
, false);
7077 root_jobmgr
= jobmgr_do_garbage_collection(root_jobmgr
);
7083 job_ack_no_senders(job_t j
)
7085 j
->priv_port_has_senders
= false;
7087 (void)job_assumes(j
, launchd_mport_close_recv(j
->j_port
) == KERN_SUCCESS
);
7090 job_log(j
, LOG_DEBUG
, "No more senders on privileged Mach bootstrap port");
7092 job_dispatch(j
, false);
7096 semaphoreitem_new(job_t j
, semaphore_reason_t why
, const char *what
)
7098 struct semaphoreitem
*si
;
7099 size_t alloc_sz
= sizeof(struct semaphoreitem
);
7102 alloc_sz
+= strlen(what
) + 1;
7105 if (!job_assumes(j
, si
= calloc(1, alloc_sz
))) {
7113 strcpy(si
->what_init
, what
);
7116 SLIST_INSERT_HEAD(&j
->semaphores
, si
, sle
);
7118 if ((why
== OTHER_JOB_ENABLED
|| why
== OTHER_JOB_DISABLED
) && !j
->nosy
) {
7119 job_log(j
, LOG_DEBUG
, "Job is interested in \"%s\".", what
);
7120 SLIST_INSERT_HEAD(&s_curious_jobs
, j
, curious_jobs_sle
);
7124 semaphoreitem_runtime_mod_ref(si
, true);
7130 semaphoreitem_runtime_mod_ref(struct semaphoreitem
*si
, bool add
)
7133 * External events need to be tracked.
7134 * Internal events do NOT need to be tracked.
7138 case SUCCESSFUL_EXIT
:
7140 case OTHER_JOB_ENABLED
:
7141 case OTHER_JOB_DISABLED
:
7142 case OTHER_JOB_ACTIVE
:
7143 case OTHER_JOB_INACTIVE
:
7150 runtime_add_weak_ref();
7152 runtime_del_weak_ref();
7157 semaphoreitem_delete(job_t j
, struct semaphoreitem
*si
)
7159 semaphoreitem_runtime_mod_ref(si
, false);
7161 SLIST_REMOVE(&j
->semaphores
, si
, semaphoreitem
, sle
);
7164 (void)job_assumes(j
, runtime_close(si
->fd
) != -1);
7167 /* We'll need to rethink this if it ever becomes possible to dynamically add or remove semaphores. */
7168 if ((si
->why
== OTHER_JOB_ENABLED
|| si
->why
== OTHER_JOB_DISABLED
) && j
->nosy
) {
7170 SLIST_REMOVE(&s_curious_jobs
, j
, job_s
, curious_jobs_sle
);
7177 semaphoreitem_setup_dict_iter(launch_data_t obj
, const char *key
, void *context
)
7179 struct semaphoreitem_dict_iter_context
*sdic
= context
;
7180 semaphore_reason_t why
;
7182 why
= launch_data_get_bool(obj
) ? sdic
->why_true
: sdic
->why_false
;
7184 semaphoreitem_new(sdic
->j
, why
, key
);
7188 semaphoreitem_setup(launch_data_t obj
, const char *key
, void *context
)
7190 struct semaphoreitem_dict_iter_context sdic
= { context
, 0, 0 };
7192 semaphore_reason_t why
;
7194 switch (launch_data_get_type(obj
)) {
7195 case LAUNCH_DATA_BOOL
:
7196 if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_NETWORKSTATE
) == 0) {
7197 why
= launch_data_get_bool(obj
) ? NETWORK_UP
: NETWORK_DOWN
;
7198 semaphoreitem_new(j
, why
, NULL
);
7199 } else if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT
) == 0) {
7200 why
= launch_data_get_bool(obj
) ? SUCCESSFUL_EXIT
: FAILED_EXIT
;
7201 semaphoreitem_new(j
, why
, NULL
);
7202 j
->start_pending
= true;
7203 } else if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_AFTERINITIALDEMAND
) == 0) {
7204 j
->needs_kickoff
= launch_data_get_bool(obj
);
7205 } else if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_CRASHED
) == 0) {
7206 why
= launch_data_get_bool(obj
) ? CRASHED
: DID_NOT_CRASH
;
7207 semaphoreitem_new(j
, why
, NULL
);
7208 j
->start_pending
= true;
7210 (void)job_assumes(j
, false);
7213 case LAUNCH_DATA_DICTIONARY
:
7214 if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_PATHSTATE
) == 0) {
7215 sdic
.why_true
= PATH_EXISTS
;
7216 sdic
.why_false
= PATH_MISSING
;
7217 } else if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_OTHERJOBACTIVE
) == 0) {
7218 sdic
.why_true
= OTHER_JOB_ACTIVE
;
7219 sdic
.why_false
= OTHER_JOB_INACTIVE
;
7220 } else if (strcasecmp(key
, LAUNCH_JOBKEY_KEEPALIVE_OTHERJOBENABLED
) == 0) {
7221 sdic
.why_true
= OTHER_JOB_ENABLED
;
7222 sdic
.why_false
= OTHER_JOB_DISABLED
;
7224 (void)job_assumes(j
, false);
7228 launch_data_dict_iterate(obj
, semaphoreitem_setup_dict_iter
, &sdic
);
7231 (void)job_assumes(j
, false);
7237 externalevent_new(job_t j
, struct eventsystem
*sys
, char *evname
, launch_data_t event
)
7239 struct externalevent
*ee
= (struct externalevent
*)calloc(1, sizeof(struct externalevent
) + strlen(evname
) + 1);
7240 if (job_assumes(j
, ee
!= NULL
)) {
7241 ee
->event
= launch_data_copy(event
);
7242 if (job_assumes(j
, ee
->event
!= NULL
)) {
7243 strcpy(ee
->name
, evname
);
7245 ee
->id
= sys
->curid
;
7248 ee
->wanted_state
= true;
7251 LIST_INSERT_HEAD(&j
->events
, ee
, job_le
);
7252 LIST_INSERT_HEAD(&sys
->events
, ee
, sys_le
);
7254 job_log(j
, LOG_DEBUG
, "New event: %s:%s", sys
->name
, evname
);
7266 externalevent_delete(struct externalevent
*ee
)
7268 launch_data_free(ee
->event
);
7269 LIST_REMOVE(ee
, job_le
);
7270 LIST_REMOVE(ee
, sys_le
);
7278 externalevent_setup(launch_data_t obj
, const char *key
, void *context
)
7280 struct externalevent_iter_ctx
*ctx
= (struct externalevent_iter_ctx
*)context
;
7281 (void)job_assumes(ctx
->j
, externalevent_new(ctx
->j
, ctx
->sys
, (char *)key
, obj
));
7284 struct externalevent
*
7285 externalevent_find(const char *sysname
, uint64_t id
)
7287 struct externalevent
*ei
= NULL
;
7289 struct eventsystem
*es
= eventsystem_find(sysname
);
7290 if (launchd_assumes(es
!= NULL
)) {
7291 LIST_FOREACH(ei
, &es
->events
, sys_le
) {
7301 struct eventsystem
*
7302 eventsystem_new(const char *name
)
7304 struct eventsystem
*es
= (struct eventsystem
*)calloc(1, sizeof(struct eventsystem
) + strlen(name
) + 1);
7305 if (launchd_assumes(es
!= NULL
)) {
7306 strcpy(es
->name
, name
);
7307 LIST_INSERT_HEAD(&_s_event_systems
, es
, global_le
);
7314 eventsystem_delete(struct eventsystem
*es
)
7316 struct externalevent
*ei
= NULL
;
7317 while ((ei
= LIST_FIRST(&es
->events
))) {
7318 externalevent_delete(ei
);
7321 LIST_REMOVE(es
, global_le
);
7327 eventsystem_setup(launch_data_t obj
, const char *key
, void *context
)
7329 job_t j
= (job_t
)context
;
7330 if (!job_assumes(j
, launch_data_get_type(obj
) == LAUNCH_DATA_DICTIONARY
)) {
7334 struct eventsystem
*sys
= eventsystem_find(key
);
7335 if (unlikely(sys
== NULL
)) {
7336 sys
= eventsystem_new(key
);
7337 job_log(j
, LOG_DEBUG
, "New event system: %s", key
);
7340 if (job_assumes(j
, sys
!= NULL
)) {
7341 struct externalevent_iter_ctx ctx
= {
7345 launch_data_dict_iterate(obj
, externalevent_setup
, &ctx
);
7346 sys
->has_updates
= true;
7350 struct eventsystem
*
7351 eventsystem_find(const char *name
)
7353 struct eventsystem
*esi
= NULL
;
7354 LIST_FOREACH(esi
, &_s_event_systems
, global_le
) {
7355 if (strcmp(name
, esi
->name
) == 0) {
7364 eventsystem_ping(void)
7366 /* We don't wrap this in an assumes() macro because we could potentially
7367 * call this function many times before the helper job gets back to us
7368 * and gives us another send-once right. So if it's MACH_PORT_NULL, that
7369 * means that we've sent a ping, but the helper hasn't yet checked in to
7370 * get the new set of notifications.
7372 if (_s_event_update_port
!= MACH_PORT_NULL
) {
7373 kern_return_t kr
= helper_downcall_ping(_s_event_update_port
);
7374 if (kr
!= KERN_SUCCESS
) {
7375 runtime_syslog(LOG_NOTICE
, "helper_downcall_ping(): kr = 0x%x", kr
);
7377 _s_event_update_port
= MACH_PORT_NULL
;
7382 jobmgr_dispatch_all_semaphores(jobmgr_t jm
)
7388 SLIST_FOREACH_SAFE(jmi
, &jm
->submgrs
, sle
, jmn
) {
7389 jobmgr_dispatch_all_semaphores(jmi
);
7392 LIST_FOREACH_SAFE(ji
, &jm
->jobs
, sle
, jn
) {
7393 if (!SLIST_EMPTY(&ji
->semaphores
)) {
7394 job_dispatch(ji
, false);
7400 cronemu(int mon
, int mday
, int hour
, int min
)
7402 struct tm workingtm
;
7406 workingtm
= *localtime(&now
);
7408 workingtm
.tm_isdst
= -1;
7409 workingtm
.tm_sec
= 0;
7412 while (!cronemu_mon(&workingtm
, mon
, mday
, hour
, min
)) {
7413 workingtm
.tm_year
++;
7414 workingtm
.tm_mon
= 0;
7415 workingtm
.tm_mday
= 1;
7416 workingtm
.tm_hour
= 0;
7417 workingtm
.tm_min
= 0;
7421 return mktime(&workingtm
);
7425 cronemu_wday(int wday
, int hour
, int min
)
7427 struct tm workingtm
;
7431 workingtm
= *localtime(&now
);
7433 workingtm
.tm_isdst
= -1;
7434 workingtm
.tm_sec
= 0;
7441 while (!(workingtm
.tm_wday
== wday
&& cronemu_hour(&workingtm
, hour
, min
))) {
7442 workingtm
.tm_mday
++;
7443 workingtm
.tm_hour
= 0;
7444 workingtm
.tm_min
= 0;
7448 return mktime(&workingtm
);
7452 cronemu_mon(struct tm
*wtm
, int mon
, int mday
, int hour
, int min
)
7455 struct tm workingtm
= *wtm
;
7458 while (!cronemu_mday(&workingtm
, mday
, hour
, min
)) {
7460 workingtm
.tm_mday
= 1;
7461 workingtm
.tm_hour
= 0;
7462 workingtm
.tm_min
= 0;
7463 carrytest
= workingtm
.tm_mon
;
7465 if (carrytest
!= workingtm
.tm_mon
) {
7473 if (mon
< wtm
->tm_mon
) {
7477 if (mon
> wtm
->tm_mon
) {
7484 return cronemu_mday(wtm
, mday
, hour
, min
);
7488 cronemu_mday(struct tm
*wtm
, int mday
, int hour
, int min
)
7491 struct tm workingtm
= *wtm
;
7494 while (!cronemu_hour(&workingtm
, hour
, min
)) {
7495 workingtm
.tm_mday
++;
7496 workingtm
.tm_hour
= 0;
7497 workingtm
.tm_min
= 0;
7498 carrytest
= workingtm
.tm_mday
;
7500 if (carrytest
!= workingtm
.tm_mday
) {
7508 if (mday
< wtm
->tm_mday
) {
7512 if (mday
> wtm
->tm_mday
) {
7513 wtm
->tm_mday
= mday
;
7518 return cronemu_hour(wtm
, hour
, min
);
7522 cronemu_hour(struct tm
*wtm
, int hour
, int min
)
7525 struct tm workingtm
= *wtm
;
7528 while (!cronemu_min(&workingtm
, min
)) {
7529 workingtm
.tm_hour
++;
7530 workingtm
.tm_min
= 0;
7531 carrytest
= workingtm
.tm_hour
;
7533 if (carrytest
!= workingtm
.tm_hour
) {
7541 if (hour
< wtm
->tm_hour
) {
7545 if (hour
> wtm
->tm_hour
) {
7546 wtm
->tm_hour
= hour
;
7550 return cronemu_min(wtm
, min
);
7554 cronemu_min(struct tm
*wtm
, int min
)
7560 if (min
< wtm
->tm_min
) {
7564 if (min
> wtm
->tm_min
) {
7572 job_mig_setup_shmem(job_t j
, mach_port_t
*shmem_port
)
7574 memory_object_size_t size_of_page
, size_of_page_orig
;
7575 vm_address_t vm_addr
;
7578 if (!launchd_assumes(j
!= NULL
)) {
7579 return BOOTSTRAP_NO_MEMORY
;
7582 if (unlikely(j
->anonymous
)) {
7583 job_log(j
, LOG_DEBUG
, "Anonymous job tried to setup shared memory");
7584 return BOOTSTRAP_NOT_PRIVILEGED
;
7587 if (unlikely(j
->shmem
)) {
7588 job_log(j
, LOG_ERR
, "Tried to setup shared memory more than once");
7589 return BOOTSTRAP_NOT_PRIVILEGED
;
7592 size_of_page_orig
= size_of_page
= getpagesize();
7594 kr
= vm_allocate(mach_task_self(), &vm_addr
, size_of_page
, true);
7596 if (!job_assumes(j
, kr
== 0)) {
7600 j
->shmem
= (typeof(j
->shmem
))vm_addr
;
7601 j
->shmem
->vp_shmem_standby_timeout
= j
->timeout
;
7603 kr
= mach_make_memory_entry_64(mach_task_self(), &size_of_page
,
7604 (memory_object_offset_t
)vm_addr
, VM_PROT_READ
|VM_PROT_WRITE
, shmem_port
, 0);
7606 if (job_assumes(j
, kr
== 0)) {
7607 (void)job_assumes(j
, size_of_page
== size_of_page_orig
);
7610 /* no need to inherit this in child processes */
7611 (void)job_assumes(j
, vm_inherit(mach_task_self(), (vm_address_t
)j
->shmem
, size_of_page_orig
, VM_INHERIT_NONE
) == 0);
7617 job_mig_create_server(job_t j
, cmd_t server_cmd
, uid_t server_uid
, boolean_t on_demand
, mach_port_t
*server_portp
)
7619 struct ldcred
*ldc
= runtime_get_caller_creds();
7622 if (!launchd_assumes(j
!= NULL
)) {
7623 return BOOTSTRAP_NO_MEMORY
;
7626 if (unlikely(j
->deny_job_creation
)) {
7627 return BOOTSTRAP_NOT_PRIVILEGED
;
7631 const char **argv
= (const char **)mach_cmd2argv(server_cmd
);
7632 if (unlikely(argv
== NULL
)) {
7633 return BOOTSTRAP_NO_MEMORY
;
7635 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_PATH
, argv
[0]) > 0)) {
7637 return BOOTSTRAP_NOT_PRIVILEGED
;
7642 job_log(j
, LOG_DEBUG
, "Server create attempt: %s", server_cmd
);
7645 if (ldc
->euid
|| ldc
->uid
) {
7646 job_log(j
, LOG_WARNING
, "Server create attempt moved to per-user launchd: %s", server_cmd
);
7647 return VPROC_ERR_TRY_PER_USER
;
7650 if (unlikely(server_uid
!= getuid())) {
7651 job_log(j
, LOG_WARNING
, "Server create: \"%s\": As UID %d, we will not be able to switch to UID %d",
7652 server_cmd
, getuid(), server_uid
);
7654 server_uid
= 0; /* zero means "do nothing" */
7657 js
= job_new_via_mach_init(j
, server_cmd
, server_uid
, on_demand
);
7659 if (unlikely(js
== NULL
)) {
7660 return BOOTSTRAP_NO_MEMORY
;
7663 *server_portp
= js
->j_port
;
7664 return BOOTSTRAP_SUCCESS
;
7668 job_mig_send_signal(job_t j
, mach_port_t srp
, name_t targetlabel
, int sig
)
7670 struct ldcred
*ldc
= runtime_get_caller_creds();
7673 if (!launchd_assumes(j
!= NULL
)) {
7674 return BOOTSTRAP_NO_MEMORY
;
7677 if (unlikely(ldc
->euid
!= 0 && ldc
->euid
!= getuid()) || j
->deny_job_creation
) {
7678 #if TARGET_OS_EMBEDDED
7679 if (!j
->embedded_special_privileges
) {
7680 return BOOTSTRAP_NOT_PRIVILEGED
;
7683 return BOOTSTRAP_NOT_PRIVILEGED
;
7688 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_NONE
) > 0)) {
7689 return BOOTSTRAP_NOT_PRIVILEGED
;
7693 if (unlikely(!(otherj
= job_find(NULL
, targetlabel
)))) {
7694 return BOOTSTRAP_UNKNOWN_SERVICE
;
7697 #if TARGET_OS_EMBEDDED
7698 if (j
->embedded_special_privileges
&& strcmp(j
->username
, otherj
->username
) != 0) {
7699 return BOOTSTRAP_NOT_PRIVILEGED
;
7703 if (sig
== VPROC_MAGIC_UNLOAD_SIGNAL
) {
7704 bool do_block
= otherj
->p
;
7706 if (otherj
->anonymous
) {
7707 return BOOTSTRAP_NOT_PRIVILEGED
;
7713 job_log(j
, LOG_DEBUG
, "Blocking MIG return of job_remove(): %s", otherj
->label
);
7714 /* this is messy. We shouldn't access 'otherj' after job_remove(), but we check otherj->p first... */
7715 (void)job_assumes(otherj
, waiting4removal_new(otherj
, srp
));
7716 return MIG_NO_REPLY
;
7720 } else if (sig
== VPROC_MAGIC_TRYKILL_SIGNAL
) {
7721 if (!j
->kill_via_shmem
) {
7722 return BOOTSTRAP_NOT_PRIVILEGED
;
7726 j
->sent_kill_via_shmem
= true;
7727 (void)job_assumes(j
, runtime_kill(otherj
->p
, SIGKILL
) != -1);
7731 #if !TARGET_OS_EMBEDDED
7732 if (__sync_bool_compare_and_swap(&j
->shmem
->vp_shmem_transaction_cnt
, 0, -1)) {
7733 j
->shmem
->vp_shmem_flags
|= VPROC_SHMEM_EXITING
;
7734 j
->sent_kill_via_shmem
= true;
7735 (void)job_assumes(j
, runtime_kill(otherj
->p
, SIGKILL
) != -1);
7739 return BOOTSTRAP_NOT_PRIVILEGED
;
7740 } else if (otherj
->p
) {
7741 (void)job_assumes(j
, runtime_kill(otherj
->p
, sig
) != -1);
7748 job_mig_log_forward(job_t j
, vm_offset_t inval
, mach_msg_type_number_t invalCnt
)
7750 struct ldcred
*ldc
= runtime_get_caller_creds();
7752 if (!launchd_assumes(j
!= NULL
)) {
7753 return BOOTSTRAP_NO_MEMORY
;
7756 if (!job_assumes(j
, j
->per_user
)) {
7757 return BOOTSTRAP_NOT_PRIVILEGED
;
7760 return runtime_log_forward(ldc
->euid
, ldc
->egid
, inval
, invalCnt
);
7764 job_mig_log_drain(job_t j
, mach_port_t srp
, vm_offset_t
*outval
, mach_msg_type_number_t
*outvalCnt
)
7766 struct ldcred
*ldc
= runtime_get_caller_creds();
7768 if (!launchd_assumes(j
!= NULL
)) {
7769 return BOOTSTRAP_NO_MEMORY
;
7772 if (unlikely(ldc
->euid
)) {
7773 return BOOTSTRAP_NOT_PRIVILEGED
;
7776 return runtime_log_drain(srp
, outval
, outvalCnt
);
7780 job_mig_swap_complex(job_t j
, vproc_gsk_t inkey
, vproc_gsk_t outkey
, vm_offset_t inval
, mach_msg_type_number_t invalCnt
, vm_offset_t
*outval
, mach_msg_type_number_t
*outvalCnt
)
7783 launch_data_t input_obj
= NULL
, output_obj
= NULL
;
7784 size_t data_offset
= 0;
7786 struct ldcred
*ldc
= runtime_get_caller_creds();
7788 if (!launchd_assumes(j
!= NULL
)) {
7789 return BOOTSTRAP_NO_MEMORY
;
7791 if (unlikely(inkey
&& ldc
->euid
&& ldc
->euid
!= getuid())) {
7792 return BOOTSTRAP_NOT_PRIVILEGED
;
7794 if (unlikely(inkey
&& outkey
&& !job_assumes(j
, inkey
== outkey
))) {
7798 if (inkey
&& outkey
) {
7799 action
= "Swapping";
7806 job_log(j
, LOG_DEBUG
, "%s key: %u", action
, inkey
? inkey
: outkey
);
7808 *outvalCnt
= 20 * 1024 * 1024;
7809 mig_allocate(outval
, *outvalCnt
);
7810 if (!job_assumes(j
, *outval
!= 0)) {
7814 /* Note to future maintainers: launch_data_unpack() does NOT return a heap object. The data
7815 * is decoded in-place. So do not call launch_data_free() on input_obj.
7817 runtime_ktrace0(RTKT_LAUNCHD_DATA_UNPACK
);
7818 if (unlikely(invalCnt
&& !job_assumes(j
, (input_obj
= launch_data_unpack((void *)inval
, invalCnt
, NULL
, 0, &data_offset
, NULL
)) != NULL
))) {
7823 case VPROC_GSK_ENVIRONMENT
:
7824 if (!job_assumes(j
, (output_obj
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
)))) {
7827 jobmgr_export_env_from_other_jobs(j
->mgr
, output_obj
);
7828 runtime_ktrace0(RTKT_LAUNCHD_DATA_PACK
);
7829 if (!job_assumes(j
, launch_data_pack(output_obj
, (void *)*outval
, *outvalCnt
, NULL
, NULL
) != 0)) {
7832 launch_data_free(output_obj
);
7834 case VPROC_GSK_ALLJOBS
:
7835 if (!job_assumes(j
, (output_obj
= job_export_all()) != NULL
)) {
7838 ipc_revoke_fds(output_obj
);
7839 runtime_ktrace0(RTKT_LAUNCHD_DATA_PACK
);
7840 packed_size
= launch_data_pack(output_obj
, (void *)*outval
, *outvalCnt
, NULL
, NULL
);
7841 if (!job_assumes(j
, packed_size
!= 0)) {
7844 launch_data_free(output_obj
);
7846 case VPROC_GSK_MGR_NAME
:
7847 if (!job_assumes(j
, (output_obj
= launch_data_new_string(j
->mgr
->name
)) != NULL
)) {
7850 packed_size
= launch_data_pack(output_obj
, (void *)*outval
, *outvalCnt
, NULL
, NULL
);
7851 if (!job_assumes(j
, packed_size
!= 0)) {
7855 launch_data_free(output_obj
);
7857 case VPROC_GSK_JOB_OVERRIDES_DB
:
7858 if (!job_assumes(j
, (output_obj
= launch_data_new_string(launchd_data_base_path(LAUNCHD_DB_TYPE_OVERRIDES
))) != NULL
)) {
7861 packed_size
= launch_data_pack(output_obj
, (void *)*outval
, *outvalCnt
, NULL
, NULL
);
7862 if (!job_assumes(j
, packed_size
!= 0)) {
7866 launch_data_free(output_obj
);
7868 case VPROC_GSK_JOB_CACHE_DB
:
7869 if (!job_assumes(j
, (output_obj
= launch_data_new_string(launchd_data_base_path(LAUNCHD_DB_TYPE_JOBCACHE
))) != NULL
)) {
7872 packed_size
= launch_data_pack(output_obj
, (void *)*outval
, *outvalCnt
, NULL
, NULL
);
7873 if (!job_assumes(j
, packed_size
!= 0)) {
7877 job_log(j
, LOG_DEBUG
, "Location of job cache database: %s", launch_data_get_string(output_obj
));
7879 launch_data_free(output_obj
);
7882 mig_deallocate(*outval
, *outvalCnt
);
7890 if (invalCnt
) switch (inkey
) {
7891 case VPROC_GSK_ENVIRONMENT
:
7892 if (launch_data_get_type(input_obj
) == LAUNCH_DATA_DICTIONARY
) {
7894 job_log(j
, LOG_INFO
, "Setting environment for a currently active job. This environment will take effect on the next invocation of the job.");
7896 launch_data_dict_iterate(input_obj
, envitem_setup_one_shot
, j
);
7905 mig_deallocate(inval
, invalCnt
);
7909 mig_deallocate(inval
, invalCnt
);
7911 mig_deallocate(*outval
, *outvalCnt
);
7914 launch_data_free(output_obj
);
7921 job_mig_swap_integer(job_t j
, vproc_gsk_t inkey
, vproc_gsk_t outkey
, int64_t inval
, int64_t *outval
)
7924 kern_return_t kr
= 0;
7925 struct ldcred
*ldc
= runtime_get_caller_creds();
7928 if (!launchd_assumes(j
!= NULL
)) {
7929 return BOOTSTRAP_NO_MEMORY
;
7932 if (unlikely(inkey
&& ldc
->euid
&& ldc
->euid
!= getuid())) {
7933 return BOOTSTRAP_NOT_PRIVILEGED
;
7936 if (unlikely(inkey
&& outkey
&& !job_assumes(j
, inkey
== outkey
))) {
7940 if (inkey
&& outkey
) {
7941 action
= "Swapping";
7948 job_log(j
, LOG_DEBUG
, "%s key: %u", action
, inkey
? inkey
: outkey
);
7951 case VPROC_GSK_ABANDON_PROCESS_GROUP
:
7952 *outval
= j
->abandon_pg
;
7954 case VPROC_GSK_LAST_EXIT_STATUS
:
7955 *outval
= j
->last_exit_status
;
7957 case VPROC_GSK_MGR_UID
:
7960 case VPROC_GSK_MGR_PID
:
7963 case VPROC_GSK_IS_MANAGED
:
7964 *outval
= j
->anonymous
? 0 : 1;
7966 case VPROC_GSK_BASIC_KEEPALIVE
:
7967 *outval
= !j
->ondemand
;
7969 case VPROC_GSK_START_INTERVAL
:
7970 *outval
= j
->start_interval
;
7972 case VPROC_GSK_IDLE_TIMEOUT
:
7973 *outval
= j
->timeout
;
7975 case VPROC_GSK_EXIT_TIMEOUT
:
7976 *outval
= j
->exit_timeout
;
7978 case VPROC_GSK_GLOBAL_LOG_MASK
:
7979 oldmask
= runtime_setlogmask(LOG_UPTO(LOG_DEBUG
));
7981 runtime_setlogmask(oldmask
);
7983 case VPROC_GSK_GLOBAL_UMASK
:
7988 case VPROC_GSK_TRANSACTIONS_ENABLED
:
7989 job_log(j
, LOG_DEBUG
, "Reading transaction model status.");
7990 *outval
= j
->kill_via_shmem
;
7992 case VPROC_GSK_WAITFORDEBUGGER
:
7993 *outval
= j
->wait4debugger
;
7995 case VPROC_GSK_EMBEDDEDROOTEQUIVALENT
:
7996 *outval
= j
->embedded_special_privileges
;
8007 case VPROC_GSK_ABANDON_PROCESS_GROUP
:
8008 j
->abandon_pg
= (bool)inval
;
8010 case VPROC_GSK_GLOBAL_ON_DEMAND
:
8011 job_log(j
, LOG_DEBUG
, "Job is setting global on-demand mode to %s (j->forced_peers_to_demand_mode = %s)", (bool)inval
? "true" : "false", j
->forced_peers_to_demand_mode
? "true" : "false");
8012 kr
= job_set_global_on_demand(j
, (bool)inval
) ? 0 : 1;
8014 case VPROC_GSK_BASIC_KEEPALIVE
:
8015 j
->ondemand
= !inval
;
8017 case VPROC_GSK_START_INTERVAL
:
8018 if (inval
> UINT32_MAX
|| inval
< 0) {
8021 if (j
->start_interval
== 0) {
8022 runtime_add_weak_ref();
8024 j
->start_interval
= (typeof(j
->start_interval
)) inval
;
8025 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->start_interval
, EVFILT_TIMER
, EV_ADD
, NOTE_SECONDS
, j
->start_interval
, j
) != -1);
8026 } else if (j
->start_interval
) {
8027 (void)job_assumes(j
, kevent_mod((uintptr_t)&j
->start_interval
, EVFILT_TIMER
, EV_DELETE
, 0, 0, NULL
) != -1);
8028 if (j
->start_interval
!= 0) {
8029 runtime_del_weak_ref();
8031 j
->start_interval
= 0;
8034 case VPROC_GSK_IDLE_TIMEOUT
:
8035 if (inval
< 0 || inval
> UINT32_MAX
) {
8038 j
->timeout
= (typeof(j
->timeout
)) inval
;
8041 case VPROC_GSK_EXIT_TIMEOUT
:
8042 if (inval
< 0 || inval
> UINT32_MAX
) {
8045 j
->exit_timeout
= (typeof(j
->exit_timeout
)) inval
;
8048 case VPROC_GSK_GLOBAL_LOG_MASK
:
8049 if (inval
< 0 || inval
> UINT32_MAX
) {
8052 runtime_setlogmask((int) inval
);
8055 case VPROC_GSK_GLOBAL_UMASK
:
8056 launchd_assert(sizeof (mode_t
) == 2);
8057 if (inval
< 0 || inval
> UINT16_MAX
) {
8061 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_NONE
) > 0)) {
8064 umask((mode_t
) inval
);
8069 case VPROC_GSK_TRANSACTIONS_ENABLED
:
8070 if (!job_assumes(j
, inval
!= 0)) {
8071 job_log(j
, LOG_WARNING
, "Attempt to unregister from transaction model. This is not supported.");
8074 j
->kill_via_shmem
= (bool)inval
;
8077 case VPROC_GSK_WEIRD_BOOTSTRAP
:
8078 if (job_assumes(j
, j
->weird_bootstrap
)) {
8079 job_log(j
, LOG_DEBUG
, "Unsetting weird bootstrap.");
8081 mach_msg_size_t mxmsgsz
= (typeof(mxmsgsz
)) sizeof(union __RequestUnion__job_mig_protocol_vproc_subsystem
);
8083 if (job_mig_protocol_vproc_subsystem
.maxsize
> mxmsgsz
) {
8084 mxmsgsz
= job_mig_protocol_vproc_subsystem
.maxsize
;
8087 (void)job_assumes(j
, runtime_add_mport(j
->mgr
->jm_port
, protocol_vproc_server
, mxmsgsz
) == KERN_SUCCESS
);
8088 j
->weird_bootstrap
= false;
8091 case VPROC_GSK_WAITFORDEBUGGER
:
8092 j
->wait4debugger_oneshot
= inval
;
8094 case VPROC_GSK_PERUSER_SUSPEND
:
8095 if (job_assumes(j
, pid1_magic
&& ldc
->euid
== 0)) {
8096 mach_port_t junk
= MACH_PORT_NULL
;
8097 job_t jpu
= jobmgr_lookup_per_user_context_internal(j
, (uid_t
)inval
, &junk
);
8098 if (job_assumes(j
, jpu
!= NULL
)) {
8099 struct suspended_peruser
*spi
= NULL
;
8100 LIST_FOREACH(spi
, &j
->suspended_perusers
, sle
) {
8101 if ((int64_t)(spi
->j
->mach_uid
) == inval
) {
8102 job_log(j
, LOG_WARNING
, "Job tried to suspend per-user launchd for UID %lli twice.", inval
);
8108 job_log(j
, LOG_INFO
, "Job is suspending the per-user launchd for UID %lli.", inval
);
8109 spi
= (struct suspended_peruser
*)calloc(sizeof(struct suspended_peruser
), 1);
8110 if (job_assumes(j
, spi
!= NULL
)) {
8111 /* Stop listening for events.
8113 * See <rdar://problem/9014146>.
8115 if (jpu
->peruser_suspend_count
== 0) {
8120 spi
->j
->peruser_suspend_count
++;
8121 LIST_INSERT_HEAD(&j
->suspended_perusers
, spi
, sle
);
8125 kr
= BOOTSTRAP_NO_MEMORY
;
8133 case VPROC_GSK_PERUSER_RESUME
:
8134 if (job_assumes(j
, pid1_magic
== true)) {
8135 struct suspended_peruser
*spi
= NULL
, *spt
= NULL
;
8136 LIST_FOREACH_SAFE(spi
, &j
->suspended_perusers
, sle
, spt
) {
8137 if ((int64_t)(spi
->j
->mach_uid
) == inval
) {
8138 spi
->j
->peruser_suspend_count
--;
8139 LIST_REMOVE(spi
, sle
);
8140 job_log(j
, LOG_INFO
, "Job is resuming the per-user launchd for UID %lli.", inval
);
8145 if (!job_assumes(j
, spi
!= NULL
)) {
8146 job_log(j
, LOG_WARNING
, "Job tried to resume per-user launchd for UID %lli that it did not suspend.", inval
);
8147 kr
= BOOTSTRAP_NOT_PRIVILEGED
;
8148 } else if (spi
->j
->peruser_suspend_count
== 0) {
8150 job_dispatch(spi
->j
, false);
8168 job_mig_post_fork_ping(job_t j
, task_t child_task
, mach_port_t
*asport
)
8170 struct machservice
*ms
;
8172 if (!launchd_assumes(j
!= NULL
)) {
8173 return BOOTSTRAP_NO_MEMORY
;
8176 job_log(j
, LOG_DEBUG
, "Post fork ping.");
8178 job_setup_exception_port(j
, child_task
);
8180 SLIST_FOREACH(ms
, &special_ports
, special_port_sle
) {
8181 if (j
->per_user
&& (ms
->special_port_num
!= TASK_ACCESS_PORT
)) {
8182 /* The TASK_ACCESS_PORT funny business is to workaround 5325399. */
8186 errno
= task_set_special_port(child_task
, ms
->special_port_num
, ms
->port
);
8188 if (unlikely(errno
)) {
8189 int desired_log_level
= LOG_ERR
;
8194 desired_log_level
= LOG_WARNING
;
8196 if (ms
->special_port_num
== TASK_SEATBELT_PORT
) {
8197 desired_log_level
= LOG_DEBUG
;
8201 job_log(j
, desired_log_level
, "Could not setup Mach task special port %u: %s", ms
->special_port_num
, mach_error_string(errno
));
8205 /* MIG will not zero-initialize this pointer, so we must always do so. See
8206 * <rdar://problem/8562593>.
8208 *asport
= MACH_PORT_NULL
;
8209 #if !TARGET_OS_EMBEDDED
8210 if (!j
->anonymous
) {
8211 /* XPC services will spawn into the root security session by default.
8212 * xpcproxy will switch them away if needed.
8214 if (!(j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
)) {
8215 job_log(j
, LOG_DEBUG
, "Returning j->asport: %u", j
->asport
);
8216 *asport
= j
->asport
;
8220 (void)job_assumes(j
, launchd_mport_deallocate(child_task
) == KERN_SUCCESS
);
8226 job_mig_reboot2(job_t j
, uint64_t flags
)
8228 char who_started_the_reboot
[2048] = "";
8229 struct proc_bsdshortinfo proc
;
8230 struct ldcred
*ldc
= runtime_get_caller_creds();
8233 if (!launchd_assumes(j
!= NULL
)) {
8234 return BOOTSTRAP_NO_MEMORY
;
8237 if (unlikely(!pid1_magic
)) {
8238 return BOOTSTRAP_NOT_PRIVILEGED
;
8241 #if !TARGET_OS_EMBEDDED
8242 if (unlikely(ldc
->euid
)) {
8244 if (unlikely(ldc
->euid
) && !j
->embedded_special_privileges
) {
8246 return BOOTSTRAP_NOT_PRIVILEGED
;
8249 for (pid_to_log
= ldc
->pid
; pid_to_log
; pid_to_log
= proc
.pbsi_ppid
) {
8251 if (proc_pidinfo(pid_to_log
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
8252 if (errno
!= ESRCH
) {
8253 job_assumes(j
, errno
== 0);
8258 if (!job_assumes(j
, pid_to_log
!= (pid_t
)proc
.pbsi_ppid
)) {
8259 job_log(j
, LOG_WARNING
, "Job which is its own parent started reboot.");
8260 snprintf(who_started_the_reboot
, sizeof(who_started_the_reboot
), "%s[%u]->%s[%u]->%s[%u]->...", proc
.pbsi_comm
, pid_to_log
, proc
.pbsi_comm
, pid_to_log
, proc
.pbsi_comm
, pid_to_log
);
8264 who_offset
= strlen(who_started_the_reboot
);
8265 snprintf(who_started_the_reboot
+ who_offset
, sizeof(who_started_the_reboot
) - who_offset
,
8266 " %s[%u]%s", proc
.pbsi_comm
, pid_to_log
, proc
.pbsi_ppid
? " ->" : "");
8269 root_jobmgr
->reboot_flags
= (int)flags
;
8270 job_log(j
, LOG_DEBUG
, "reboot2() initiated by:%s", who_started_the_reboot
);
8277 job_mig_getsocket(job_t j
, name_t spr
)
8279 if (!launchd_assumes(j
!= NULL
)) {
8280 return BOOTSTRAP_NO_MEMORY
;
8283 if (j
->deny_job_creation
) {
8284 return BOOTSTRAP_NOT_PRIVILEGED
;
8288 struct ldcred
*ldc
= runtime_get_caller_creds();
8289 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_NONE
) > 0)) {
8290 return BOOTSTRAP_NOT_PRIVILEGED
;
8296 if (unlikely(!sockpath
)) {
8297 return BOOTSTRAP_NO_MEMORY
;
8300 strncpy(spr
, sockpath
, sizeof(name_t
));
8302 return BOOTSTRAP_SUCCESS
;
8306 job_mig_log(job_t j
, int pri
, int err
, logmsg_t msg
)
8308 if (!launchd_assumes(j
!= NULL
)) {
8309 return BOOTSTRAP_NO_MEMORY
;
8312 if ((errno
= err
)) {
8313 job_log_error(j
, pri
, "%s", msg
);
8315 job_log(j
, pri
, "%s", msg
);
8322 jobmgr_lookup_per_user_context_internal(job_t j
, uid_t which_user
, mach_port_t
*mp
)
8325 LIST_FOREACH(ji
, &root_jobmgr
->jobs
, sle
) {
8326 if (!ji
->per_user
) {
8329 if (ji
->mach_uid
!= which_user
) {
8332 if (SLIST_EMPTY(&ji
->machservices
)) {
8335 if (!SLIST_FIRST(&ji
->machservices
)->per_user_hack
) {
8341 if (unlikely(ji
== NULL
)) {
8342 struct machservice
*ms
;
8345 job_log(j
, LOG_DEBUG
, "Creating per user launchd job for UID: %u", which_user
);
8347 sprintf(lbuf
, "com.apple.launchd.peruser.%u", which_user
);
8349 ji
= job_new(root_jobmgr
, lbuf
, "/sbin/launchd", NULL
);
8352 auditinfo_addr_t auinfo
= {
8353 .ai_termid
= { .at_type
= AU_IPv4
},
8354 .ai_auid
= which_user
,
8355 .ai_asid
= AU_ASSIGN_ASID
,
8358 if (setaudit_addr(&auinfo
, sizeof(auinfo
)) == 0) {
8359 job_log(ji
, LOG_DEBUG
, "Created new security session for per-user launchd: %u", auinfo
.ai_asid
);
8360 (void)job_assumes(ji
, (ji
->asport
= audit_session_self()) != MACH_PORT_NULL
);
8362 /* Kinda lame that we have to do this, but we can't create an
8363 * audit session without joining it.
8365 (void)job_assumes(ji
, audit_session_join(g_audit_session_port
));
8366 ji
->asid
= auinfo
.ai_asid
;
8368 job_log(ji
, LOG_WARNING
, "Could not set audit session!");
8373 ji
->mach_uid
= which_user
;
8374 ji
->per_user
= true;
8375 ji
->kill_via_shmem
= true;
8378 char pu_db
[PATH_MAX
];
8379 snprintf(pu_db
, sizeof(pu_db
), LAUNCHD_DB_PREFIX
"/%s", lbuf
);
8381 bool created
= false;
8382 int err
= stat(pu_db
, &sb
);
8383 if ((err
== -1 && errno
== ENOENT
) || (err
== 0 && !S_ISDIR(sb
.st_mode
))) {
8385 char move_aside
[PATH_MAX
];
8386 snprintf(move_aside
, sizeof(move_aside
), LAUNCHD_DB_PREFIX
"/%s.movedaside", lbuf
);
8388 (void)job_assumes(ji
, rename(pu_db
, move_aside
) != -1);
8391 (void)job_assumes(ji
, mkdir(pu_db
, S_IRWXU
) != -1);
8392 (void)job_assumes(ji
, chown(pu_db
, which_user
, 0) != -1);
8397 if (!job_assumes(ji
, sb
.st_uid
== which_user
)) {
8398 (void)job_assumes(ji
, chown(pu_db
, which_user
, 0) != -1);
8400 if (!job_assumes(ji
, sb
.st_gid
== 0)) {
8401 (void)job_assumes(ji
, chown(pu_db
, which_user
, 0) != -1);
8403 if (!job_assumes(ji
, sb
.st_mode
== (S_IRWXU
| S_IFDIR
))) {
8404 (void)job_assumes(ji
, chmod(pu_db
, S_IRWXU
) != -1);
8408 if ((ms
= machservice_new(ji
, lbuf
, mp
, false)) == NULL
) {
8412 ms
->per_user_hack
= true;
8415 ji
= job_dispatch(ji
, false);
8419 *mp
= machservice_port(SLIST_FIRST(&ji
->machservices
));
8420 job_log(j
, LOG_DEBUG
, "Per user launchd job found for UID: %u", which_user
);
8427 job_mig_lookup_per_user_context(job_t j
, uid_t which_user
, mach_port_t
*up_cont
)
8429 struct ldcred
*ldc
= runtime_get_caller_creds();
8432 #if TARGET_OS_EMBEDDED
8433 /* There is no need for per-user launchd's on embedded. */
8434 job_log(j
, LOG_ERR
, "Per-user launchds are not supported on this platform.");
8435 return BOOTSTRAP_NOT_PRIVILEGED
;
8439 if (unlikely(sandbox_check(ldc
->pid
, "mach-per-user-lookup", SANDBOX_FILTER_NONE
) > 0)) {
8440 return BOOTSTRAP_NOT_PRIVILEGED
;
8444 if (!launchd_assumes(j
!= NULL
)) {
8445 return BOOTSTRAP_NO_MEMORY
;
8448 job_log(j
, LOG_INFO
, "Looking up per user launchd for UID: %u", which_user
);
8450 if (unlikely(!pid1_magic
)) {
8451 job_log(j
, LOG_ERR
, "Only PID 1 supports per user launchd lookups.");
8452 return BOOTSTRAP_NOT_PRIVILEGED
;
8455 if (ldc
->euid
|| ldc
->uid
) {
8456 which_user
= ldc
->euid
?: ldc
->uid
;
8459 *up_cont
= MACH_PORT_NULL
;
8461 jpu
= jobmgr_lookup_per_user_context_internal(j
, which_user
, up_cont
);
8467 job_mig_check_in2(job_t j
, name_t servicename
, mach_port_t
*serviceportp
, uuid_t instance_id
, uint64_t flags
)
8469 bool per_pid_service
= flags
& BOOTSTRAP_PER_PID_SERVICE
;
8470 bool strict
= flags
& BOOTSTRAP_STRICT_CHECKIN
;
8471 struct ldcred
*ldc
= runtime_get_caller_creds();
8472 struct machservice
*ms
= NULL
;
8475 if (!launchd_assumes(j
!= NULL
)) {
8476 return BOOTSTRAP_NO_MEMORY
;
8479 if (j
->dedicated_instance
) {
8480 struct machservice
*msi
= NULL
;
8481 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
8482 if (strncmp(servicename
, msi
->name
, sizeof(name_t
) - 1) == 0) {
8483 uuid_copy(instance_id
, j
->instance_id
);
8489 ms
= jobmgr_lookup_service(j
->mgr
, servicename
, false, per_pid_service
? ldc
->pid
: 0);
8493 if (likely(ms
!= NULL
)) {
8495 return BOOTSTRAP_NOT_PRIVILEGED
;
8496 } else if (ms
->isActive
) {
8497 return BOOTSTRAP_SERVICE_ACTIVE
;
8500 return BOOTSTRAP_UNKNOWN_SERVICE
;
8502 } else if (ms
== NULL
) {
8503 if (job_assumes(j
, !j
->dedicated_instance
)) {
8504 *serviceportp
= MACH_PORT_NULL
;
8506 if (unlikely((ms
= machservice_new(j
, servicename
, serviceportp
, per_pid_service
)) == NULL
)) {
8507 return BOOTSTRAP_NO_MEMORY
;
8510 /* Treat this like a legacy job. */
8511 if (!j
->legacy_mach_job
) {
8512 ms
->isActive
= true;
8516 if (!(j
->anonymous
|| j
->legacy_LS_job
|| j
->legacy_mach_job
)) {
8517 job_log(j
, LOG_SCOLDING
, "Please add the following service to the configuration file for this job: %s", servicename
);
8520 return BOOTSTRAP_UNKNOWN_SERVICE
;
8523 if (unlikely((jo
= machservice_job(ms
)) != j
)) {
8524 static pid_t last_warned_pid
;
8526 if (last_warned_pid
!= ldc
->pid
) {
8527 job_log(jo
, LOG_WARNING
, "The following job tried to hijack the service \"%s\" from this job: %s", servicename
, j
->label
);
8528 last_warned_pid
= ldc
->pid
;
8531 return BOOTSTRAP_NOT_PRIVILEGED
;
8533 if (unlikely(machservice_active(ms
))) {
8534 job_log(j
, LOG_WARNING
, "Check-in of Mach service failed. Already active: %s", servicename
);
8535 return BOOTSTRAP_SERVICE_ACTIVE
;
8540 machservice_request_notifications(ms
);
8542 job_log(j
, LOG_INFO
, "Check-in of service: %s", servicename
);
8544 *serviceportp
= machservice_port(ms
);
8545 return BOOTSTRAP_SUCCESS
;
8549 job_mig_register2(job_t j
, name_t servicename
, mach_port_t serviceport
, uint64_t flags
)
8551 struct machservice
*ms
;
8552 struct ldcred
*ldc
= runtime_get_caller_creds();
8554 if (!launchd_assumes(j
!= NULL
)) {
8555 return BOOTSTRAP_NO_MEMORY
;
8558 if (!(flags
& BOOTSTRAP_PER_PID_SERVICE
) && !j
->legacy_LS_job
) {
8559 job_log(j
, LOG_SCOLDING
, "Performance: bootstrap_register() is deprecated. Service: %s", servicename
);
8562 job_log(j
, LOG_DEBUG
, "%sMach service registration attempt: %s", flags
& BOOTSTRAP_PER_PID_SERVICE
? "Per PID " : "", servicename
);
8564 /* 5641783 for the embedded hack */
8565 #if !TARGET_OS_EMBEDDED
8567 * From a per-user/session launchd's perspective, SecurityAgent (UID
8568 * 92) is a rogue application (not our UID, not root and not a child of
8569 * us). We'll have to reconcile this design friction at a later date.
8571 if (unlikely(j
->anonymous
&& j
->mgr
->parentmgr
== NULL
&& ldc
->uid
!= 0 && ldc
->uid
!= getuid() && ldc
->uid
!= 92)) {
8573 return VPROC_ERR_TRY_PER_USER
;
8575 return BOOTSTRAP_NOT_PRIVILEGED
;
8580 ms
= jobmgr_lookup_service(j
->mgr
, servicename
, false, flags
& BOOTSTRAP_PER_PID_SERVICE
? ldc
->pid
: 0);
8583 if (machservice_job(ms
) != j
) {
8584 return BOOTSTRAP_NOT_PRIVILEGED
;
8586 if (machservice_active(ms
)) {
8587 job_log(j
, LOG_DEBUG
, "Mach service registration failed. Already active: %s", servicename
);
8588 return BOOTSTRAP_SERVICE_ACTIVE
;
8590 if (ms
->recv
&& (serviceport
!= MACH_PORT_NULL
)) {
8591 job_log(j
, LOG_ERR
, "bootstrap_register() erroneously called instead of bootstrap_check_in(). Mach service: %s", servicename
);
8592 return BOOTSTRAP_NOT_PRIVILEGED
;
8595 machservice_delete(j
, ms
, false);
8598 if (likely(serviceport
!= MACH_PORT_NULL
)) {
8599 if (likely(ms
= machservice_new(j
, servicename
, &serviceport
, flags
& BOOTSTRAP_PER_PID_SERVICE
? true : false))) {
8600 machservice_request_notifications(ms
);
8602 return BOOTSTRAP_NO_MEMORY
;
8607 return BOOTSTRAP_SUCCESS
;
8611 job_mig_look_up2(job_t j
, mach_port_t srp
, name_t servicename
, mach_port_t
*serviceportp
, pid_t target_pid
, uuid_t instance_id
, uint64_t flags
)
8613 struct machservice
*ms
= NULL
;
8614 struct ldcred
*ldc
= runtime_get_caller_creds();
8616 bool per_pid_lookup
= flags
& BOOTSTRAP_PER_PID_SERVICE
;
8617 bool specific_instance
= flags
& BOOTSTRAP_SPECIFIC_INSTANCE
;
8618 bool strict_lookup
= flags
& BOOTSTRAP_STRICT_LOOKUP
;
8619 bool privileged
= flags
& BOOTSTRAP_PRIVILEGED_SERVER
;
8621 if (!launchd_assumes(j
!= NULL
)) {
8622 return BOOTSTRAP_NO_MEMORY
;
8625 bool xpc_req
= j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
;
8627 /* 5641783 for the embedded hack */
8628 #if !TARGET_OS_EMBEDDED
8629 if (unlikely(pid1_magic
&& j
->anonymous
&& j
->mgr
->parentmgr
== NULL
&& ldc
->uid
!= 0 && ldc
->euid
!= 0)) {
8630 return VPROC_ERR_TRY_PER_USER
;
8635 /* We don't do sandbox checking for XPC domains because, by definition, all
8636 * the services within your domain should be accessibly to you.
8638 if (!xpc_req
&& unlikely(sandbox_check(ldc
->pid
, "mach-lookup", per_pid_lookup
? SANDBOX_FILTER_LOCAL_NAME
: SANDBOX_FILTER_GLOBAL_NAME
, servicename
) > 0)) {
8639 return BOOTSTRAP_NOT_PRIVILEGED
;
8643 if (per_pid_lookup
) {
8644 ms
= jobmgr_lookup_service(j
->mgr
, servicename
, false, target_pid
);
8647 /* Requests from XPC domains stay local. */
8648 ms
= jobmgr_lookup_service(j
->mgr
, servicename
, false, 0);
8650 /* A strict lookup which is privileged won't even bother trying to
8651 * find a service if we're not hosting the root Mach bootstrap.
8653 if (strict_lookup
&& privileged
) {
8654 if (inherited_bootstrap_port
== MACH_PORT_NULL
) {
8655 ms
= jobmgr_lookup_service(j
->mgr
, servicename
, true, 0);
8658 ms
= jobmgr_lookup_service(j
->mgr
, servicename
, true, 0);
8664 ms
= ms
->alias
? ms
->alias
: ms
;
8665 if (unlikely(specific_instance
&& ms
->job
->multiple_instances
)) {
8667 job_t instance
= NULL
;
8668 LIST_FOREACH(ji
, &ms
->job
->subjobs
, subjob_sle
) {
8669 if (uuid_compare(instance_id
, ji
->instance_id
) == 0) {
8675 if (unlikely(instance
== NULL
)) {
8676 job_log(ms
->job
, LOG_DEBUG
, "Creating new instance of job based on lookup of service %s", ms
->name
);
8677 instance
= job_new_subjob(ms
->job
, instance_id
);
8678 if (job_assumes(j
, instance
!= NULL
)) {
8679 /* Disable this support for now. We only support having
8680 * multi-instance jobs within private XPC domains.
8683 /* If the job is multi-instance, in a singleton XPC domain
8684 * and the request is not coming from within that singleton
8685 * domain, we need to alias the new job into the requesting
8688 if (!j
->mgr
->xpc_singleton
&& xpc_req
) {
8689 (void)job_assumes(instance
, job_new_alias(j
->mgr
, instance
));
8692 job_dispatch(instance
, false);
8697 if (job_assumes(j
, instance
!= NULL
)) {
8698 struct machservice
*msi
= NULL
;
8699 SLIST_FOREACH(msi
, &instance
->machservices
, sle
) {
8700 /* sizeof(servicename) will return the size of a pointer, even though it's
8701 * an array type, because when passing arrays as parameters in C, they
8702 * implicitly degrade to pointers.
8704 if (strncmp(servicename
, msi
->name
, sizeof(name_t
) - 1) == 0) {
8711 if (machservice_hidden(ms
) && !machservice_active(ms
)) {
8713 } else if (unlikely(ms
->per_user_hack
)) {
8720 (void)job_assumes(j
, machservice_port(ms
) != MACH_PORT_NULL
);
8721 job_log(j
, LOG_DEBUG
, "%sMach service lookup: %s", per_pid_lookup
? "Per PID " : "", servicename
);
8723 if (unlikely(!per_pid_lookup
&& j
->lastlookup
== ms
&& j
->lastlookup_gennum
== ms
->gen_num
&& !j
->per_user
)) {
8724 /* we need to think more about the per_pid_lookup logic before logging about repeated lookups */
8725 job_log(j
, LOG_DEBUG
, "Performance: Please fix the framework that talks to \"%s\" to cache the Mach port for service: %s", ms
->job
->label
, servicename
);
8729 j
->lastlookup_gennum
= ms
->gen_num
;
8731 *serviceportp
= machservice_port(ms
);
8733 kr
= BOOTSTRAP_SUCCESS
;
8734 } else if (strict_lookup
&& !privileged
) {
8735 /* Hack: We need to simulate XPC's desire not to establish a hierarchy. So if
8736 * XPC is doing the lookup, and it's not a privileged lookup, we won't forward.
8737 * But if it is a privileged lookup (that is, was looked up in XPC_DOMAIN_LOCAL_SYSTEM)
8738 * then we must forward.
8740 return BOOTSTRAP_UNKNOWN_SERVICE
;
8741 } else if (inherited_bootstrap_port
!= MACH_PORT_NULL
) {
8742 /* Requests from within an XPC domain don't get forwarded. */
8743 job_log(j
, LOG_DEBUG
, "Mach service lookup forwarded: %s", servicename
);
8744 /* Clients potentially check the audit token of the reply to verify that the returned send right is trustworthy. */
8745 (void)job_assumes(j
, vproc_mig_look_up2_forward(inherited_bootstrap_port
, srp
, servicename
, target_pid
, instance_id
, flags
) == 0);
8746 /* The previous routine moved the reply port, we're forced to return MIG_NO_REPLY now */
8747 return MIG_NO_REPLY
;
8748 } else if (pid1_magic
&& j
->anonymous
&& ldc
->euid
>= 500 && strcasecmp(j
->mgr
->name
, VPROCMGR_SESSION_LOGINWINDOW
) == 0) {
8750 * 5240036 Should start background session when a lookup of CCacheServer occurs
8752 * This is a total hack. We sniff out loginwindow session, and attempt to guess what it is up to.
8753 * If we find a EUID that isn't root, we force it over to the per-user context.
8755 return VPROC_ERR_TRY_PER_USER
;
8757 job_log(j
, LOG_DEBUG
, "%sMach service lookup failed: %s", per_pid_lookup
? "Per PID " : "", servicename
);
8758 kr
= BOOTSTRAP_UNKNOWN_SERVICE
;
8765 job_mig_parent(job_t j
, mach_port_t srp
, mach_port_t
*parentport
)
8767 if (!launchd_assumes(j
!= NULL
)) {
8768 return BOOTSTRAP_NO_MEMORY
;
8771 job_log(j
, LOG_DEBUG
, "Requested parent bootstrap port");
8772 jobmgr_t jm
= j
->mgr
;
8774 if (jobmgr_parent(jm
)) {
8775 *parentport
= jobmgr_parent(jm
)->jm_port
;
8776 } else if (MACH_PORT_NULL
== inherited_bootstrap_port
) {
8777 *parentport
= jm
->jm_port
;
8779 (void)job_assumes(j
, vproc_mig_parent_forward(inherited_bootstrap_port
, srp
) == 0);
8780 /* The previous routine moved the reply port, we're forced to return MIG_NO_REPLY now */
8781 return MIG_NO_REPLY
;
8783 return BOOTSTRAP_SUCCESS
;
8787 job_mig_get_root_bootstrap(job_t j
, mach_port_t
*rootbsp
)
8790 return BOOTSTRAP_NO_MEMORY
;
8793 if (inherited_bootstrap_port
== MACH_PORT_NULL
) {
8794 *rootbsp
= root_jobmgr
->jm_port
;
8795 (void)job_assumes(j
, launchd_mport_make_send(root_jobmgr
->jm_port
) == KERN_SUCCESS
);
8797 *rootbsp
= inherited_bootstrap_port
;
8798 (void)job_assumes(j
, launchd_mport_copy_send(inherited_bootstrap_port
) == KERN_SUCCESS
);
8801 return BOOTSTRAP_SUCCESS
;
8805 job_mig_info(job_t j
, name_array_t
*servicenamesp
, unsigned int *servicenames_cnt
, name_array_t
*servicejobsp
, unsigned int *servicejobs_cnt
, bootstrap_status_array_t
*serviceactivesp
, unsigned int *serviceactives_cnt
, uint64_t flags
)
8807 name_array_t service_names
= NULL
;
8808 name_array_t service_jobs
= NULL
;
8809 bootstrap_status_array_t service_actives
= NULL
;
8810 unsigned int cnt
= 0, cnt2
= 0;
8813 if (!launchd_assumes(j
!= NULL
)) {
8814 return BOOTSTRAP_NO_MEMORY
;
8817 if (g_flat_mach_namespace
) {
8818 if ((j
->mgr
->properties
& BOOTSTRAP_PROPERTY_EXPLICITSUBSET
) || (flags
& BOOTSTRAP_FORCE_LOCAL
)) {
8828 struct machservice
*msi
= NULL
;
8829 for (i
= 0; i
< MACHSERVICE_HASH_SIZE
; i
++) {
8830 LIST_FOREACH(msi
, &jm
->ms_hash
[i
], name_hash_sle
) {
8831 cnt
+= !msi
->per_pid
? 1 : 0;
8839 mig_allocate((vm_address_t
*)&service_names
, cnt
* sizeof(service_names
[0]));
8840 if (!job_assumes(j
, service_names
!= NULL
)) {
8844 mig_allocate((vm_address_t
*)&service_jobs
, cnt
* sizeof(service_jobs
[0]));
8845 if (!job_assumes(j
, service_jobs
!= NULL
)) {
8849 mig_allocate((vm_address_t
*)&service_actives
, cnt
* sizeof(service_actives
[0]));
8850 if (!job_assumes(j
, service_actives
!= NULL
)) {
8854 for (i
= 0; i
< MACHSERVICE_HASH_SIZE
; i
++) {
8855 LIST_FOREACH(msi
, &jm
->ms_hash
[i
], name_hash_sle
) {
8856 if (!msi
->per_pid
) {
8857 strlcpy(service_names
[cnt2
], machservice_name(msi
), sizeof(service_names
[0]));
8858 msi
= msi
->alias
? msi
->alias
: msi
;
8859 if (msi
->job
->mgr
->shortdesc
) {
8860 strlcpy(service_jobs
[cnt2
], msi
->job
->mgr
->shortdesc
, sizeof(service_jobs
[0]));
8862 strlcpy(service_jobs
[cnt2
], msi
->job
->label
, sizeof(service_jobs
[0]));
8864 service_actives
[cnt2
] = machservice_status(msi
);
8870 (void)job_assumes(j
, cnt
== cnt2
);
8873 *servicenamesp
= service_names
;
8874 *servicejobsp
= service_jobs
;
8875 *serviceactivesp
= service_actives
;
8876 *servicenames_cnt
= *servicejobs_cnt
= *serviceactives_cnt
= cnt
;
8878 return BOOTSTRAP_SUCCESS
;
8881 if (service_names
) {
8882 mig_deallocate((vm_address_t
)service_names
, cnt
* sizeof(service_names
[0]));
8885 mig_deallocate((vm_address_t
)service_jobs
, cnt
* sizeof(service_jobs
[0]));
8887 if (service_actives
) {
8888 mig_deallocate((vm_address_t
)service_actives
, cnt
* sizeof(service_actives
[0]));
8891 return BOOTSTRAP_NO_MEMORY
;
8895 job_mig_lookup_children(job_t j
, mach_port_array_t
*child_ports
, mach_msg_type_number_t
*child_ports_cnt
, name_array_t
*child_names
, mach_msg_type_number_t
*child_names_cnt
, bootstrap_property_array_t
*child_properties
,mach_msg_type_number_t
*child_properties_cnt
)
8897 kern_return_t kr
= BOOTSTRAP_NO_MEMORY
;
8898 if (!launchd_assumes(j
!= NULL
)) {
8899 return BOOTSTRAP_NO_MEMORY
;
8902 struct ldcred
*ldc
= runtime_get_caller_creds();
8904 /* Only allow root processes to look up children, even if we're in the per-user launchd.
8905 * Otherwise, this could be used to cross sessions, which counts as a security vulnerability
8906 * in a non-flat namespace.
8908 if (ldc
->euid
!= 0) {
8909 job_log(j
, LOG_WARNING
, "Attempt to look up children of bootstrap by unprivileged job.");
8910 return BOOTSTRAP_NOT_PRIVILEGED
;
8913 unsigned int cnt
= 0;
8915 jobmgr_t jmr
= j
->mgr
;
8916 jobmgr_t jmi
= NULL
;
8917 SLIST_FOREACH(jmi
, &jmr
->submgrs
, sle
) {
8921 /* Find our per-user launchds if we're PID 1. */
8924 LIST_FOREACH(ji
, &jmr
->jobs
, sle
) {
8925 cnt
+= ji
->per_user
? 1 : 0;
8930 return BOOTSTRAP_NO_CHILDREN
;
8933 mach_port_array_t _child_ports
= NULL
;
8934 mig_allocate((vm_address_t
*)&_child_ports
, cnt
* sizeof(_child_ports
[0]));
8935 if (!job_assumes(j
, _child_ports
!= NULL
)) {
8936 kr
= BOOTSTRAP_NO_MEMORY
;
8940 name_array_t _child_names
= NULL
;
8941 mig_allocate((vm_address_t
*)&_child_names
, cnt
* sizeof(_child_names
[0]));
8942 if (!job_assumes(j
, _child_names
!= NULL
)) {
8943 kr
= BOOTSTRAP_NO_MEMORY
;
8947 bootstrap_property_array_t _child_properties
= NULL
;
8948 mig_allocate((vm_address_t
*)&_child_properties
, cnt
* sizeof(_child_properties
[0]));
8949 if (!job_assumes(j
, _child_properties
!= NULL
)) {
8950 kr
= BOOTSTRAP_NO_MEMORY
;
8954 unsigned int cnt2
= 0;
8955 SLIST_FOREACH(jmi
, &jmr
->submgrs
, sle
) {
8956 if (jobmgr_assumes(jmi
, launchd_mport_make_send(jmi
->jm_port
) == KERN_SUCCESS
)) {
8957 _child_ports
[cnt2
] = jmi
->jm_port
;
8959 _child_ports
[cnt2
] = MACH_PORT_NULL
;
8962 strlcpy(_child_names
[cnt2
], jmi
->name
, sizeof(_child_names
[0]));
8963 _child_properties
[cnt2
] = jmi
->properties
;
8968 if (pid1_magic
) LIST_FOREACH( ji
, &jmr
->jobs
, sle
) {
8970 if (job_assumes(ji
, SLIST_FIRST(&ji
->machservices
)->per_user_hack
== true)) {
8971 mach_port_t port
= machservice_port(SLIST_FIRST(&ji
->machservices
));
8973 if (job_assumes(ji
, launchd_mport_copy_send(port
) == KERN_SUCCESS
)) {
8974 _child_ports
[cnt2
] = port
;
8976 _child_ports
[cnt2
] = MACH_PORT_NULL
;
8979 _child_ports
[cnt2
] = MACH_PORT_NULL
;
8982 strlcpy(_child_names
[cnt2
], ji
->label
, sizeof(_child_names
[0]));
8983 _child_properties
[cnt2
] |= BOOTSTRAP_PROPERTY_PERUSER
;
8989 *child_names_cnt
= cnt
;
8990 *child_ports_cnt
= cnt
;
8991 *child_properties_cnt
= cnt
;
8993 *child_names
= _child_names
;
8994 *child_ports
= _child_ports
;
8995 *child_properties
= _child_properties
;
8998 for (i
= 0; i
< cnt
; i
++) {
8999 job_log(j
, LOG_DEBUG
, "child_names[%u] = %s", i
, (char *)_child_names
[i
]);
9002 return BOOTSTRAP_SUCCESS
;
9005 mig_deallocate((vm_address_t
)_child_ports
, cnt
* sizeof(_child_ports
[0]));
9009 mig_deallocate((vm_address_t
)_child_names
, cnt
* sizeof(_child_ports
[0]));
9012 if (_child_properties
) {
9013 mig_deallocate((vm_address_t
)_child_properties
, cnt
* sizeof(_child_properties
[0]));
9020 job_mig_transaction_count_for_pid(job_t j
, pid_t p
, int32_t *cnt
, boolean_t
*condemned
)
9023 return BOOTSTRAP_NO_MEMORY
;
9026 kern_return_t kr
= KERN_FAILURE
;
9027 struct ldcred
*ldc
= runtime_get_caller_creds();
9028 if ((ldc
->euid
!= geteuid()) && (ldc
->euid
!= 0)) {
9029 return BOOTSTRAP_NOT_PRIVILEGED
;
9032 job_t j_for_pid
= jobmgr_find_by_pid_deep(j
->mgr
, p
, false);
9034 if (j_for_pid
->kill_via_shmem
) {
9035 if (j_for_pid
->shmem
) {
9036 *cnt
= j_for_pid
->shmem
->vp_shmem_transaction_cnt
;
9037 *condemned
= j_for_pid
->shmem
->vp_shmem_flags
& VPROC_SHMEM_EXITING
;
9038 *cnt
+= *condemned
? 1 : 0;
9044 kr
= BOOTSTRAP_SUCCESS
;
9046 kr
= BOOTSTRAP_NO_MEMORY
;
9049 kr
= BOOTSTRAP_UNKNOWN_SERVICE
;
9056 job_mig_pid_is_managed(job_t j
__attribute__((unused
)), pid_t p
, boolean_t
*managed
)
9058 struct ldcred
*ldc
= runtime_get_caller_creds();
9059 if ((ldc
->euid
!= geteuid()) && (ldc
->euid
!= 0)) {
9060 return BOOTSTRAP_NOT_PRIVILEGED
;
9063 /* This is so loginwindow doesn't try to quit GUI apps that have been launched
9064 * directly by launchd as agents.
9066 job_t j_for_pid
= jobmgr_find_by_pid_deep(root_jobmgr
, p
, false);
9067 if (j_for_pid
&& !j_for_pid
->anonymous
&& !j_for_pid
->legacy_LS_job
) {
9071 return BOOTSTRAP_SUCCESS
;
9075 job_mig_port_for_label(job_t j
__attribute__((unused
)), name_t label
, mach_port_t
*mp
)
9078 return BOOTSTRAP_NO_MEMORY
;
9081 struct ldcred
*ldc
= runtime_get_caller_creds();
9082 kern_return_t kr
= BOOTSTRAP_NOT_PRIVILEGED
;
9085 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_NONE
) > 0)) {
9086 return BOOTSTRAP_NOT_PRIVILEGED
;
9090 mach_port_t _mp
= MACH_PORT_NULL
;
9091 if (!j
->deny_job_creation
&& (ldc
->euid
== 0 || ldc
->euid
== geteuid())) {
9092 job_t target_j
= job_find(NULL
, label
);
9093 if (jobmgr_assumes(root_jobmgr
, target_j
!= NULL
)) {
9094 if (target_j
->j_port
== MACH_PORT_NULL
) {
9095 (void)job_assumes(target_j
, job_setup_machport(target_j
) == true);
9098 _mp
= target_j
->j_port
;
9099 kr
= _mp
!= MACH_PORT_NULL
? BOOTSTRAP_SUCCESS
: BOOTSTRAP_NO_MEMORY
;
9101 kr
= BOOTSTRAP_NO_MEMORY
;
9109 #if !TARGET_OS_EMBEDDED
9111 job_mig_set_security_session(job_t j
, uuid_t uuid
, mach_port_t asport
)
9114 return BOOTSTRAP_NO_MEMORY
;
9117 uuid_string_t uuid_str
;
9118 uuid_unparse(uuid
, uuid_str
);
9119 job_log(j
, LOG_DEBUG
, "Setting session %u for UUID %s...", asport
, uuid_str
);
9121 job_t ji
= NULL
, jt
= NULL
;
9122 LIST_FOREACH_SAFE(ji
, &s_needing_sessions
, sle
, jt
) {
9123 uuid_string_t uuid_str2
;
9124 uuid_unparse(ji
->expected_audit_uuid
, uuid_str2
);
9126 if (uuid_compare(uuid
, ji
->expected_audit_uuid
) == 0) {
9127 uuid_clear(ji
->expected_audit_uuid
);
9128 if (asport
!= MACH_PORT_NULL
) {
9129 job_log(ji
, LOG_DEBUG
, "Job should join session with port %u", asport
);
9130 (void)job_assumes(j
, launchd_mport_copy_send(asport
) == KERN_SUCCESS
);
9132 job_log(ji
, LOG_DEBUG
, "No session to set for job. Using our session.");
9135 ji
->asport
= asport
;
9136 LIST_REMOVE(ji
, needing_session_sle
);
9137 job_dispatch(ji
, false);
9141 /* Each job that the session port was set for holds a reference. At the end of
9142 * the loop, there will be one extra reference belonging to this MiG protocol.
9143 * We need to release it so that the session goes away when all the jobs
9144 * referencing it are unloaded.
9146 (void)job_assumes(j
, launchd_mport_deallocate(asport
) == KERN_SUCCESS
);
9148 return KERN_SUCCESS
;
9152 job_mig_set_security_session(job_t j
__attribute__((unused
)), uuid_t uuid
__attribute__((unused
)), mach_port_t session
__attribute__((unused
)))
9154 return KERN_SUCCESS
;
9159 jobmgr_find_by_name(jobmgr_t jm
, const char *where
)
9163 /* NULL is only passed for our custom API for LaunchServices. If that is the case, we do magic. */
9164 if (where
== NULL
) {
9165 if (strcasecmp(jm
->name
, VPROCMGR_SESSION_LOGINWINDOW
) == 0) {
9166 where
= VPROCMGR_SESSION_LOGINWINDOW
;
9168 where
= VPROCMGR_SESSION_AQUA
;
9172 if (strcasecmp(jm
->name
, where
) == 0) {
9176 if (strcasecmp(where
, VPROCMGR_SESSION_BACKGROUND
) == 0 && !pid1_magic
) {
9181 SLIST_FOREACH(jmi
, &root_jobmgr
->submgrs
, sle
) {
9182 if (unlikely(jmi
->shutting_down
)) {
9184 } else if (jmi
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
) {
9186 } else if (strcasecmp(jmi
->name
, where
) == 0) {
9188 } else if (strcasecmp(jmi
->name
, VPROCMGR_SESSION_BACKGROUND
) == 0 && pid1_magic
) {
9189 SLIST_FOREACH(jmi2
, &jmi
->submgrs
, sle
) {
9190 if (strcasecmp(jmi2
->name
, where
) == 0) {
9203 job_mig_move_subset(job_t j
, mach_port_t target_subset
, name_t session_type
, mach_port_t asport
, uint64_t flags
)
9205 mach_msg_type_number_t l2l_i
, l2l_port_cnt
= 0;
9206 mach_port_array_t l2l_ports
= NULL
;
9207 mach_port_t reqport
, rcvright
;
9208 kern_return_t kr
= 1;
9209 launch_data_t out_obj_array
= NULL
;
9210 struct ldcred
*ldc
= runtime_get_caller_creds();
9211 jobmgr_t jmr
= NULL
;
9213 if (!launchd_assumes(j
!= NULL
)) {
9214 return BOOTSTRAP_NO_MEMORY
;
9217 if (job_mig_intran2(root_jobmgr
, target_subset
, ldc
->pid
)) {
9218 job_log(j
, LOG_ERR
, "Moving a session to ourself is bogus.");
9220 kr
= BOOTSTRAP_NOT_PRIVILEGED
;
9224 job_log(j
, LOG_DEBUG
, "Move subset attempt: 0x%x", target_subset
);
9226 kr
= _vproc_grab_subset(target_subset
, &reqport
, &rcvright
, &out_obj_array
, &l2l_ports
, &l2l_port_cnt
);
9228 if (!job_assumes(j
, kr
== 0)) {
9232 launchd_assert(launch_data_array_get_count(out_obj_array
) == l2l_port_cnt
);
9234 if (!job_assumes(j
, (jmr
= jobmgr_new(j
->mgr
, reqport
, rcvright
, false, session_type
, false, asport
)) != NULL
)) {
9235 kr
= BOOTSTRAP_NO_MEMORY
;
9239 jmr
->properties
|= BOOTSTRAP_PROPERTY_MOVEDSUBSET
;
9241 /* This is a hack. We should be doing this in jobmgr_new(), but since we're in the middle of
9242 * processing an IPC request, we'll do this action before the new job manager can get any IPC
9243 * requests. This serialization is guaranteed since we are single-threaded in that respect.
9245 if (flags
& LAUNCH_GLOBAL_ON_DEMAND
) {
9246 /* This is so awful. */
9247 /* Remove the job from its current job manager. */
9248 LIST_REMOVE(j
, sle
);
9249 LIST_REMOVE(j
, pid_hash_sle
);
9251 /* Put the job into the target job manager. */
9252 LIST_INSERT_HEAD(&jmr
->jobs
, j
, sle
);
9253 LIST_INSERT_HEAD(&jmr
->active_jobs
[ACTIVE_JOB_HASH(j
->p
)], j
, pid_hash_sle
);
9256 job_set_global_on_demand(j
, true);
9258 if (!j
->holds_ref
) {
9259 j
->holds_ref
= true;
9264 for (l2l_i
= 0; l2l_i
< l2l_port_cnt
; l2l_i
++) {
9265 launch_data_t tmp
, obj_at_idx
;
9266 struct machservice
*ms
;
9267 job_t j_for_service
;
9268 const char *serv_name
;
9272 (void)job_assumes(j
, obj_at_idx
= launch_data_array_get_index(out_obj_array
, l2l_i
));
9273 (void)job_assumes(j
, tmp
= launch_data_dict_lookup(obj_at_idx
, TAKE_SUBSET_PID
));
9274 target_pid
= (pid_t
)launch_data_get_integer(tmp
);
9275 (void)job_assumes(j
, tmp
= launch_data_dict_lookup(obj_at_idx
, TAKE_SUBSET_PERPID
));
9276 serv_perpid
= launch_data_get_bool(tmp
);
9277 (void)job_assumes(j
, tmp
= launch_data_dict_lookup(obj_at_idx
, TAKE_SUBSET_NAME
));
9278 serv_name
= launch_data_get_string(tmp
);
9280 j_for_service
= jobmgr_find_by_pid(jmr
, target_pid
, true);
9282 if (unlikely(!j_for_service
)) {
9283 /* The PID probably exited */
9284 (void)job_assumes(j
, launchd_mport_deallocate(l2l_ports
[l2l_i
]) == KERN_SUCCESS
);
9288 if (likely(ms
= machservice_new(j_for_service
, serv_name
, &l2l_ports
[l2l_i
], serv_perpid
))) {
9289 job_log(j
, LOG_DEBUG
, "Importing %s into new bootstrap.", serv_name
);
9290 machservice_request_notifications(ms
);
9297 if (out_obj_array
) {
9298 launch_data_free(out_obj_array
);
9302 mig_deallocate((vm_address_t
)l2l_ports
, l2l_port_cnt
* sizeof(l2l_ports
[0]));
9306 if (target_subset
) {
9307 (void)job_assumes(j
, launchd_mport_deallocate(target_subset
) == KERN_SUCCESS
);
9310 (void)job_assumes(j
, launchd_mport_deallocate(asport
) == KERN_SUCCESS
);
9313 jobmgr_shutdown(jmr
);
9320 job_mig_init_session(job_t j
, name_t session_type
, mach_port_t asport
)
9323 return BOOTSTRAP_NO_MEMORY
;
9328 kern_return_t kr
= BOOTSTRAP_NO_MEMORY
;
9329 if (j
->mgr
->session_initialized
) {
9330 job_log(j
, LOG_ERR
, "Tried to initialize an already setup session!");
9331 kr
= BOOTSTRAP_NOT_PRIVILEGED
;
9332 } else if (strcmp(session_type
, VPROCMGR_SESSION_LOGINWINDOW
) == 0) {
9338 * We're working around LoginWindow and the WindowServer.
9340 * In practice, there is only one LoginWindow session. Unfortunately, for certain
9341 * scenarios, the WindowServer spawns loginwindow, and in those cases, it frequently
9342 * spawns a replacement loginwindow session before cleaning up the previous one.
9344 * We're going to use the creation of a new LoginWindow context as a clue that the
9345 * previous LoginWindow context is on the way out and therefore we should just
9346 * kick-start the shutdown of it.
9349 SLIST_FOREACH(jmi
, &root_jobmgr
->submgrs
, sle
) {
9350 if (unlikely(jmi
->shutting_down
)) {
9352 } else if (strcasecmp(jmi
->name
, session_type
) == 0) {
9353 jobmgr_shutdown(jmi
);
9359 jobmgr_log(j
->mgr
, LOG_DEBUG
, "Initializing as %s", session_type
);
9360 strcpy(j
->mgr
->name_init
, session_type
);
9362 if (job_assumes(j
, (j2
= jobmgr_init_session(j
->mgr
, session_type
, false)))) {
9363 j2
->asport
= asport
;
9364 (void)job_assumes(j
, job_dispatch(j2
, true));
9365 kr
= BOOTSTRAP_SUCCESS
;
9372 job_mig_switch_to_session(job_t j
, mach_port_t requestor_port
, name_t session_name
, mach_port_t asport
, mach_port_t
*new_bsport
)
9374 struct ldcred
*ldc
= runtime_get_caller_creds();
9375 if (!jobmgr_assumes(root_jobmgr
, j
!= NULL
)) {
9376 jobmgr_log(root_jobmgr
, LOG_ERR
, "%s() called with NULL job: PID %d", __func__
, ldc
->pid
);
9377 return BOOTSTRAP_NO_MEMORY
;
9380 if (j
->mgr
->shutting_down
) {
9381 return BOOTSTRAP_UNKNOWN_SERVICE
;
9384 job_log(j
, LOG_DEBUG
, "Job wants to move to %s session.", session_name
);
9386 if (!job_assumes(j
, pid1_magic
== false)) {
9387 job_log(j
, LOG_WARNING
, "Switching sessions is not allowed in the system Mach bootstrap.");
9388 return BOOTSTRAP_NOT_PRIVILEGED
;
9391 if (!j
->anonymous
) {
9392 job_log(j
, LOG_NOTICE
, "Non-anonymous job tried to switch sessions. Please use LimitLoadToSessionType instead.");
9393 return BOOTSTRAP_NOT_PRIVILEGED
;
9396 jobmgr_t target_jm
= jobmgr_find_by_name(root_jobmgr
, session_name
);
9397 if (target_jm
== j
->mgr
) {
9398 job_log(j
, LOG_DEBUG
, "Job is already in its desired session (%s).", session_name
);
9399 *new_bsport
= target_jm
->jm_port
;
9400 return BOOTSTRAP_SUCCESS
;
9404 target_jm
= jobmgr_new(j
->mgr
, requestor_port
, MACH_PORT_NULL
, false, session_name
, false, asport
);
9406 target_jm
->properties
|= BOOTSTRAP_PROPERTY_IMPLICITSUBSET
;
9407 (void)job_assumes(j
, launchd_mport_deallocate(asport
) == KERN_SUCCESS
);
9411 if (!job_assumes(j
, target_jm
!= NULL
)) {
9412 job_log(j
, LOG_WARNING
, "Could not find %s session!", session_name
);
9413 return BOOTSTRAP_NO_MEMORY
;
9416 /* Remove the job from it's current job manager. */
9417 LIST_REMOVE(j
, sle
);
9418 LIST_REMOVE(j
, pid_hash_sle
);
9420 job_t ji
= NULL
, jit
= NULL
;
9421 LIST_FOREACH_SAFE(ji
, &j
->mgr
->global_env_jobs
, global_env_sle
, jit
) {
9423 LIST_REMOVE(ji
, global_env_sle
);
9428 /* Put the job into the target job manager. */
9429 LIST_INSERT_HEAD(&target_jm
->jobs
, j
, sle
);
9430 LIST_INSERT_HEAD(&target_jm
->active_jobs
[ACTIVE_JOB_HASH(j
->p
)], j
, pid_hash_sle
);
9433 LIST_INSERT_HEAD(&target_jm
->global_env_jobs
, j
, global_env_sle
);
9436 /* Move our Mach services over if we're not in a flat namespace. */
9437 if (!g_flat_mach_namespace
&& !SLIST_EMPTY(&j
->machservices
)) {
9438 struct machservice
*msi
= NULL
, *msit
= NULL
;
9439 SLIST_FOREACH_SAFE(msi
, &j
->machservices
, sle
, msit
) {
9440 LIST_REMOVE(msi
, name_hash_sle
);
9441 LIST_INSERT_HEAD(&target_jm
->ms_hash
[hash_ms(msi
->name
)], msi
, name_hash_sle
);
9447 if (!j
->holds_ref
) {
9448 /* Anonymous jobs which move around are particularly interesting to us, so we want to
9449 * stick around while they're still around.
9450 * For example, login calls into the PAM launchd module, which moves the process into
9451 * the StandardIO session by default. So we'll hold a reference on that job to prevent
9452 * ourselves from going away.
9454 j
->holds_ref
= true;
9458 *new_bsport
= target_jm
->jm_port
;
9460 return KERN_SUCCESS
;
9464 job_mig_take_subset(job_t j
, mach_port_t
*reqport
, mach_port_t
*rcvright
,
9465 vm_offset_t
*outdata
, mach_msg_type_number_t
*outdataCnt
,
9466 mach_port_array_t
*portsp
, unsigned int *ports_cnt
)
9468 launch_data_t tmp_obj
, tmp_dict
, outdata_obj_array
= NULL
;
9469 mach_port_array_t ports
= NULL
;
9470 unsigned int cnt
= 0, cnt2
= 0;
9472 struct machservice
*ms
;
9476 if (!launchd_assumes(j
!= NULL
)) {
9477 return BOOTSTRAP_NO_MEMORY
;
9482 if (unlikely(!pid1_magic
)) {
9483 job_log(j
, LOG_ERR
, "Only the system launchd will transfer Mach sub-bootstraps.");
9484 return BOOTSTRAP_NOT_PRIVILEGED
;
9486 if (unlikely(jobmgr_parent(jm
) == NULL
)) {
9487 job_log(j
, LOG_ERR
, "Root Mach bootstrap cannot be transferred.");
9488 return BOOTSTRAP_NOT_PRIVILEGED
;
9490 if (unlikely(strcasecmp(jm
->name
, VPROCMGR_SESSION_AQUA
) == 0)) {
9491 job_log(j
, LOG_ERR
, "Cannot transfer a setup GUI session.");
9492 return BOOTSTRAP_NOT_PRIVILEGED
;
9494 if (unlikely(!j
->anonymous
)) {
9495 job_log(j
, LOG_ERR
, "Only the anonymous job can transfer Mach sub-bootstraps.");
9496 return BOOTSTRAP_NOT_PRIVILEGED
;
9499 job_log(j
, LOG_DEBUG
, "Transferring sub-bootstrap to the per session launchd.");
9501 outdata_obj_array
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
9502 if (!job_assumes(j
, outdata_obj_array
)) {
9506 *outdataCnt
= 20 * 1024 * 1024;
9507 mig_allocate(outdata
, *outdataCnt
);
9508 if (!job_assumes(j
, *outdata
!= 0)) {
9512 LIST_FOREACH(ji
, &j
->mgr
->jobs
, sle
) {
9513 if (!ji
->anonymous
) {
9516 SLIST_FOREACH(ms
, &ji
->machservices
, sle
) {
9521 mig_allocate((vm_address_t
*)&ports
, cnt
* sizeof(ports
[0]));
9522 if (!job_assumes(j
, ports
!= NULL
)) {
9526 LIST_FOREACH(ji
, &j
->mgr
->jobs
, sle
) {
9527 if (!ji
->anonymous
) {
9531 SLIST_FOREACH(ms
, &ji
->machservices
, sle
) {
9532 if (job_assumes(j
, (tmp_dict
= launch_data_alloc(LAUNCH_DATA_DICTIONARY
)))) {
9533 (void)job_assumes(j
, launch_data_array_set_index(outdata_obj_array
, tmp_dict
, cnt2
));
9538 if (job_assumes(j
, (tmp_obj
= launch_data_new_string(machservice_name(ms
))))) {
9539 (void)job_assumes(j
, launch_data_dict_insert(tmp_dict
, tmp_obj
, TAKE_SUBSET_NAME
));
9544 if (job_assumes(j
, (tmp_obj
= launch_data_new_integer((ms
->job
->p
))))) {
9545 (void)job_assumes(j
, launch_data_dict_insert(tmp_dict
, tmp_obj
, TAKE_SUBSET_PID
));
9550 if (job_assumes(j
, (tmp_obj
= launch_data_new_bool((ms
->per_pid
))))) {
9551 (void)job_assumes(j
, launch_data_dict_insert(tmp_dict
, tmp_obj
, TAKE_SUBSET_PERPID
));
9556 ports
[cnt2
] = machservice_port(ms
);
9558 /* Increment the send right by one so we can shutdown the jobmgr cleanly */
9559 (void)jobmgr_assumes(jm
, (errno
= launchd_mport_copy_send(ports
[cnt2
])) == KERN_SUCCESS
);
9564 (void)job_assumes(j
, cnt
== cnt2
);
9566 runtime_ktrace0(RTKT_LAUNCHD_DATA_PACK
);
9567 packed_size
= launch_data_pack(outdata_obj_array
, (void *)*outdata
, *outdataCnt
, NULL
, NULL
);
9568 if (!job_assumes(j
, packed_size
!= 0)) {
9572 launch_data_free(outdata_obj_array
);
9577 *reqport
= jm
->req_port
;
9578 *rcvright
= jm
->jm_port
;
9583 workaround_5477111
= j
;
9585 jobmgr_shutdown(jm
);
9587 return BOOTSTRAP_SUCCESS
;
9590 if (outdata_obj_array
) {
9591 launch_data_free(outdata_obj_array
);
9594 mig_deallocate(*outdata
, *outdataCnt
);
9597 mig_deallocate((vm_address_t
)ports
, cnt
* sizeof(ports
[0]));
9600 return BOOTSTRAP_NO_MEMORY
;
9604 job_mig_subset(job_t j
, mach_port_t requestorport
, mach_port_t
*subsetportp
)
9609 if (!launchd_assumes(j
!= NULL
)) {
9610 return BOOTSTRAP_NO_MEMORY
;
9612 if (j
->mgr
->shutting_down
) {
9613 return BOOTSTRAP_UNKNOWN_SERVICE
;
9618 while ((jmr
= jobmgr_parent(jmr
)) != NULL
) {
9622 /* Since we use recursion, we need an artificial depth for subsets */
9623 if (unlikely(bsdepth
> 100)) {
9624 job_log(j
, LOG_ERR
, "Mach sub-bootstrap create request failed. Depth greater than: %d", bsdepth
);
9625 return BOOTSTRAP_NO_MEMORY
;
9628 char name
[NAME_MAX
];
9629 snprintf(name
, sizeof(name
), "%s[%i].subset.%i", j
->anonymous
? j
->prog
: j
->label
, j
->p
, MACH_PORT_INDEX(requestorport
));
9631 if (!job_assumes(j
, (jmr
= jobmgr_new(j
->mgr
, requestorport
, MACH_PORT_NULL
, false, name
, true, j
->asport
)) != NULL
)) {
9632 if (unlikely(requestorport
== MACH_PORT_NULL
)) {
9633 return BOOTSTRAP_NOT_PRIVILEGED
;
9635 return BOOTSTRAP_NO_MEMORY
;
9638 *subsetportp
= jmr
->jm_port
;
9639 jmr
->properties
|= BOOTSTRAP_PROPERTY_EXPLICITSUBSET
;
9641 /* A job could create multiple subsets, so only add a reference the first time
9642 * it does so we don't have to keep a count.
9644 if (j
->anonymous
&& !j
->holds_ref
) {
9645 j
->holds_ref
= true;
9649 job_log(j
, LOG_DEBUG
, "Job created a subset named \"%s\"", jmr
->name
);
9650 return BOOTSTRAP_SUCCESS
;
9653 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
9655 xpc_domain_import_service(jobmgr_t jm
, launch_data_t pload
)
9657 jobmgr_t where2put
= NULL
;
9659 launch_data_t destname
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_XPCDOMAIN
);
9661 if (launch_data_get_type(destname
) == LAUNCH_DATA_STRING
) {
9662 const char *str
= launch_data_get_string(destname
);
9663 if (strcmp(str
, XPC_DOMAIN_TYPE_SYSTEM
) == 0) {
9664 where2put
= _s_xpc_system_domain
;
9665 } else if (strcmp(str
, XPC_DOMAIN_TYPE_PERUSER
) == 0) {
9666 where2put
= jobmgr_find_xpc_per_user_domain(jm
, jm
->req_euid
);
9667 } else if (strcmp(str
, XPC_DOMAIN_TYPE_PERSESSION
) == 0) {
9668 where2put
= jobmgr_find_xpc_per_session_domain(jm
, jm
->req_asid
);
9670 jobmgr_log(jm
, LOG_ERR
, "Invalid XPC domain type: %s", str
);
9674 jobmgr_log(jm
, LOG_ERR
, "XPC domain type is not a string.");
9679 launch_data_t mi
= NULL
;
9680 if ((mi
= launch_data_dict_lookup(pload
, LAUNCH_JOBKEY_MULTIPLEINSTANCES
))) {
9681 if (launch_data_get_type(mi
) == LAUNCH_DATA_BOOL
&& launch_data_get_bool(mi
)) {
9682 jobmgr_log(where2put
, LOG_ERR
, "Multiple-instance services are not supported in this domain.");
9694 jobmgr_log(where2put
, LOG_DEBUG
, "Importing service...");
9695 j
= jobmgr_import2(where2put
, pload
);
9697 j
->xpc_service
= true;
9698 if (where2put
->xpc_singleton
) {
9699 /* If the service was destined for one of the global domains,
9700 * then we have to alias it into our local domain to reserve the
9703 job_t ja
= job_new_alias(jm
, j
);
9705 /* If we failed to alias the job because of a conflict over
9706 * the label, then we remove it from the global domain. We
9707 * don't want to risk having imported a malicious job into
9708 * one of the global domains.
9710 if (errno
!= EEXIST
) {
9711 job_assumes(j
, errno
== 0);
9713 job_log(j
, LOG_ERR
, "Failed to alias job into: %s", where2put
->name
);
9718 ja
->xpc_service
= true;
9729 xpc_domain_import2(job_t j
, mach_port_t reqport
, mach_port_t dport
)
9731 if (unlikely(!pid1_magic
)) {
9732 job_log(j
, LOG_ERR
, "XPC domains may only reside in PID 1.");
9733 return BOOTSTRAP_NOT_PRIVILEGED
;
9735 if (!j
|| !MACH_PORT_VALID(reqport
)) {
9736 return BOOTSTRAP_UNKNOWN_SERVICE
;
9738 if (root_jobmgr
->shutting_down
) {
9739 jobmgr_log(root_jobmgr
, LOG_ERR
, "Attempt to create new domain while shutting down.");
9740 return BOOTSTRAP_NOT_PRIVILEGED
;
9742 if (!j
->xpc_bootstrapper
) {
9743 job_log(j
, LOG_ERR
, "Attempt to create new XPC domain by unprivileged job.");
9744 return BOOTSTRAP_NOT_PRIVILEGED
;
9747 kern_return_t kr
= BOOTSTRAP_NO_MEMORY
;
9748 /* All XPC domains are children of the root job manager. What we're creating
9749 * here is really just a skeleton. By creating it, we're adding reqp to our
9750 * port set. It will have two messages on it. The first specifies the
9751 * environment of the originator. This is so we can cache it and hand it to
9752 * xpcproxy to bootstrap our services. The second is the set of jobs that is
9753 * to be bootstrapped in.
9755 jobmgr_t jm
= jobmgr_new(root_jobmgr
, reqport
, dport
, false, NULL
, true, MACH_PORT_NULL
);
9756 if (job_assumes(j
, jm
!= NULL
)) {
9757 jm
->properties
|= BOOTSTRAP_PROPERTY_XPC_DOMAIN
;
9758 jm
->shortdesc
= "private";
9759 kr
= BOOTSTRAP_SUCCESS
;
9766 xpc_domain_set_environment(job_t j
, mach_port_t rp
, mach_port_t bsport
, mach_port_t excport
, vm_offset_t ctx
, mach_msg_type_number_t ctx_sz
)
9769 /* Due to the whacky nature of XPC service bootstrapping, we can end up
9770 * getting this message long after the requesting process has gone away.
9771 * See <rdar://problem/8593143>.
9773 return BOOTSTRAP_UNKNOWN_SERVICE
;
9776 jobmgr_t jm
= j
->mgr
;
9777 if (!(jm
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
)) {
9778 return BOOTSTRAP_NOT_PRIVILEGED
;
9781 if (jm
->req_asport
!= MACH_PORT_NULL
) {
9782 return BOOTSTRAP_NOT_PRIVILEGED
;
9785 struct ldcred
*ldc
= runtime_get_caller_creds();
9786 struct proc_bsdshortinfo proc
;
9787 if (proc_pidinfo(ldc
->pid
, PROC_PIDT_SHORTBSDINFO
, 1, &proc
, PROC_PIDT_SHORTBSDINFO_SIZE
) == 0) {
9788 if (errno
!= ESRCH
) {
9789 jobmgr_assumes(jm
, errno
== 0);
9794 return BOOTSTRAP_NO_MEMORY
;
9797 if (!jobmgr_assumes(jm
, audit_session_port(ldc
->asid
, &jm
->req_asport
) == 0)) {
9800 job_log(j
, LOG_ERR
, "Failed to get port for ASID: %u", ldc
->asid
);
9801 return BOOTSTRAP_NOT_PRIVILEGED
;
9804 (void)snprintf(jm
->name_init
, NAME_MAX
, "com.apple.xpc.domain.%s[%i]", proc
.pbsi_comm
, ldc
->pid
);
9805 strlcpy(jm
->owner
, proc
.pbsi_comm
, sizeof(jm
->owner
));
9806 jm
->req_bsport
= bsport
;
9807 jm
->req_excport
= excport
;
9810 jm
->req_ctx_sz
= ctx_sz
;
9811 jm
->req_pid
= ldc
->pid
;
9812 jm
->req_euid
= ldc
->euid
;
9813 jm
->req_egid
= ldc
->egid
;
9814 jm
->req_asid
= ldc
->asid
;
9816 return KERN_SUCCESS
;
9820 xpc_domain_load_services(job_t j
, vm_offset_t services_buff
, mach_msg_type_number_t services_sz
)
9823 return BOOTSTRAP_UNKNOWN_SERVICE
;
9826 job_t rootj
= jobmgr_find_by_pid(root_jobmgr
, j
->p
, false);
9827 if (!(rootj
&& rootj
->xpc_bootstrapper
)) {
9828 job_log(j
, LOG_ERR
, "Attempt to load services into XPC domain by unprivileged job.");
9829 return BOOTSTRAP_NOT_PRIVILEGED
;
9832 /* This is just for XPC domains (for now). */
9833 if (!(j
->mgr
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
)) {
9834 return BOOTSTRAP_NOT_PRIVILEGED
;
9836 if (j
->mgr
->session_initialized
) {
9837 jobmgr_log(j
->mgr
, LOG_ERR
, "Attempt to initialize an already-initialized XPC domain.");
9838 return BOOTSTRAP_NOT_PRIVILEGED
;
9842 launch_data_t services
= launch_data_unpack((void *)services_buff
, services_sz
, NULL
, 0, &offset
, NULL
);
9843 if (!jobmgr_assumes(j
->mgr
, services
!= NULL
)) {
9844 return BOOTSTRAP_NO_MEMORY
;
9848 size_t c
= launch_data_array_get_count(services
);
9849 for (i
= 0; i
< c
; i
++) {
9851 launch_data_t ploadi
= launch_data_array_get_index(services
, i
);
9852 if (!(nj
= xpc_domain_import_service(j
->mgr
, ploadi
))) {
9853 /* If loading one job fails, just fail the whole thing. At this
9854 * point, xpchelper should receive the failure and then just refuse
9855 * to launch the application, since its XPC services could not be
9856 * fully bootstrapped.
9858 * Take care to not reference the job or its manager after this
9861 if (errno
== EINVAL
) {
9862 jobmgr_log(j
->mgr
, LOG_ERR
, "Service at index is not valid: %lu", i
);
9863 } else if (errno
== EEXIST
) {
9864 /* If we get back EEXIST, we know that the payload was a
9865 * dictionary with a label. But, well, I guess it never hurts to
9868 char *label
= "(bogus)";
9869 if (launch_data_get_type(ploadi
) == LAUNCH_DATA_DICTIONARY
) {
9870 launch_data_t llabel
= launch_data_dict_lookup(ploadi
, LAUNCH_JOBKEY_LABEL
);
9871 if (launch_data_get_type(llabel
) == LAUNCH_DATA_STRING
) {
9872 label
= (char *)launch_data_get_string(llabel
);
9875 jobmgr_log(j
->mgr
, LOG_ERR
, "Service name conflict: %s", label
);
9878 j
->mgr
->error
= errno
;
9879 jobmgr_log(j
->mgr
, LOG_ERR
, "Obliterating domain.");
9880 jobmgr_remove(j
->mgr
);
9883 jobmgr_log(j
->mgr
, LOG_DEBUG
, "Imported service %s", nj
->label
);
9884 job_dispatch(nj
, false);
9888 kern_return_t result
= BOOTSTRAP_NO_MEMORY
;
9890 j
->mgr
->session_initialized
= true;
9891 (void)jobmgr_assumes(j
->mgr
, xpc_call_wakeup(j
->mgr
->req_rport
, BOOTSTRAP_SUCCESS
) == KERN_SUCCESS
);
9892 j
->mgr
->req_rport
= MACH_PORT_NULL
;
9894 /* Returning a failure code will destroy the message, whereas returning
9895 * success will not, so we need to clean up here.
9897 mig_deallocate(services_buff
, services_sz
);
9898 result
= BOOTSTRAP_SUCCESS
;
9905 xpc_domain_check_in(job_t j
, mach_port_t
*bsport
, mach_port_t
*sbsport
, mach_port_t
*excport
, mach_port_t
*asport
, uint32_t *uid
, uint32_t *gid
, int32_t *asid
, vm_offset_t
*ctx
, mach_msg_type_number_t
*ctx_sz
)
9907 if (!jobmgr_assumes(root_jobmgr
, j
!= NULL
)) {
9908 return BOOTSTRAP_UNKNOWN_SERVICE
;
9910 jobmgr_t jm
= j
->mgr
;
9911 if (!(jm
->properties
& BOOTSTRAP_PROPERTY_XPC_DOMAIN
)) {
9912 return BOOTSTRAP_NOT_PRIVILEGED
;
9915 if (jm
->req_asport
== MACH_PORT_NULL
) {
9916 return BOOTSTRAP_NOT_PRIVILEGED
;
9919 *bsport
= jm
->req_bsport
;
9920 *sbsport
= root_jobmgr
->jm_port
;
9921 *excport
= jm
->req_excport
;
9922 *asport
= jm
->req_asport
;
9923 *uid
= jm
->req_euid
;
9924 *gid
= jm
->req_egid
;
9925 *asid
= jm
->req_asid
;
9928 *ctx_sz
= jm
->req_ctx_sz
;
9930 return KERN_SUCCESS
;
9934 xpc_domain_get_service_name(job_t j
, event_name_t name
)
9937 return BOOTSTRAP_NO_MEMORY
;
9939 if (!j
->xpc_service
) {
9940 jobmgr_log(j
->mgr
, LOG_ERR
, "Attempt to get service name by non-XPC service: %s", j
->label
);
9941 return BOOTSTRAP_NOT_PRIVILEGED
;
9944 struct machservice
* ms
= SLIST_FIRST(&j
->machservices
);
9946 jobmgr_log(j
->mgr
, LOG_ERR
, "Attempt to get service name of job with no machservices: %s", j
->label
);
9947 return BOOTSTRAP_UNKNOWN_SERVICE
;
9950 (void)strlcpy(name
, ms
->name
, sizeof(event_name_t
));
9951 return BOOTSTRAP_SUCCESS
;
9953 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
9956 xpc_events_get_channel_name(job_t j
__attribute__((unused
)), event_name_t stream
__attribute__((unused
)), uint64_t token
__attribute__((unused
)), event_name_t name
__attribute__((unused
)))
9958 return KERN_FAILURE
;
9962 xpc_events_get_event_name(job_t j
, event_name_t stream
, uint64_t token
, event_name_t name
)
9964 struct externalevent
*event
= externalevent_find(stream
, token
);
9965 if (event
&& j
->event_monitor
) {
9966 (void)strcpy(name
, event
->name
);
9971 return event
? BOOTSTRAP_SUCCESS
: BOOTSTRAP_UNKNOWN_SERVICE
;
9975 xpc_events_set_event(job_t j
, event_name_t stream
, event_name_t key
, vm_offset_t event
, mach_msg_type_number_t eventCnt
)
9978 return BOOTSTRAP_NOT_PRIVILEGED
;
9981 struct externalevent
*eei
= NULL
;
9982 LIST_FOREACH(eei
, &j
->events
, job_le
) {
9983 if (strcmp(eei
->name
, key
) == 0 && strcmp(eei
->sys
->name
, stream
) == 0) {
9984 externalevent_delete(eei
);
9990 bool success
= false;
9991 struct eventsystem
*es
= eventsystem_find(stream
);
9993 es
= eventsystem_new(stream
);
9994 (void)job_assumes(j
, es
!= NULL
);
9999 launch_data_t unpacked
= launch_data_unpack((void *)event
, eventCnt
, NULL
, 0, &offset
, 0);
10000 if (unpacked
&& launch_data_get_type(unpacked
) == LAUNCH_DATA_DICTIONARY
) {
10001 success
= externalevent_new(j
, es
, key
, unpacked
);
10006 mig_deallocate(event
, eventCnt
);
10009 return KERN_SUCCESS
;
10013 xpc_events_get_event(job_t j
, event_name_t stream
, event_name_t key
, vm_offset_t
*event
, mach_msg_type_number_t
*eventCnt
)
10015 struct externalevent
*eei
= NULL
;
10016 LIST_FOREACH(eei
, &j
->events
, job_le
) {
10017 if (strcmp(eei
->name
, key
) == 0 && strcmp(eei
->sys
->name
, stream
) == 0) {
10019 *eventCnt
= 10 * 1024;
10020 mig_allocate(event
, *eventCnt
);
10022 size_t sz
= launch_data_pack(eei
->event
, (void *)*event
, *eventCnt
, NULL
, NULL
);
10023 if (!job_assumes(j
, sz
!= 0)) {
10024 mig_deallocate(*event
, *eventCnt
);
10025 return BOOTSTRAP_NO_MEMORY
;
10028 return BOOTSTRAP_SUCCESS
;
10032 return BOOTSTRAP_UNKNOWN_SERVICE
;
10035 struct machservice
*
10036 xpc_events_find_channel(job_t j
, event_name_t stream
, mach_port_t
*p
)
10038 struct machservice
*msi
= NULL
;
10039 SLIST_FOREACH(msi
, &j
->machservices
, sle
) {
10040 if (strcmp(stream
, msi
->name
) == 0) {
10046 mach_port_t sp
= MACH_PORT_NULL
;
10047 msi
= machservice_new(j
, stream
, &sp
, false);
10048 if (job_assumes(j
, msi
)) {
10049 /* Hack to keep this from being publicly accessible through
10050 * bootstrap_look_up().
10052 LIST_REMOVE(msi
, name_hash_sle
);
10053 msi
->event_channel
= true;
10056 /* If we call job_dispatch() here before the audit session for the
10057 * job has been set, we'll end up not watching this service. But we
10058 * also have to take care not to watch the port if the job is
10061 * See <rdar://problem/10357855>.
10063 if (!j
->currently_ignored
) {
10064 machservice_watch(j
, msi
);
10067 errno
= BOOTSTRAP_NO_MEMORY
;
10070 if (!msi
->event_channel
) {
10071 job_log(j
, LOG_ERR
, "This job registered a MachService name identical to the requested event channel name: %s", stream
);
10073 errno
= BOOTSTRAP_NAME_IN_USE
;
10083 xpc_events_channel_check_in(job_t j
, event_name_t stream
, uint64_t flags
__attribute__((unused
)), mach_port_t
*p
)
10085 struct machservice
*ms
= xpc_events_find_channel(j
, stream
, p
);
10087 if (ms
->isActive
) {
10088 job_log(j
, LOG_ERR
, "Attempt to check in on event channel multiple times: %s", stream
);
10089 *p
= MACH_PORT_NULL
;
10090 errno
= BOOTSTRAP_SERVICE_ACTIVE
;
10093 machservice_request_notifications(ms
);
10094 errno
= BOOTSTRAP_SUCCESS
;
10102 xpc_events_channel_look_up(job_t j
, event_name_t stream
, event_token_t token
, uint64_t flags
__attribute__((unused
)), mach_port_t
*p
)
10104 if (!j
->event_monitor
) {
10105 return BOOTSTRAP_NOT_PRIVILEGED
;
10108 struct externalevent
*ee
= externalevent_find(stream
, token
);
10110 return BOOTSTRAP_UNKNOWN_SERVICE
;
10113 struct machservice
*ms
= xpc_events_find_channel(ee
->job
, stream
, p
);
10115 errno
= BOOTSTRAP_SUCCESS
;
10122 job_mig_kickstart(job_t j
, name_t targetlabel
, pid_t
*out_pid
, unsigned int flags
)
10124 struct ldcred
*ldc
= runtime_get_caller_creds();
10127 if (!launchd_assumes(j
!= NULL
)) {
10128 return BOOTSTRAP_NO_MEMORY
;
10131 if (unlikely(!(otherj
= job_find(NULL
, targetlabel
)))) {
10132 return BOOTSTRAP_UNKNOWN_SERVICE
;
10135 #if TARGET_OS_EMBEDDED
10136 bool allow_non_root_kickstart
= j
->username
&& otherj
->username
&& (strcmp(j
->username
, otherj
->username
) == 0);
10138 bool allow_non_root_kickstart
= false;
10141 if (ldc
->euid
!= 0 && ldc
->euid
!= geteuid() && !allow_non_root_kickstart
) {
10142 return BOOTSTRAP_NOT_PRIVILEGED
;
10146 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_NONE
) > 0)) {
10147 return BOOTSTRAP_NOT_PRIVILEGED
;
10151 if (otherj
->p
&& (flags
& VPROCFLAG_STALL_JOB_EXEC
)) {
10152 return BOOTSTRAP_SERVICE_ACTIVE
;
10155 otherj
->stall_before_exec
= (flags
& VPROCFLAG_STALL_JOB_EXEC
);
10156 otherj
= job_dispatch(otherj
, true);
10158 if (!job_assumes(j
, otherj
&& otherj
->p
)) {
10159 /* <rdar://problem/6787083> Clear this flag if we failed to start the job. */
10160 otherj
->stall_before_exec
= false;
10161 return BOOTSTRAP_NO_MEMORY
;
10164 *out_pid
= otherj
->p
;
10170 job_mig_spawn_internal(job_t j
, vm_offset_t indata
, mach_msg_type_number_t indataCnt
, mach_port_t asport
, job_t
*outj
)
10172 launch_data_t jobdata
= NULL
;
10173 size_t data_offset
= 0;
10174 struct ldcred
*ldc
= runtime_get_caller_creds();
10177 if (!launchd_assumes(j
!= NULL
)) {
10178 return BOOTSTRAP_NO_MEMORY
;
10181 if (unlikely(j
->deny_job_creation
)) {
10182 return BOOTSTRAP_NOT_PRIVILEGED
;
10186 if (unlikely(sandbox_check(ldc
->pid
, "job-creation", SANDBOX_FILTER_NONE
) > 0)) {
10187 return BOOTSTRAP_NOT_PRIVILEGED
;
10191 if (unlikely(pid1_magic
&& ldc
->euid
&& ldc
->uid
)) {
10192 job_log(j
, LOG_DEBUG
, "Punting spawn to per-user-context");
10193 return VPROC_ERR_TRY_PER_USER
;
10196 if (!job_assumes(j
, indataCnt
!= 0)) {
10200 runtime_ktrace0(RTKT_LAUNCHD_DATA_UNPACK
);
10201 if (!job_assumes(j
, (jobdata
= launch_data_unpack((void *)indata
, indataCnt
, NULL
, 0, &data_offset
, NULL
)) != NULL
)) {
10205 jobmgr_t target_jm
= jobmgr_find_by_name(j
->mgr
, NULL
);
10206 if (!jobmgr_assumes(j
->mgr
, target_jm
!= NULL
)) {
10207 jobmgr_log(j
->mgr
, LOG_ERR
, "This API can only be used by a process running within an Aqua session.");
10211 jr
= jobmgr_import2(target_jm
?: j
->mgr
, jobdata
);
10213 launch_data_t label
= NULL
;
10214 launch_data_t wait4debugger
= NULL
;
10218 /* If EEXIST was returned, we know that there is a label string in
10219 * the dictionary. So we don't need to check the types here; that
10220 * has already been done.
10222 label
= launch_data_dict_lookup(jobdata
, LAUNCH_JOBKEY_LABEL
);
10223 jr
= job_find(NULL
, launch_data_get_string(label
));
10224 if (job_assumes(j
, jr
!= NULL
) && !jr
->p
) {
10225 wait4debugger
= launch_data_dict_lookup(jobdata
, LAUNCH_JOBKEY_WAITFORDEBUGGER
);
10226 if (wait4debugger
&& launch_data_get_type(wait4debugger
) == LAUNCH_DATA_BOOL
) {
10227 if (launch_data_get_bool(wait4debugger
)) {
10228 /* If the job exists, we're going to kick-start it, but
10229 * we need to give the caller the opportunity to start
10230 * it suspended if it so desires. But this will only
10231 * take effect if the job isn't running.
10233 jr
->wait4debugger_oneshot
= true;
10239 return BOOTSTRAP_NAME_IN_USE
;
10241 return BOOTSTRAP_NO_MEMORY
;
10246 jr
->mach_uid
= ldc
->uid
;
10249 jr
->legacy_LS_job
= true;
10250 jr
->abandon_pg
= true;
10251 jr
->asport
= asport
;
10252 uuid_clear(jr
->expected_audit_uuid
);
10253 jr
= job_dispatch(jr
, true);
10255 if (!job_assumes(j
, jr
!= NULL
)) {
10257 return BOOTSTRAP_NO_MEMORY
;
10260 if (!job_assumes(jr
, jr
->p
)) {
10262 return BOOTSTRAP_NO_MEMORY
;
10265 job_log(jr
, LOG_DEBUG
, "Spawned by PID %u: %s", j
->p
, j
->label
);
10268 return BOOTSTRAP_SUCCESS
;
10272 job_mig_spawn2(job_t j
, mach_port_t rp
, vm_offset_t indata
, mach_msg_type_number_t indataCnt
, mach_port_t asport
, pid_t
*child_pid
, mach_port_t
*obsvr_port
)
10275 kern_return_t kr
= job_mig_spawn_internal(j
, indata
, indataCnt
, asport
, &nj
);
10276 if (likely(kr
== KERN_SUCCESS
)) {
10277 if (job_setup_exit_port(nj
) != KERN_SUCCESS
) {
10279 kr
= BOOTSTRAP_NO_MEMORY
;
10281 /* Do not return until the job has called exec(3), thereby making it
10282 * safe for the caller to send it SIGCONT.
10284 * <rdar://problem/9042798>
10286 nj
->spawn_reply_port
= rp
;
10289 } else if (kr
== BOOTSTRAP_NAME_IN_USE
) {
10290 bool was_running
= nj
->p
;
10291 if (job_dispatch(nj
, true)) {
10292 if (!was_running
) {
10293 job_log(nj
, LOG_DEBUG
, "Job exists but is not running. Kick-starting.");
10295 if (job_setup_exit_port(nj
) == KERN_SUCCESS
) {
10296 nj
->spawn_reply_port
= rp
;
10299 kr
= BOOTSTRAP_NO_MEMORY
;
10302 *obsvr_port
= MACH_PORT_NULL
;
10303 *child_pid
= nj
->p
;
10307 job_log(nj
, LOG_ERR
, "Failed to dispatch job, requestor: %s", j
->label
);
10308 kr
= BOOTSTRAP_UNKNOWN_SERVICE
;
10312 mig_deallocate(indata
, indataCnt
);
10317 job_mig_event_source_check_in(job_t j
, name_t name
, mach_port_t ping_port
, vm_offset_t
*outval
, mach_msg_type_number_t
*outvalCnt
, uint64_t *tokens
)
10319 if (!j
|| !j
->event_monitor
) {
10320 return BOOTSTRAP_NOT_PRIVILEGED
;
10323 /* Update our ping-port. One ping will force all the notification systems
10324 * to check in, so they'll all give us send-once rights. It doesn't really
10325 * matter which one we keep around. It's not the most efficient thing ever,
10326 * but keep in mind that, by doing this over one channel, we can do it over
10327 * the job's MachService. This means that we'll get it back when the job dies,
10328 * and we can create ourselves a send-once right if we didn't have one already,
10329 * and we can just keep the helper alive without it needing to bootstrap
10332 * So we're trading efficiency for robustness. In this case, the checkins
10333 * should happen pretty infrequently, so it's pretty worth it.
10335 if (_s_event_update_port
!= MACH_PORT_NULL
) {
10336 (void)job_assumes(j
, launchd_mport_deallocate(_s_event_update_port
) == KERN_SUCCESS
);
10338 _s_event_update_port
= ping_port
;
10340 kern_return_t result
= BOOTSTRAP_NO_MEMORY
;
10341 launch_data_t arr
= launch_data_alloc(LAUNCH_DATA_ARRAY
);
10342 if (job_assumes(j
, arr
!= NULL
)) {
10343 struct eventsystem
*es
= eventsystem_find(name
);
10344 if (unlikely(es
== NULL
)) {
10345 es
= eventsystem_new(name
);
10348 if (job_assumes(j
, es
!= NULL
)) {
10349 struct externalevent
*ei
= NULL
;
10351 LIST_FOREACH(ei
, &es
->events
, sys_le
) {
10352 (void)job_assumes(j
, launch_data_array_set_index(arr
, ei
->event
, i
));
10353 if (job_assumes(j
, i
< 1024)) {
10354 tokens
[i
] = ei
->id
;
10362 *outvalCnt
= 10 * 1024;
10363 mig_allocate(outval
, *outvalCnt
);
10365 size_t sz
= launch_data_pack(arr
, (void *)*outval
, *outvalCnt
, NULL
, NULL
);
10366 if (job_assumes(j
, sz
!= 0)) {
10367 result
= BOOTSTRAP_SUCCESS
;
10369 mig_deallocate(*outval
, *outvalCnt
);
10373 /* Total hack, but launch_data doesn't do ref-counting. */
10374 struct _launch_data
*hack
= (struct _launch_data
*)arr
;
10375 free(hack
->_array
);
10383 job_mig_event_set_state(job_t j
, name_t name
, uint64_t token
, boolean_t state
)
10385 if (!j
|| !j
->event_monitor
) {
10386 return BOOTSTRAP_NOT_PRIVILEGED
;
10389 struct externalevent
*ei
= externalevent_find(name
, token
);
10390 if (job_assumes(j
, ei
!= NULL
)) {
10392 if(job_dispatch(ei
->job
, false) == NULL
) {
10393 if (errno
== EPERM
) {
10394 return BOOTSTRAP_NOT_PRIVILEGED
;
10396 return BOOTSTRAP_NO_MEMORY
;
10399 return BOOTSTRAP_NO_MEMORY
;
10402 return BOOTSTRAP_SUCCESS
;
10406 jobmgr_init(bool sflag
)
10408 const char *root_session_type
= pid1_magic
? VPROCMGR_SESSION_SYSTEM
: VPROCMGR_SESSION_BACKGROUND
;
10409 SLIST_INIT(&s_curious_jobs
);
10410 LIST_INIT(&s_needing_sessions
);
10412 launchd_assert((root_jobmgr
= jobmgr_new(NULL
, MACH_PORT_NULL
, MACH_PORT_NULL
, sflag
, root_session_type
, false, MACH_PORT_NULL
)) != NULL
);
10413 #ifndef __LAUNCH_DISABLE_XPC_SUPPORT__
10414 launchd_assert((_s_xpc_system_domain
= jobmgr_new_xpc_singleton_domain(root_jobmgr
, "com.apple.xpc.system")) != NULL
);
10415 _s_xpc_system_domain
->req_asid
= g_audit_session
;
10416 _s_xpc_system_domain
->req_asport
= g_audit_session_port
;
10417 _s_xpc_system_domain
->shortdesc
= "system";
10418 #endif /* __LAUNCH_DISABLE_XPC_SUPPORT__ */
10420 root_jobmgr
->monitor_shutdown
= true;
10423 uint32_t fflags
= NOTE_ATTRIB
| NOTE_LINK
| NOTE_REVOKE
| NOTE_EXTEND
| NOTE_WRITE
;
10424 s_no_hang_fd
= open("/dev/autofs_nowait", O_EVTONLY
| O_NONBLOCK
);
10425 if (likely(s_no_hang_fd
== -1)) {
10426 if (jobmgr_assumes(root_jobmgr
, (s_no_hang_fd
= open("/dev", O_EVTONLY
| O_NONBLOCK
)) != -1)) {
10427 (void)jobmgr_assumes(root_jobmgr
, kevent_mod((uintptr_t)s_no_hang_fd
, EVFILT_VNODE
, EV_ADD
, fflags
, 0, root_jobmgr
) != -1);
10430 s_no_hang_fd
= _fd(s_no_hang_fd
);
10434 our_strhash(const char *s
)
10436 size_t c
, r
= 5381;
10439 * This algorithm was first reported by Dan Bernstein many years ago in comp.lang.c
10442 while ((c
= *s
++)) {
10443 r
= ((r
<< 5) + r
) + c
; /* hash*33 + c */
10450 hash_label(const char *label
)
10452 return our_strhash(label
) % LABEL_HASH_SIZE
;
10456 hash_ms(const char *msstr
)
10458 return our_strhash(msstr
) % MACHSERVICE_HASH_SIZE
;
10462 waiting4removal_new(job_t j
, mach_port_t rp
)
10464 struct waiting_for_removal
*w4r
;
10466 if (!job_assumes(j
, (w4r
= malloc(sizeof(struct waiting_for_removal
))) != NULL
)) {
10470 w4r
->reply_port
= rp
;
10472 SLIST_INSERT_HEAD(&j
->removal_watchers
, w4r
, sle
);
10478 waiting4removal_delete(job_t j
, struct waiting_for_removal
*w4r
)
10480 (void)job_assumes(j
, job_mig_send_signal_reply(w4r
->reply_port
, 0) == 0);
10482 SLIST_REMOVE(&j
->removal_watchers
, w4r
, waiting_for_removal
, sle
);
10488 get_kern_max_proc(void)
10490 int mib
[] = { CTL_KERN
, KERN_MAXPROC
};
10492 size_t max_sz
= sizeof(max
);
10494 (void)launchd_assumes(sysctl(mib
, 2, &max
, &max_sz
, NULL
, 0) != -1);
10499 /* See rdar://problem/6271234 */
10501 eliminate_double_reboot(void)
10503 if (unlikely(!pid1_magic
)) {
10508 const char *argv
[] = { _PATH_BSHELL
, "/etc/rc.deferred_install", NULL
};
10509 char *try_again
= "Will try again at next boot.";
10512 if (unlikely(stat(argv
[1], &sb
) != -1)) {
10513 jobmgr_log(root_jobmgr
, LOG_DEBUG
| LOG_CONSOLE
, "Going to run deferred install script.");
10518 (void)jobmgr_assumes(root_jobmgr
, (errno
= posix_spawnp(&p
, argv
[0], NULL
, NULL
, (char **)argv
, environ
)) == 0);
10521 jobmgr_log(root_jobmgr
, LOG_WARNING
| LOG_CONSOLE
, "Couldn't run deferred install script! %s", try_again
);
10525 if (!jobmgr_assumes(root_jobmgr
, waitpid(p
, &wstatus
, 0) != -1)) {
10526 jobmgr_log(root_jobmgr
, LOG_WARNING
| LOG_CONSOLE
, "Couldn't confirm that deferred install script exited successfully! %s", try_again
);
10530 if (jobmgr_assumes(root_jobmgr
, WIFEXITED(wstatus
) != 0)) {
10531 if (jobmgr_assumes(root_jobmgr
, (result
= WEXITSTATUS(wstatus
)) == EXIT_SUCCESS
)) {
10532 jobmgr_log(root_jobmgr
, LOG_DEBUG
| LOG_CONSOLE
, "Deferred install script completed successfully.");
10534 jobmgr_log(root_jobmgr
, LOG_WARNING
| LOG_CONSOLE
, "Deferred install script exited with status %d. %s", WEXITSTATUS(wstatus
), try_again
);
10537 jobmgr_log(root_jobmgr
, LOG_WARNING
| LOG_CONSOLE
, "Confirmed that deferred install script exited, but couldn't confirm that it was successful. %s", try_again
);
10542 /* If the unlink(2) was to fail, it would be most likely fail with EBUSY. All the other
10543 * failure cases for unlink(2) don't apply when we're running under PID 1 and have verified
10544 * that the file exists. Outside of someone deliberately messing with us (like if /etc/rc.deferredinstall
10545 * is actually a looping sym-link or a mount point for a filesystem) and I/O errors, we should be good.
10547 if (!jobmgr_assumes(root_jobmgr
, unlink(argv
[1]) != -1)) {
10548 jobmgr_log(root_jobmgr
, LOG_WARNING
| LOG_CONSOLE
, "Deferred install script couldn't be removed!");
10554 jetsam_property_setup(launch_data_t obj
, const char *key
, job_t j
)
10556 job_log(j
, LOG_DEBUG
, "Setting Jetsam properties for job...");
10557 if (strcasecmp(key
, LAUNCH_JOBKEY_JETSAMPRIORITY
) == 0 && launch_data_get_type(obj
) == LAUNCH_DATA_INTEGER
) {
10558 j
->jetsam_priority
= (typeof(j
->jetsam_priority
))launch_data_get_integer(obj
);
10559 job_log(j
, LOG_DEBUG
, "Priority: %d", j
->jetsam_priority
);
10560 } else if (strcasecmp(key
, LAUNCH_JOBKEY_JETSAMMEMORYLIMIT
) == 0 && launch_data_get_type(obj
) == LAUNCH_DATA_INTEGER
) {
10561 j
->jetsam_memlimit
= (typeof(j
->jetsam_memlimit
))launch_data_get_integer(obj
);
10562 job_log(j
, LOG_DEBUG
, "Memory limit: %d", j
->jetsam_memlimit
);
10563 } else if (strcasecmp(key
, LAUNCH_KEY_JETSAMFRONTMOST
) == 0) {
10564 /* Ignore. We only recognize this key so we don't complain when we get SpringBoard's request.
10565 * You can't set this in a plist.
10567 } else if (strcasecmp(key
, LAUNCH_KEY_JETSAMLABEL
) == 0) {
10568 /* Ignore. This key is present in SpringBoard's request dictionary, so we don't want to
10569 * complain about it.
10572 job_log(j
, LOG_ERR
, "Unknown Jetsam key: %s", key
);
10575 if (unlikely(!j
->jetsam_properties
)) {
10576 j
->jetsam_properties
= true;
10577 LIST_INSERT_HEAD(&j
->mgr
->jetsam_jobs
, j
, jetsam_sle
);
10578 j
->mgr
->jetsam_jobs_cnt
++;
10581 j
->jetsam_seq
= s_jetsam_sequence_id
++;
10585 launchd_set_jetsam_priorities(launch_data_t priorities
)
10587 if (!launchd_assumes(launch_data_get_type(priorities
) == LAUNCH_DATA_ARRAY
)) {
10591 jobmgr_t jm
= NULL
;
10592 #if !TARGET_OS_EMBEDDED
10594 jm
= jobmgr_find_by_name(root_jobmgr
, VPROCMGR_SESSION_AQUA
);
10595 if (!launchd_assumes(jm
!= NULL
)) {
10599 /* Since this is for embedded, we can assume that the root job manager holds the Jetsam jobs. */
10602 if (!g_embedded_privileged_action
) {
10607 size_t npris
= launch_data_array_get_count(priorities
);
10611 for (i
= 0; i
< npris
; i
++) {
10612 launch_data_t ldi
= launch_data_array_get_index(priorities
, i
);
10613 if (!launchd_assumes(launch_data_get_type(ldi
) == LAUNCH_DATA_DICTIONARY
)) {
10617 launch_data_t label
= NULL
;
10618 if (!launchd_assumes(label
= launch_data_dict_lookup(ldi
, LAUNCH_KEY_JETSAMLABEL
))) {
10621 const char *_label
= launch_data_get_string(label
);
10623 ji
= job_find(NULL
, _label
);
10624 if (!launchd_assumes(ji
!= NULL
)) {
10628 launch_data_dict_iterate(ldi
, (void (*)(launch_data_t
, const char *, void *))jetsam_property_setup
, ji
);
10630 launch_data_t frontmost
= NULL
;
10631 if ((frontmost
= launch_data_dict_lookup(ldi
, LAUNCH_KEY_JETSAMFRONTMOST
)) && launch_data_get_type(frontmost
) == LAUNCH_DATA_BOOL
) {
10632 ji
->jetsam_frontmost
= launch_data_get_bool(frontmost
);
10637 job_t
*jobs
= (job_t
*)calloc(jm
->jetsam_jobs_cnt
, sizeof(job_t
));
10638 if (launchd_assumes(jobs
!= NULL
)) {
10639 LIST_FOREACH(ji
, &jm
->jetsam_jobs
, jetsam_sle
) {
10647 size_t totalpris
= i
;
10649 int result
= EINVAL
;
10651 /* It is conceivable that there could be no Jetsam jobs running. */
10652 if (totalpris
> 0) {
10654 qsort_b((void *)jobs
, totalpris
, sizeof(job_t
), ^ int (const void *lhs
, const void *rhs
) {
10655 job_t _lhs
= *(job_t
*)lhs
;
10656 job_t _rhs
= *(job_t
*)rhs
;
10657 /* Sort in descending order. (Priority correlates to the soonishness with which you will be killed.) */
10658 if (_lhs
->jetsam_priority
> _rhs
->jetsam_priority
) {
10660 } else if (_lhs
->jetsam_priority
< _rhs
->jetsam_priority
) {
10663 /* Priority is equal, so sort by sequence ID to maintain LRU order */
10664 if( (int)(_lhs
->jetsam_seq
- _rhs
->jetsam_seq
) > 0 ) {
10666 } else if( (int)(_lhs
->jetsam_seq
- _rhs
->jetsam_seq
) < 0 ) {
10673 jetsam_priority_entry_t
*jpris
= (jetsam_priority_entry_t
*)calloc(totalpris
, sizeof(jetsam_priority_entry_t
));
10674 if (!launchd_assumes(jpris
!= NULL
)) {
10677 for (i
= 0; i
< totalpris
; i
++) {
10678 jpris
[i
].pid
= jobs
[i
]->p
; /* Subject to time-of-use vs. time-of-check, obviously. */
10679 jpris
[i
].flags
|= jobs
[i
]->jetsam_frontmost
? kJetsamFlagsFrontmost
: 0;
10680 jpris
[i
].hiwat_pages
= jobs
[i
]->jetsam_memlimit
;
10683 (void)launchd_assumes((result
= sysctlbyname("kern.memorystatus_priority_list", NULL
, NULL
, &jpris
[0], totalpris
* sizeof(jetsam_priority_entry_t
))) != -1);
10684 result
= result
!= 0 ? errno
: 0;