+ if ( ngrp < 1 ) {
+ ngrp = 1;
+ } else {
+ error = copyin(gidset,
+ (caddr_t)newgroups, ngrp * sizeof(gid_t));
+ if (error) {
+ return (error);
+ }
+ }
+
+ my_cred = kauth_cred_proc_ref(p);
+ if ((error = suser(my_cred, &p->p_acflag))) {
+ kauth_cred_unref(&my_cred);
+ return (error);
+ }
+
+ if ((uthread->uu_flag & UT_SETUID) != 0) {
+#if DEBUG_CRED
+ int my_cred_flags = uthread->uu_ucred->cr_flags;
+#endif /* DEBUG_CRED */
+ kauth_cred_unref(&my_cred);
+
+ /*
+ * If this thread is under an assumed identity, set the
+ * supplementary grouplist on the thread credential instead
+ * of the process one. If we were the only reference holder,
+ * the credential is updated in place, otherwise, our reference
+ * is dropped and we get back a different cred with a reference
+ * already held on it. Because this is per-thread, we don't
+ * need the referencing/locking/retry required for per-process.
+ */
+ my_cred = uthread->uu_ucred;
+ uthread->uu_ucred = kauth_cred_setgroups(my_cred, &newgroups[0], ngrp, gmuid);
+#if DEBUG_CRED
+ if (my_cred != uthread->uu_ucred) {
+ DEBUG_CRED_CHANGE("setgroups1(CH)%d: %p/0x%08x->%p/0x%08x\n", p->p_pid, my_cred, my_cred_flags, uthread->uu_ucred , uthread->uu_ucred ->cr_flags);
+ }
+#endif /* DEBUG_CRED */
+ } else {
+
+ /*
+ * get current credential and take a reference while we muck
+ * with it
+ */
+ for (;;) {
+ /*
+ * Set the credential with new info. If there is no
+ * change, we get back the same credential we passed
+ * in; if there is a change, we drop the reference on
+ * the credential we passed in. The subsequent
+ * compare is safe, because it is a pointer compare
+ * rather than a contents compare.
+ */
+ my_new_cred = kauth_cred_setgroups(my_cred, &newgroups[0], ngrp, gmuid);
+ if (my_cred != my_new_cred) {
+
+ DEBUG_CRED_CHANGE("setgroups1(CH)%d: %p/0x%08x->%p/0x%08x\n", p->p_pid, my_cred, my_cred->cr_flags, my_new_cred, my_new_cred->cr_flags);
+
+ proc_lock(p);
+ /*
+ * We need to protect for a race where another
+ * thread also changed the credential after we
+ * took our reference. If p_ucred has
+ * changed then we should restart this again
+ * with the new cred.
+ */
+ if (p->p_ucred != my_cred) {
+ proc_unlock(p);
+ kauth_cred_unref(&my_new_cred);
+ my_cred = kauth_cred_proc_ref(p);
+ /* try again */
+ continue;
+ }
+ p->p_ucred = my_new_cred;
+ /* update cred on proc */
+ PROC_UPDATE_CREDS_ONPROC(p);
+ OSBitOrAtomic(P_SUGID, &p->p_flag);
+ proc_unlock(p);
+ }
+ break;
+ }
+ /* Drop old proc reference or our extra reference */
+ AUDIT_ARG(groupset, posix_cred_get(my_cred)->cr_groups, ngrp);
+ kauth_cred_unref(&my_cred);
+
+
+ set_security_token(p);
+ }
+
+ return (0);