xref: /titanic_51/usr/src/cmd/sgs/rtld/common/remove.c (revision f34a71784df3fbc5d1227a7b6201fd318ad1667e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Remove objects.  Objects need removal from a process as part of:
29  *
30  *  o	a dlclose() request
31  *
32  *  o	tearing down a dlopen(), lazy-load, or filter hierarchy that failed to
33  *	completely load
34  *
35  * Any other failure condition will result in process exit (in which case all
36  * we have to do is execute the fini's - tear down is unnecessary).
37  *
38  * Any removal of objects is therefore associated with a dlopen() handle.  There
39  * is a small window between creation of the first dlopen() object and creating
40  * its handle (in which case remove_so() can get rid of the new link-map if
41  * necessary), but other than this all object removal is driven by inspecting
42  * the components of a handle.
43  *
44  * Things to note.  The creation of a link-map, and its addition to the link-map
45  * list occurs in {elf|aout}_new_lm(), if this returns success the link-map is
46  * valid and added, otherwise any steps (allocations) in the process of creating
47  * the link-map would have been undone.  If a failure occurs between creating
48  * the link-map and adding it to a handle, remove_so() is called to remove the
49  * link-map.  If a failures occurs after a handle have been created,
50  * remove_hdl() is called to remove the handle and the link-map.
51  */
52 
53 #include	<string.h>
54 #include	<stdio.h>
55 #include	<unistd.h>
56 #include	<dlfcn.h>
57 #include	<sys/debug.h>
58 #include	<sys/avl.h>
59 #include	<libc_int.h>
60 #include	<debug.h>
61 #include	"_rtld.h"
62 #include	"_audit.h"
63 #include	"_elf.h"
64 #include	"msg.h"
65 
66 /*
67  * Atexit callback provided by libc.  As part of dlclose() determine the address
68  * ranges of all objects that are to be deleted.  Pass this information to
69  * libc's pre-atexit routine.  Libc will purge any registered atexit() calls
70  * related to those objects about to be deleted.
71  */
72 static int
73 purge_exit_handlers(Lm_list *lml, Rt_map **tobj)
74 {
75 	uint_t			num;
76 	Rt_map			**_tobj;
77 	Lc_addr_range_t		*addr, *_addr;
78 	int			error;
79 	int			(*fptr)(Lc_addr_range_t *, uint_t);
80 
81 	/*
82 	 * Has a callback been established?
83 	 */
84 	if ((fptr = lml->lm_lcs[CI_ATEXIT].lc_un.lc_func) == NULL)
85 		return (0);
86 
87 	/*
88 	 * Determine the total number of mapped segments that will be unloaded.
89 	 */
90 	for (num = 0, _tobj = tobj; *_tobj != NULL; _tobj++) {
91 		Rt_map	*lmp = *_tobj;
92 
93 		num += MMAPCNT(lmp);
94 	}
95 
96 	/*
97 	 * Account for a null entry at the end of the address range array.
98 	 */
99 	if (num++ == 0)
100 		return (0);
101 
102 	/*
103 	 * Allocate an array for the address range.
104 	 */
105 	if ((addr = malloc(num * sizeof (Lc_addr_range_t))) == NULL)
106 		return (1);
107 
108 	/*
109 	 * Fill the address range with each loadable segments size and address.
110 	 */
111 	for (_tobj = tobj, _addr = addr; *_tobj != NULL; _tobj++) {
112 		Rt_map			*lmp = *_tobj;
113 		mmapobj_result_t	*mpp = MMAPS(lmp);
114 		uint_t			ndx;
115 
116 		for (ndx = 0; ndx < MMAPCNT(lmp); ndx++, mpp++) {
117 			_addr->lb = (void *)(uintptr_t)(mpp->mr_addr +
118 			    mpp->mr_offset);
119 			_addr->ub = (void *)(uintptr_t)(mpp->mr_addr +
120 			    mpp->mr_msize);
121 			_addr++;
122 		}
123 	}
124 	_addr->lb = _addr->ub = 0;
125 
126 	leave(LIST(*tobj), 0);
127 	error = (*fptr)(addr, (num - 1));
128 	(void) enter(0);
129 
130 	/*
131 	 * If we fail to converse with libc, generate an error message to
132 	 * satisfy any dlerror() usage.
133 	 */
134 	if (error)
135 		eprintf(lml, ERR_FATAL, MSG_INTL(MSG_ARG_ATEXIT), error);
136 
137 	free(addr);
138 	return (error);
139 }
140 
141 /*
142  * Break down an Alist containing pathname descriptors.  In most instances, the
143  * Alist is cleaned of all entries, but retained for later use.
144  */
145 void
146 remove_plist(Alist **alpp, int complete)
147 {
148 	Alist	*alp = *alpp;
149 
150 	if (alp) {
151 		if (complete) {
152 			free((void *)alp);
153 			*alpp = NULL;
154 		} else {
155 			alp->al_nitems = 0;
156 			alp->al_next = ALIST_OFF_DATA;
157 		}
158 	}
159 }
160 
161 /*
162  * Remove a link-map list descriptor.  This is called to finalize the removal
163  * of an entire link-map list, after all link-maps have been removed, or none
164  * got added.  As load_one() can process a list of potential candidate objects,
165  * the link-map descriptor must be maintained as each object is processed.  Only
166  * after all objects have been processed can a failure condition finally tear
167  * down the link-map list descriptor.
168  */
169 void
170 remove_lml(Lm_list *lml)
171 {
172 	if (lml && (lml->lm_head == NULL)) {
173 		/*
174 		 * As a whole link-map list is being removed, the debuggers
175 		 * would have been alerted of this deletion (or an addition
176 		 * in the case we're here to clean up from a failure).  Set
177 		 * the main link-map list so that a consistent registration
178 		 * can be signaled to the debuggers when we leave ld.so.1.
179 		 */
180 		lml_main.lm_flags |= LML_FLG_DBNOTIF;
181 
182 		if (lml->lm_lmidstr)
183 			free(lml->lm_lmidstr);
184 		if (lml->lm_alp)
185 			free(lml->lm_alp);
186 		if (lml->lm_lists)
187 			free(lml->lm_lists);
188 		if (lml->lm_actaudit)
189 			free(lml->lm_actaudit);
190 
191 		/*
192 		 * Cleanup any pending RTLDINFO in the case where it was
193 		 * allocated but not called (see _relocate_lmc()).
194 		 */
195 		if (lml->lm_rti)
196 			free(lml->lm_rti);
197 		if (lml->lm_fpavl) {
198 			/*
199 			 * As we are freeing the link-map list, all nodes must
200 			 * have previously been removed.
201 			 */
202 			ASSERT(avl_numnodes(lml->lm_fpavl) == 0);
203 			free(lml->lm_fpavl);
204 		}
205 		(void) aplist_delete_value(dynlm_list, lml);
206 		free(lml);
207 	}
208 }
209 
210 /*
211  * Remove a link-map.  This removes a link-map from its associated list and
212  * free's up the link-map itself.  Note, all components that are freed are local
213  * to the link-map, no inter-link-map lists are operated on as these are all
214  * broken down by dlclose() while all objects are still mapped.
215  *
216  * This routine is called from dlclose() to zap individual link-maps after their
217  * interdependencies (DEPENDS(), CALLER(), handles, etc.) have been removed.
218  * This routine is also called from the bowels of load_one() in the case of a
219  * link-map creation failure.
220  */
221 void
222 remove_so(Lm_list *lml, Rt_map *lmp)
223 {
224 	Dyninfo *dip;
225 
226 	if (lmp == NULL)
227 		return;
228 
229 	/*
230 	 * Unlink the link map from the link-map list.
231 	 */
232 	if (lml && lmp)
233 		lm_delete(lml, lmp);
234 
235 	/*
236 	 * If this object contributed any local external vectors for the current
237 	 * link-map list, remove the vectors.  If this object contributed any
238 	 * global external vectors we should find some new candidates, or leave
239 	 * this object lying around.
240 	 */
241 	if (lml) {
242 		int	tag;
243 
244 		for (tag = 0; tag < CI_MAX; tag++) {
245 			if (lml->lm_lcs[tag].lc_lmp == lmp) {
246 				lml->lm_lcs[tag].lc_lmp = NULL;
247 				lml->lm_lcs[tag].lc_un.lc_val = 0;
248 			}
249 			if (glcs[tag].lc_lmp == lmp) {
250 				ASSERT(glcs[tag].lc_lmp != NULL);
251 				glcs[tag].lc_lmp = NULL;
252 				glcs[tag].lc_un.lc_val = 0;
253 			}
254 		}
255 	}
256 
257 	DBG_CALL(Dbg_file_delete(lmp));
258 
259 	/*
260 	 * If this is a temporary link-map, put in place to facilitate the
261 	 * link-edit or a relocatable object, then the link-map contains no
262 	 * information that needs to be cleaned up.
263 	 */
264 	if (FLAGS(lmp) & FLG_RT_OBJECT)
265 		return;
266 
267 	/*
268 	 * Remove any FullpathNode AVL names if they still exist.
269 	 */
270 	if (FPNODE(lmp))
271 		fpavl_remove(lmp);
272 
273 	/*
274 	 * Remove any alias names.
275 	 */
276 	if (ALIAS(lmp))
277 		free(ALIAS(lmp));
278 
279 	/*
280 	 * Remove any of this objects filtee infrastructure.  The filtees them-
281 	 * selves have already been removed.
282 	 */
283 	if (((dip = DYNINFO(lmp)) != NULL) && (FLAGS1(lmp) & MSK_RT_FILTER)) {
284 		uint_t	cnt, max = DYNINFOCNT(lmp);
285 
286 		for (cnt = 0; cnt < max; cnt++, dip++) {
287 			if ((dip->di_info == NULL) ||
288 			    ((dip->di_flags & MSK_DI_FILTER) == 0))
289 				continue;
290 
291 			remove_plist((Alist **)&(dip->di_info), 1);
292 		}
293 	}
294 
295 	/*
296 	 * Deallocate any remaining cruft and free the link-map.
297 	 */
298 	if (RLIST(lmp))
299 		remove_plist(&RLIST(lmp), 1);
300 
301 	if (AUDITORS(lmp))
302 		audit_desc_cleanup(lmp);
303 	if (AUDINFO(lmp))
304 		audit_info_cleanup(lmp);
305 
306 	/*
307 	 * Note that COPY_R() and COPY_S() reference the same memory
308 	 * location, and that we want to release the memory referenced
309 	 * without regard to which list it logically belongs to. We can
310 	 * use either pointer to do this.
311 	 */
312 	if (COPY_R(lmp))
313 		free(COPY_R(lmp));
314 
315 	/*
316 	 * During a dlclose() any groups this object was a part of will have
317 	 * been torn down.  However, we can get here to remove an object that
318 	 * has failed to load, perhaps because its addition to a handle failed.
319 	 * Therefore if this object indicates that its part of a group tear
320 	 * these associations down.
321 	 */
322 	if (GROUPS(lmp) != NULL) {
323 		Aliste	idx1;
324 		Grp_hdl	*ghp;
325 
326 		for (APLIST_TRAVERSE(GROUPS(lmp), idx1, ghp)) {
327 			Grp_desc	*gdp;
328 			Aliste		idx2;
329 
330 			for (ALIST_TRAVERSE(ghp->gh_depends, idx2, gdp)) {
331 				if (gdp->gd_depend != lmp)
332 					continue;
333 
334 				alist_delete(ghp->gh_depends, &idx2);
335 				break;
336 			}
337 		}
338 		free(GROUPS(lmp));
339 	}
340 	if (HANDLES(lmp))
341 		free(HANDLES(lmp));
342 
343 	/*
344 	 * Clean up reglist if needed
345 	 */
346 	if (reglist) {
347 		Reglist	*cur, *prv, *del;
348 
349 		cur = prv = reglist;
350 		while (cur) {
351 			if (cur->rl_lmp == lmp) {
352 				del = cur;
353 				if (cur == reglist) {
354 					reglist = cur->rl_next;
355 					cur = prv = reglist;
356 				} else {
357 					prv->rl_next = cur->rl_next;
358 					cur = cur->rl_next;
359 				}
360 				free(del);
361 			} else {
362 				prv = cur;
363 				cur = cur->rl_next;
364 			}
365 		}
366 	}
367 
368 	/*
369 	 * If this link map represents a relocatable object concatenation, then
370 	 * the image was simply generated in allocated memory.  Free the memory.
371 	 * Note: memory maps were fabricated for the relocatable object, and
372 	 * the mapping infrastructure must be free'd, but there are no address
373 	 * mappings that must be unmapped.
374 	 *
375 	 * Otherwise, unmap the object.
376 	 */
377 	if (FLAGS(lmp) & FLG_RT_IMGALLOC)
378 		free((void *)ADDR(lmp));
379 
380 	if (MMAPS(lmp)) {
381 		if ((FLAGS(lmp) & FLG_RT_IMGALLOC) == 0)
382 			unmap_obj(MMAPS(lmp), MMAPCNT(lmp));
383 		free(MMAPS(lmp));
384 	}
385 
386 	free(lmp);
387 }
388 
389 /*
390  * Traverse an objects dependency list removing callers and dependencies.
391  * There's a chicken and egg problem with tearing down link-maps.  Any
392  * relationship between link-maps is maintained on a DEPENDS list, and an
393  * associated CALLERS list.  These lists can't be broken down at the time a
394  * single link-map is removed, as any related link-map may have already been
395  * removed.  Thus, lists between link-maps must be broken down before the
396  * individual link-maps themselves.
397  */
398 static void
399 remove_lists(Rt_map *lmp, int lazy)
400 {
401 	Aliste		idx1;
402 	Bnd_desc	*bdp;
403 
404 	/*
405 	 * First, traverse this objects dependencies.
406 	 */
407 	for (APLIST_TRAVERSE(DEPENDS(lmp), idx1, bdp)) {
408 		Rt_map		*dlmp = bdp->b_depend;
409 
410 		/*
411 		 * Remove this object from the dependencies callers.
412 		 */
413 		(void) aplist_delete_value(CALLERS(dlmp), bdp);
414 		free(bdp);
415 	}
416 	if (DEPENDS(lmp)) {
417 		free(DEPENDS(lmp));
418 		DEPENDS(lmp) = NULL;
419 	}
420 
421 	/*
422 	 * Second, traverse this objects callers.
423 	 */
424 	for (APLIST_TRAVERSE(CALLERS(lmp), idx1,  bdp)) {
425 		Rt_map		*clmp = bdp->b_caller;
426 		Dyninfo		*dip;
427 
428 		/*
429 		 * If we're removing an object that was triggered by a lazyload,
430 		 * remove the callers DYNINFO() entry and bump the lazy counts.
431 		 * This reinitialization of the lazy information allows a lazy
432 		 * object to be reloaded again later.  Although we may be
433 		 * breaking down a group of lazyloaded objects because one has
434 		 * failed to relocate, it's possible that one or more of the
435 		 * individual objects can be reloaded without a problem.
436 		 */
437 		if (lazy && ((dip = DYNINFO(clmp)) != NULL)) {
438 			uint_t	cnt, max = DYNINFOCNT(clmp);
439 
440 			for (cnt = 0; cnt < max; cnt++, dip++) {
441 				if ((dip->di_flags & FLG_DI_LAZY) == 0)
442 					continue;
443 
444 				if (dip->di_info == (void *)lmp) {
445 					dip->di_info = NULL;
446 
447 					if (LAZY(clmp)++ == 0)
448 						LIST(clmp)->lm_lazy++;
449 				}
450 			}
451 		}
452 
453 		(void) aplist_delete_value(DEPENDS(clmp), bdp);
454 		free(bdp);
455 	}
456 	if (CALLERS(lmp)) {
457 		free(CALLERS(lmp));
458 		CALLERS(lmp) = NULL;
459 	}
460 }
461 
462 /*
463  * Delete any temporary link-map control list.
464  */
465 void
466 remove_cntl(Lm_list *lml, Aliste lmco)
467 {
468 	Aliste	_lmco = lmco;
469 #if	DEBUG
470 	Lm_cntl	*lmc;
471 
472 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, lmco);
473 
474 	/*
475 	 * This element should be empty.
476 	 */
477 	ASSERT(lmc->lc_head == NULL);
478 #endif
479 	alist_delete_by_offset(lml->lm_lists, &_lmco);
480 }
481 
482 /*
483  * If a lazy loaded object, or filtee fails to load, possibly because it, or
484  * one of its dependencies can't be relocated, then tear down any objects
485  * that are apart of this link-map control list.
486  */
487 static void
488 remove_incomplete(Lm_list *lml, Aliste lmco)
489 {
490 	Rt_map	*lmp;
491 	Lm_cntl	*lmc;
492 
493 	/* LINTED */
494 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, lmco);
495 
496 	/*
497 	 * First, remove any lists that may point between objects.
498 	 */
499 	for (lmp = lmc->lc_head; lmp; lmp = NEXT_RT_MAP(lmp))
500 		remove_lists(lmp, 1);
501 
502 	/*
503 	 * Finally, remove each object.  remove_so() calls lm_delete(), thus
504 	 * effectively the link-map control head gets updated to point to the
505 	 * next link-map.
506 	 */
507 	while ((lmp = lmc->lc_head) != NULL)
508 		remove_so(lml, lmp);
509 
510 	lmc->lc_head = lmc->lc_tail = NULL;
511 }
512 
513 /*
514  * Determine whether an object is deletable.
515  */
516 static int
517 is_deletable(APlist **lmalp, APlist **ghalp, Rt_map *lmp)
518 {
519 	Aliste		idx;
520 	Bnd_desc	*bdp;
521 	Grp_hdl		*ghp;
522 
523 	/*
524 	 * If the object hasn't yet been relocated take this as a sign that
525 	 * it's loading failed, thus we're here to cleanup.  If the object is
526 	 * relocated it will only be retained if it was marked non-deletable,
527 	 * and exists on the main link-map control list.
528 	 */
529 	if ((FLAGS(lmp) & FLG_RT_RELOCED) &&
530 	    (MODE(lmp) & RTLD_NODELETE) && (CNTL(lmp) == ALIST_OFF_DATA))
531 		return (0);
532 
533 	/*
534 	 * If this object is the head of a handle that has not been captured as
535 	 * a candidate for deletion, then this object is in use from a dlopen()
536 	 * outside of the scope of this dlclose() family.  Dlopen'ed objects,
537 	 * and filtees, have group descriptors for their callers.  Typically
538 	 * this parent will have callers that are not apart of this dlclose()
539 	 * family, and thus would be caught by the CALLERS test below.  However,
540 	 * if the caller had itself been dlopen'ed, it may not have any explicit
541 	 * callers registered for itself.  Thus, but looking for objects with
542 	 * handles we can ferret out these outsiders.
543 	 */
544 	for (APLIST_TRAVERSE(HANDLES(lmp), idx, ghp)) {
545 		if (aplist_test(ghalp, ghp, 0) != ALE_EXISTS)
546 			return (0);
547 	}
548 
549 	/*
550 	 * If this object is called by any object outside of the family of
551 	 * objects selected for deletion, it can't be deleted.
552 	 */
553 	for (APLIST_TRAVERSE(CALLERS(lmp), idx, bdp)) {
554 		if (aplist_test(lmalp, bdp->b_caller, 0) !=
555 		    ALE_EXISTS)
556 			return (0);
557 	}
558 
559 	/*
560 	 * This object is a candidate for deletion.
561 	 */
562 	return (1);
563 }
564 
565 /*
566  * Collect the groups (handles) and associated objects that are candidates for
567  * deletion.  The criteria for deleting an object is whether it is only refer-
568  * enced from the objects within the groups that are candidates for deletion.
569  */
570 static int
571 gdp_collect(APlist **ghalpp, APlist **lmalpp, Grp_hdl *ghp1)
572 {
573 	Aliste		idx1;
574 	Grp_desc	*gdp;
575 	int		action;
576 
577 	/*
578 	 * Add this group to our group collection.  If it isn't added either an
579 	 * allocation has failed, or it already exists.
580 	 */
581 	if ((action = aplist_test(ghalpp, ghp1, AL_CNT_GRPCLCT)) !=
582 	    ALE_CREATE)
583 		return (action);
584 
585 	/*
586 	 * Traverse the dependencies of the group and collect the associated
587 	 * objects.
588 	 */
589 	for (ALIST_TRAVERSE(ghp1->gh_depends, idx1, gdp)) {
590 		Rt_map	*lmp = gdp->gd_depend;
591 
592 		/*
593 		 * We only want to process dependencies for deletion.  Although
594 		 * we want to purge group descriptors for parents, we don't want
595 		 * to analyze the parent itself for additional filters or
596 		 * deletion.
597 		 */
598 		if ((gdp->gd_flags & GPD_PARENT) ||
599 		    ((gdp->gd_flags & GPD_ADDEPS) == 0))
600 			continue;
601 
602 		if ((action = aplist_test(lmalpp, lmp, AL_CNT_GRPCLCT)) ==
603 		    ALE_ALLOCFAIL)
604 			return (0);
605 		if (action == ALE_EXISTS)
606 			continue;
607 
608 		/*
609 		 * If this object is a candidate for deletion, determine if the
610 		 * object provides any filtees.  If so, the filter groups are
611 		 * added to the group collection.
612 		 *
613 		 * An object is a candidate for deletion if:
614 		 *
615 		 *  .	the object hasn't yet been relocated, in which case
616 		 *	we're here to clean up a failed load, or
617 		 *  .	the object doesn't reside on the base link-map control
618 		 *	list, in which case a group of objects, typically
619 		 *	lazily loaded, or filtees, need cleaning up, or
620 		 *  .   the object isn't tagged as non-deletable.
621 		 */
622 		if ((((FLAGS(lmp) & FLG_RT_RELOCED) == 0) ||
623 		    (CNTL(lmp) != ALIST_OFF_DATA) ||
624 		    ((MODE(lmp) & RTLD_NODELETE) == 0)) &&
625 		    (FLAGS1(lmp) & MSK_RT_FILTER)) {
626 			Dyninfo	*dip = DYNINFO(lmp);
627 			uint_t	cnt, max = DYNINFOCNT(lmp);
628 
629 			for (cnt = 0; cnt < max; cnt++, dip++) {
630 				Alist	*falp;
631 				Aliste	idx2;
632 				Pdesc	*pdp;
633 
634 				if (((falp = (Alist *)dip->di_info) == NULL) ||
635 				    ((dip->di_flags & MSK_DI_FILTER) == 0))
636 					continue;
637 
638 				for (ALIST_TRAVERSE(falp, idx2, pdp)) {
639 					Grp_hdl	*ghp2;
640 
641 					if ((pdp->pd_plen == 0) || ((ghp2 =
642 					    (Grp_hdl *)pdp->pd_info) == NULL))
643 						continue;
644 
645 					if (gdp_collect(ghalpp, lmalpp,
646 					    ghp2) == 0)
647 						return (0);
648 				}
649 			}
650 		}
651 	}
652 	return (1);
653 }
654 
655 /*
656  * Traverse the list of deletable candidates.  If an object can't be deleted
657  * then neither can its dependencies or filtees.  Any object that is cleared
658  * from being deleted drops the deletion count, plus, if there are no longer
659  * any deletions pending we can discontinue any further processing.
660  */
661 static int
662 remove_rescan(APlist *lmalp, APlist *ghalp, int *delcnt)
663 {
664 	Aliste		idx1;
665 	Rt_map		*lmp;
666 	int		rescan = 0;
667 
668 	for (APLIST_TRAVERSE(lmalp, idx1, lmp)) {
669 		Aliste		idx2;
670 		Bnd_desc	*bdp;
671 		Dyninfo		*dip;
672 		uint_t		cnt, max;
673 
674 		if (FLAGS(lmp) & FLG_RT_DELETE)
675 			continue;
676 
677 		/*
678 		 * As this object can't be deleted, make sure its dependencies
679 		 * aren't deleted either.
680 		 */
681 		for (APLIST_TRAVERSE(DEPENDS(lmp), idx2, bdp)) {
682 			Rt_map	*dlmp = bdp->b_depend;
683 
684 			if (FLAGS(dlmp) & FLG_RT_DELETE) {
685 				FLAGS(dlmp) &= ~FLG_RT_DELETE;
686 				if (--(*delcnt) == 0)
687 					return (0);
688 				rescan = 1;
689 			}
690 		}
691 
692 		/*
693 		 * If this object is a filtee and one of its filters is outside
694 		 * of this dlclose family, then it can't be deleted either.
695 		 */
696 		if ((FLAGS1(lmp) & MSK_RT_FILTER) == 0)
697 			continue;
698 
699 		dip = DYNINFO(lmp);
700 		max = DYNINFOCNT(lmp);
701 
702 		for (cnt = 0; cnt < max; cnt++, dip++) {
703 			Alist	*falp;
704 			Pdesc	*pdp;
705 
706 			if (((falp = (Alist *)dip->di_info) == NULL) ||
707 			    ((dip->di_flags & MSK_DI_FILTER) == 0))
708 				continue;
709 
710 			for (ALIST_TRAVERSE(falp, idx2, pdp)) {
711 				Aliste		idx3;
712 				Grp_hdl		*ghp;
713 				Grp_desc	*gdp;
714 
715 				if ((pdp->pd_plen == 0) ||
716 				    ((ghp = (Grp_hdl *)pdp->pd_info) == NULL))
717 					continue;
718 
719 				if (aplist_test(&ghalp, ghp, 0) ==
720 				    ALE_EXISTS)
721 					continue;
722 
723 				for (ALIST_TRAVERSE(ghp->gh_depends, idx3,
724 				    gdp)) {
725 					Rt_map	*dlmp = gdp->gd_depend;
726 
727 					if (FLAGS(dlmp) & FLG_RT_DELETE) {
728 						FLAGS(dlmp) &= ~FLG_RT_DELETE;
729 						if (--(*delcnt) == 0)
730 							return (0);
731 						rescan = 1;
732 					}
733 				}
734 
735 				/*
736 				 * Remove this group handle from our dynamic
737 				 * deletion list.
738 				 */
739 				(void) aplist_delete_value(ghalp, ghp);
740 			}
741 		}
742 	}
743 	return (rescan);
744 }
745 
746 /*
747  * Cleanup any collection alists we've created.
748  */
749 static void
750 remove_collect(APlist *ghalp, APlist *lmalp)
751 {
752 	if (ghalp)
753 		free(ghalp);
754 	if (lmalp)
755 		free(lmalp);
756 }
757 
758 /*
759  * Remove a handle, leaving the associated objects intact.  Besides the classic
760  * dlopen() usage, handles are used as a means of associating a group of objects
761  * and promoting modes.  Once object promotion is completed, the handle should
762  * be discarded while leaving the associated objects intact.  Leaving the handle
763  * would prevent the object from being deleted (as it looks like it's in use
764  * by another user).
765  */
766 void
767 free_hdl(Grp_hdl *ghp, Rt_map *clmp, uint_t cdflags)
768 {
769 	Grp_desc	*gdp;
770 	Aliste		idx;
771 
772 	if (--(ghp->gh_refcnt) == 0) {
773 		uintptr_t	ndx;
774 
775 		for (ALIST_TRAVERSE(ghp->gh_depends, idx, gdp)) {
776 			Rt_map	*lmp = gdp->gd_depend;
777 
778 			if (ghp->gh_ownlmp == lmp)
779 				(void) aplist_delete_value(HANDLES(lmp), ghp);
780 			(void) aplist_delete_value(GROUPS(lmp), ghp);
781 		}
782 		(void) free(ghp->gh_depends);
783 
784 		/* LINTED */
785 		ndx = (uintptr_t)ghp % HDLIST_SZ;
786 		(void) aplist_delete_value(hdl_alp[ndx], ghp);
787 
788 		(void) free(ghp);
789 
790 	} else if (clmp) {
791 		/*
792 		 * It's possible that an RTLD_NOW promotion (via GPD_PROMOTE)
793 		 * has associated a caller with a handle that is already in use.
794 		 * In this case, find the caller and either remove the caller
795 		 * from the handle, or if the caller is used for any other
796 		 * reason, clear the promotion flag.
797 		 */
798 		for (ALIST_TRAVERSE(ghp->gh_depends, idx, gdp)) {
799 			Rt_map	*lmp = gdp->gd_depend;
800 
801 			if (lmp != clmp)
802 				continue;
803 
804 			if (gdp->gd_flags == cdflags) {
805 				alist_delete(ghp->gh_depends, &idx);
806 				(void) aplist_delete_value(GROUPS(lmp), ghp);
807 			} else {
808 				gdp->gd_flags &= ~cdflags;
809 			}
810 			return;
811 		}
812 	}
813 }
814 
815 /*
816  * If a load operation, using a new link-map control list, has failed, then
817  * forcibly remove the failed objects.  This failure can occur as a result
818  * of a lazy load, a dlopen(), or a filtee load, once the application is
819  * running.  If the link-map control list has not yet started relocation, then
820  * cleanup is simply a process of removing all the objects from the control
821  * list.  If relocation has begun, then other loads may have been triggered to
822  * satisfy the relocations, and thus we need to break down the control list
823  * using handles.
824  *
825  * The objects associated with this load must be part of a unique handle.  In
826  * the case of a dlopen() or filtee request, a handle will have been created.
827  * For a lazyload request, a handle must be generated so that the remove
828  * process can use the handle.
829  *
830  * During the course of processing these objects, other objects (handles) may
831  * have been loaded to satisfy relocation requirements.  After these families
832  * have successfully loaded, they will have been propagated to the same link-map
833  * control list.  The failed objects need to be removed from this list, while
834  * any successfully loaded families can be left alone, and propagated to the
835  * previous link-map control list.  By associating each load request with a
836  * handle, we can isolate the failed objects while not interfering with any
837  * successfully loaded families.
838  */
839 void
840 remove_lmc(Lm_list *lml, Rt_map *clmp, Aliste lmco, const char *name)
841 {
842 	Grp_hdl		*ghp;
843 	Grp_desc	*gdp;
844 	Aliste		idx;
845 	Lm_cntl		*lmc;
846 	Rt_map		*lmp;
847 
848 	/*
849 	 * Determine the link-map control list, and whether any object has been
850 	 * added to this list.
851 	 */
852 	/* LINTED */
853 	lmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, lmco);
854 	if (lmc->lc_head == NULL)
855 		return;
856 
857 	DBG_CALL(Dbg_file_cleanup(lml, name, lmco));
858 
859 	/*
860 	 * Obtain a handle for the first object on the link-map control list.
861 	 * If none exists (which would occur from a lazy load request), and
862 	 * the link-map control list is being relocated, create a handle.
863 	 */
864 	lmp = lmc->lc_head;
865 	if (HANDLES(lmp)) {
866 		ghp = (Grp_hdl *)HANDLES(lmp)->apl_data[0];
867 
868 	} else if (lmc->lc_flags & LMC_FLG_RELOCATING) {
869 		/*
870 		 * Establish a handle, and should anything fail, fall through
871 		 * to remove the link-map control list.
872 		 */
873 		if (((ghp = hdl_create(lml, lmc->lc_head, 0, 0,
874 		    GPD_ADDEPS, 0)) == NULL) ||
875 		    (hdl_initialize(ghp, lmc->lc_head, 0, 0) == 0))
876 			lmc->lc_flags &= ~LMC_FLG_RELOCATING;
877 	} else {
878 		ghp = NULL;
879 	}
880 
881 	/*
882 	 * If relocation hasn't begun, simply remove all the objects from this
883 	 * list, and any handle that may have been created.
884 	 */
885 	if ((lmc->lc_flags & LMC_FLG_RELOCATING) == 0) {
886 		remove_incomplete(lml, lmco);
887 
888 		if (ghp) {
889 			ghp->gh_refcnt = 1;
890 			free_hdl(ghp, 0, 0);
891 		}
892 		return;
893 	}
894 
895 	ASSERT(ghp != NULL);
896 
897 	/*
898 	 * As the objects of this handle are being forcibly removed, first
899 	 * remove any associations to objects on parent link-map control
900 	 * lists.  This breaks the bond between a caller and a hierarchy of
901 	 * dependencies represented by the handle, thus the caller doesn't lock
902 	 * the hierarchy and prevent their deletion from the generic handle
903 	 * processing or remove_hdl().
904 	 *
905 	 * This scenario can be produced when the relocation of a object
906 	 * results in vectoring through a filter that is already loaded.  The
907 	 * filtee may be on the link-map list that is presently being processed,
908 	 * however an association between the filter and filtee would have been
909 	 * established during filtee processing.  It is this association that
910 	 * must be broken to allow the objects on this link-map list to be
911 	 * removed.
912 	 */
913 	for (ALIST_TRAVERSE(ghp->gh_depends, idx, gdp)) {
914 		Rt_map	*lmp = gdp->gd_depend;
915 
916 		/*
917 		 * If this object has not been relocated, break down any
918 		 * dependency relationships the object might have established.
919 		 */
920 		if ((FLAGS(lmp) & FLG_RT_RELOCED) == 0)
921 			remove_lists(lmp, 1);
922 
923 		if (CNTL(lmp) == lmco)
924 			continue;
925 
926 		if (gdp->gd_flags & GPD_FILTER) {
927 			Dyninfo	*dip = DYNINFO(lmp);
928 			uint_t	cnt, max = DYNINFOCNT(lmp);
929 
930 			for (cnt = 0; cnt < max; cnt++, dip++) {
931 				Alist	*falp;
932 				Aliste	idx2;
933 				Pdesc	*pdp;
934 
935 				if (((falp = (Alist *)dip->di_info) == NULL) ||
936 				    ((dip->di_flags & MSK_DI_FILTER) == 0))
937 					continue;
938 
939 				for (ALIST_TRAVERSE(falp, idx2, pdp)) {
940 					if ((Grp_hdl *)pdp->pd_info == ghp) {
941 						pdp->pd_info = NULL;
942 						break;
943 					}
944 				}
945 			}
946 		}
947 		(void) aplist_delete_value(GROUPS(lmp), ghp);
948 		alist_delete(ghp->gh_depends, &idx);
949 	}
950 
951 	/*
952 	 * Having removed any callers, set the group handle reference count to
953 	 * one, and let the generic handle remover delete the associated
954 	 * objects.
955 	 */
956 	ghp->gh_refcnt = 1;
957 	(void) remove_hdl(ghp, clmp, NULL);
958 
959 	/*
960 	 * If this link-map control list still contains objects, determine the
961 	 * previous control list and move the objects.
962 	 */
963 	if (lmc->lc_head) {
964 		Lm_cntl *plmc;
965 		Aliste  plmco;
966 
967 		plmco = lmco - lml->lm_lists->al_size;
968 		/* LINTED */
969 		plmc = (Lm_cntl *)alist_item_by_offset(lml->lm_lists, plmco);
970 
971 		lm_move(lml, lmco, plmco, lmc, plmc);
972 	}
973 }
974 
975 /*
976  * Remove the objects associated with a handle.  There are two goals here, to
977  * delete the objects associated with the handle, and to remove the handle
978  * itself.  Things get a little more complex if the objects selected for
979  * deletion are filters, in this case we also need to collect their filtees,
980  * and process the combined groups as a whole.  But, care still must be exer-
981  * cised to make sure any filtees found aren't being used by filters outside of
982  * the groups we've collect.  The series of events is basically:
983  *
984  *  o	Determine the groups (handles) that might be deletable.
985  *
986  *  o	Determine the objects of these handles that can be deleted.
987  *
988  *  o	Fire the fini's of those objects selected for deletion.
989  *
990  *  o	Remove all inter-dependency linked lists while the objects link-maps
991  *	are still available.
992  *
993  *  o	Remove all deletable objects link-maps and unmap the objects themselves.
994  *
995  *  o	Remove the handle descriptors for each deleted object, and hopefully
996  *	the whole handle.
997  *
998  * An handle that can't be deleted is added to an orphans list.  This list is
999  * revisited any time another dlclose() request results in handle descriptors
1000  * being deleted.  These deleted descriptors can be sufficient to allow the
1001  * final deletion of the orphaned handles.
1002  */
1003 int
1004 remove_hdl(Grp_hdl *ghp, Rt_map *clmp, int *removed)
1005 {
1006 	Rt_map		*lmp;
1007 	int		rescan = 0;
1008 	int		delcnt = 0, rmcnt = 0, error = 0, orphans;
1009 	APlist		*lmalp = NULL, *ghalp = NULL;
1010 	Aliste		idx1, idx2;
1011 	Grp_hdl		*ghp2;
1012 	Grp_desc	*gdp;
1013 	Lm_list		*lml = NULL;
1014 
1015 	/*
1016 	 * Generate the family of groups and objects that are candidates for
1017 	 * deletion.  This consists of the objects that are explicitly defined
1018 	 * as dependencies of this handle, plus any filtee handles and their
1019 	 * associated objects.
1020 	 */
1021 	if (gdp_collect(&ghalp, &lmalp, ghp) == 0) {
1022 		remove_collect(ghalp, lmalp);
1023 		return (0);
1024 	}
1025 
1026 	DBG_CALL(Dbg_file_hdl_title(DBG_HDL_DELETE));
1027 
1028 	/*
1029 	 * Traverse the groups we've collected to determine if any filtees are
1030 	 * included.  If so, and the filtee handle is in use by a filter outside
1031 	 * of the family of objects collected for this deletion, it can not be
1032 	 * removed.
1033 	 */
1034 	for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1035 		Grp_hdl	*ghp = ghp2;
1036 
1037 		DBG_CALL(Dbg_file_hdl_collect(ghp, 0));
1038 
1039 		if ((ghp->gh_flags & GPH_FILTEE) == 0)
1040 			continue;
1041 
1042 		/*
1043 		 * Special case for ld.so.1.  There can be multiple instances of
1044 		 * libdl.so.1 using this handle, so although we want the handles
1045 		 * reference count to be decremented, we don't want the handle
1046 		 * removed.
1047 		 */
1048 		if (ghp->gh_flags & GPH_LDSO) {
1049 			DBG_CALL(Dbg_file_hdl_collect(ghp,
1050 			    NAME(lml_rtld.lm_head)));
1051 			aplist_delete(ghalp, &idx1);
1052 			continue;
1053 		}
1054 
1055 		for (ALIST_TRAVERSE(ghp->gh_depends, idx2, gdp)) {
1056 			Grp_hdl	*ghp3;
1057 			Aliste	idx3;
1058 
1059 			/*
1060 			 * Determine whether this dependency is the filtee's
1061 			 * parent filter, and that it isn't also an explicit
1062 			 * dependency (in which case it would have added its own
1063 			 * dependencies to the handle).
1064 			 */
1065 			if ((gdp->gd_flags &
1066 			    (GPD_FILTER | GPD_ADDEPS)) != GPD_FILTER)
1067 				continue;
1068 
1069 			lmp = gdp->gd_depend;
1070 
1071 			if (FLAGS(lmp) & FLG_RT_DELETE)
1072 				continue;
1073 
1074 			if (aplist_test(&lmalp, lmp, 0) == ALE_EXISTS)
1075 				continue;
1076 
1077 			/*
1078 			 * Remove this group handle from our dynamic deletion
1079 			 * list.  In addition, recompute the list of objects
1080 			 * that are candidates for deletion to continue this
1081 			 * group verification.
1082 			 */
1083 			DBG_CALL(Dbg_file_hdl_collect(ghp, NAME(lmp)));
1084 			aplist_delete(ghalp, &idx1);
1085 
1086 			free(lmalp);
1087 			lmalp = NULL;
1088 			for (APLIST_TRAVERSE(ghalp, idx3, ghp3)) {
1089 				Aliste		idx4;
1090 				Grp_desc	*gdp4;
1091 
1092 				for (ALIST_TRAVERSE(ghp3->gh_depends,
1093 				    idx4, gdp4))  {
1094 					if ((gdp4->gd_flags & GPD_ADDEPS) == 0)
1095 						continue;
1096 					if (aplist_test(&lmalp, gdp4->gd_depend,
1097 					    AL_CNT_GRPCLCT) == ALE_ALLOCFAIL) {
1098 						remove_collect(ghalp, lmalp);
1099 						return (0);
1100 					}
1101 				}
1102 			}
1103 			break;
1104 		}
1105 	}
1106 
1107 	/*
1108 	 * Now that we've collected all the handles dependencies, traverse the
1109 	 * collection determining whether they are a candidate for deletion.
1110 	 */
1111 	for (APLIST_TRAVERSE(lmalp, idx1, lmp)) {
1112 		/*
1113 		 * Establish which link-map list we're dealing with for later
1114 		 * .fini processing.
1115 		 */
1116 		if (lml == NULL)
1117 			lml = LIST(lmp);
1118 
1119 		/*
1120 		 * If an object isn't a candidate for deletion we'll have to
1121 		 * rescan the handle insuring that this objects dependencies
1122 		 * aren't deleted either.
1123 		 */
1124 		if (is_deletable(&lmalp, &ghalp, lmp)) {
1125 			FLAGS(lmp) |= FLG_RT_DELETE;
1126 			delcnt++;
1127 		} else
1128 			rescan = 1;
1129 	}
1130 
1131 	/*
1132 	 * Rescan the handle if any objects where found non-deletable.
1133 	 */
1134 	while (rescan)
1135 		rescan = remove_rescan(lmalp, ghalp, &delcnt);
1136 
1137 	/*
1138 	 * Now that we have determined the number of groups that are candidates
1139 	 * for removal, mark each group descriptor as a candidate for removal
1140 	 * from the group.
1141 	 */
1142 	for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1143 		for (ALIST_TRAVERSE(ghp2->gh_depends, idx2, gdp))
1144 			gdp->gd_flags |= GPD_REMOVE;
1145 	}
1146 
1147 	/*
1148 	 * Now that we know which objects on this handle can't be deleted
1149 	 * determine whether they still need to remain identified as belonging
1150 	 * to this group to be able to continue binding to one another.
1151 	 */
1152 	for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1153 		Grp_hdl	*ghp = ghp2;
1154 
1155 		for (ALIST_TRAVERSE(ghp->gh_depends, idx2, gdp)) {
1156 			Aliste		idx3;
1157 			Bnd_desc	*bdp;
1158 
1159 			lmp = gdp->gd_depend;
1160 
1161 			if (FLAGS(lmp) & FLG_RT_DELETE)
1162 				continue;
1163 
1164 			for (APLIST_TRAVERSE(DEPENDS(lmp), idx3, bdp)) {
1165 				Aliste 		idx4;
1166 				Grp_desc	*gdp4;
1167 				Rt_map		*dlmp = bdp->b_depend;
1168 
1169 				/*
1170 				 * If this dependency (dlmp) can be referenced
1171 				 * by the caller (clmp) without being part of
1172 				 * this group (ghp) then belonging to this group
1173 				 * is no longer necessary.  This can occur when
1174 				 * objects are part of multiple handles, or if a
1175 				 * previously deleted handle was moved to the
1176 				 * orphan list and has been reopened.  Note,
1177 				 * first make sure the caller can reference the
1178 				 * dependency with this group, if it can't we
1179 				 * must be bound to a filtee, so there's no need
1180 				 * to remain a part of this group either.
1181 				 */
1182 				if ((callable(lmp, dlmp, 0, 0) == 0) ||
1183 				    callable(lmp, dlmp, ghp, 0))
1184 					continue;
1185 
1186 				if (gdp->gd_flags & GPD_REMOVE)
1187 					gdp->gd_flags &= ~GPD_REMOVE;
1188 
1189 				for (ALIST_TRAVERSE(ghp->gh_depends,
1190 				    idx4, gdp4)) {
1191 					if (gdp4->gd_depend != dlmp)
1192 						continue;
1193 
1194 					if (gdp4->gd_flags & GPD_REMOVE)
1195 						gdp4->gd_flags &= ~GPD_REMOVE;
1196 				}
1197 			}
1198 		}
1199 	}
1200 
1201 	/*
1202 	 * If the owner of a handle can't be deleted and it's handle descriptor
1203 	 * must remain also, don't delete the handle at all.  Leave it for
1204 	 * possible later use.  Although it's left intact, it will still be
1205 	 * moved to the orphans list, as we might be able to revisit it on later
1206 	 * dlclose() operations and finally remove the underlying objects.  Note
1207 	 * that the handle still remains attached to the owner via the HANDLES
1208 	 * list, so that it can be re-associated to the owner if a dlopen()
1209 	 * of this object reoccurs.
1210 	 */
1211 	for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1212 		Grp_hdl	*ghp = ghp2;
1213 
1214 		/*
1215 		 * If this handle is already an orphan, or if it's owner is
1216 		 * deletable there's no need to inspect its dependencies.
1217 		 */
1218 		if ((ghp->gh_ownlmp == NULL) ||
1219 		    (FLAGS(ghp->gh_ownlmp) & FLG_RT_DELETE))
1220 			continue;
1221 
1222 		/*
1223 		 * Make sure all handle dependencies aren't removed or the
1224 		 * dependencies themselves aren't deleted.
1225 		 */
1226 		for (ALIST_TRAVERSE(ghp->gh_depends, idx2, gdp)) {
1227 			lmp = gdp->gd_depend;
1228 
1229 			/*
1230 			 * The first dependency of a non-orphaned handle is the
1231 			 * owner.  If the handle descriptor for this isn't
1232 			 * required there's no need to look at any other of the
1233 			 * handles dependencies.
1234 			 */
1235 			if ((lmp == ghp->gh_ownlmp) &&
1236 			    (gdp->gd_flags & GPD_REMOVE))
1237 				break;
1238 
1239 			if (gdp->gd_flags & GPD_REMOVE)
1240 				gdp->gd_flags &= ~GPD_REMOVE;
1241 			if (FLAGS(lmp) & FLG_RT_DELETE) {
1242 				FLAGS(lmp) &= ~FLG_RT_DELETE;
1243 				delcnt--;
1244 			}
1245 		}
1246 	}
1247 
1248 	/*
1249 	 * Final scan of objects to see if any objects are to to be deleted.
1250 	 * Also - display diagnostic information on what operations are to be
1251 	 * performed on the collected handles before firing .fini's (which
1252 	 * produces additional diagnostics).
1253 	 */
1254 	for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1255 		Grp_hdl	*ghp = ghp2;
1256 
1257 		DBG_CALL(Dbg_file_hdl_title(DBG_HDL_DELETE));
1258 
1259 		for (ALIST_TRAVERSE(ghp->gh_depends, idx2, gdp)) {
1260 			int	flag;
1261 
1262 			lmp = gdp->gd_depend;
1263 
1264 			/*
1265 			 * Note, we must never delete a parent.  The parent
1266 			 * may already be tagged for deletion from a previous
1267 			 * dlclose(). That dlclose has triggered this dlclose(),
1268 			 * but the parents deletion is the responsibility of the
1269 			 * previous dlclose(), not this one.
1270 			 */
1271 			if ((FLAGS(lmp) & FLG_RT_DELETE) &&
1272 			    ((gdp->gd_flags & GPD_PARENT) == 0)) {
1273 				flag = DBG_DEP_DELETE;
1274 
1275 				/*
1276 				 * Remove any pathnames from the FullpathNode
1277 				 * AVL tree.  As we're about to fire .fini's,
1278 				 * it's possible this object will be required
1279 				 * again, in which case we want to make sure a
1280 				 * new version of the object gets loaded.
1281 				 */
1282 				if (FPNODE(lmp))
1283 					fpavl_remove(lmp);
1284 			} else if (gdp->gd_flags & GPD_REMOVE)
1285 				flag = DBG_DEP_REMOVE;
1286 			else
1287 				flag = DBG_DEP_REMAIN;
1288 
1289 			DBG_CALL(Dbg_file_hdl_action(ghp, lmp, flag, 0));
1290 		}
1291 	}
1292 
1293 	/*
1294 	 * If there are objects to be deleted process their .fini's.
1295 	 */
1296 	if (delcnt) {
1297 		Rt_map	**tobj;
1298 
1299 		/*
1300 		 * If we're being audited tell the audit library that we're
1301 		 * about to go deleting dependencies.
1302 		 */
1303 		if (clmp && ((LIST(clmp)->lm_tflags | AFLAGS(clmp)) &
1304 		    LML_TFLG_AUD_ACTIVITY))
1305 			audit_activity(clmp, LA_ACT_DELETE);
1306 
1307 		/*
1308 		 * Sort and fire all fini's of the objects selected for
1309 		 * deletion.  Note that we have to start our search from the
1310 		 * link-map head - there's no telling whether this object has
1311 		 * dependencies on objects that were loaded before it and which
1312 		 * can now be deleted.  If the tsort() fails because of an
1313 		 * allocation error then that might just be a symptom of why
1314 		 * we're here in the first place - forgo the fini's but
1315 		 * continue to try cleaning up.
1316 		 */
1317 		lml->lm_flags |= LML_FLG_OBJDELETED;
1318 
1319 		if (((tobj = tsort(lml->lm_head, delcnt,
1320 		    (RT_SORT_DELETE | RT_SORT_FWD))) != NULL) &&
1321 		    (tobj != (Rt_map **)S_ERROR)) {
1322 			error = purge_exit_handlers(lml, tobj);
1323 			call_fini(lml, tobj);
1324 		}
1325 
1326 		/*
1327 		 * Audit the closure of the dlopen'ed object to any local
1328 		 * auditors.  Any global auditors would have been caught by
1329 		 * call_fini(), but as the link-maps CALLERS was removed
1330 		 * already we do the local auditors explicitly.
1331 		 */
1332 		for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1333 			Grp_hdl	*ghp = ghp2;
1334 			Rt_map	*dlmp = ghp->gh_ownlmp;
1335 
1336 			if (clmp && dlmp &&
1337 			    ((LIST(dlmp)->lm_flags & LML_FLG_NOAUDIT) == 0) &&
1338 			    (AFLAGS(clmp) & LML_TFLG_AUD_OBJCLOSE))
1339 				_audit_objclose(AUDITORS(clmp)->ad_list, dlmp);
1340 		}
1341 	}
1342 
1343 	/*
1344 	 * Now that .fini processing (which may have involved new bindings)
1345 	 * is complete, remove all inter-dependency lists from those objects
1346 	 * selected for deletion.
1347 	 */
1348 	for (APLIST_TRAVERSE(lmalp, idx1, lmp)) {
1349 		Dyninfo	*dip;
1350 		uint_t	cnt, max;
1351 
1352 		if (FLAGS(lmp) & FLG_RT_DELETE)
1353 			remove_lists(lmp, 0);
1354 
1355 		/*
1356 		 * Determine whether we're dealing with a filter, and if so
1357 		 * process any inter-dependencies with its filtee's.
1358 		 */
1359 		if ((FLAGS1(lmp) & MSK_RT_FILTER) == 0)
1360 			continue;
1361 
1362 		dip = DYNINFO(lmp);
1363 		max = DYNINFOCNT(lmp);
1364 
1365 		for (cnt = 0; cnt < max; cnt++, dip++) {
1366 			Alist	*falp;
1367 			Aliste	idx2;
1368 			Pdesc	*pdp;
1369 
1370 			if (((falp = (Alist *)dip->di_info) == NULL) ||
1371 			    ((dip->di_flags & MSK_DI_FILTER) == 0))
1372 				continue;
1373 
1374 			for (ALIST_TRAVERSE(falp, idx2, pdp)) {
1375 				Grp_hdl	*ghp;
1376 
1377 				if ((pdp->pd_plen == 0) ||
1378 				    ((ghp = (Grp_hdl *)pdp->pd_info) == NULL))
1379 					continue;
1380 
1381 				/*
1382 				 * Determine whether this filtee's handle is a
1383 				 * part of the list of handles being deleted.
1384 				 */
1385 				if (aplist_test(&ghalp, ghp, 0) == ALE_EXISTS) {
1386 					/*
1387 					 * If this handle exists on the deletion
1388 					 * list, then it has been removed.  If
1389 					 * this filter isn't going to be
1390 					 * deleted, sever its reference to the
1391 					 * handle.
1392 					 */
1393 					pdp->pd_info = NULL;
1394 				} else {
1395 					/*
1396 					 * If this handle isn't on the deletion
1397 					 * list, then it must still exist.  If
1398 					 * this filter is being deleted, make
1399 					 * sure the filtees reference count
1400 					 * gets decremented.
1401 					 */
1402 					if (FLAGS(lmp) & FLG_RT_DELETE) {
1403 						(void) dlclose_core(ghp,
1404 						    lmp, lml);
1405 					}
1406 				}
1407 			}
1408 		}
1409 	}
1410 
1411 	/*
1412 	 * If called from dlclose(), determine if there are already handles on
1413 	 * the orphans list that we can reinvestigate.
1414 	 */
1415 	if ((removed == 0) && aplist_nitems(hdl_alp[HDLIST_ORP]))
1416 		orphans = 1;
1417 	else
1418 		orphans = 0;
1419 
1420 	/*
1421 	 * Finally remove any handle infrastructure and remove any objects
1422 	 * marked for deletion.
1423 	 */
1424 	for (APLIST_TRAVERSE(ghalp, idx1, ghp2)) {
1425 		Grp_hdl	*ghp = ghp2;
1426 
1427 		/*
1428 		 * If we're not dealing with orphaned handles remove this handle
1429 		 * from its present handle list.
1430 		 */
1431 		if (removed == 0) {
1432 			uintptr_t ndx;
1433 
1434 			/* LINTED */
1435 			ndx = (uintptr_t)ghp % HDLIST_SZ;
1436 			(void) aplist_delete_value(hdl_alp[ndx], ghp);
1437 		}
1438 
1439 		/*
1440 		 * Traverse each handle dependency.  Retain the dependencies
1441 		 * flags to insure we don't delete any parents (the flags
1442 		 * information is deleted as part of the alist removal that
1443 		 * occurs before we inspect the object for deletion).
1444 		 */
1445 		for (ALIST_TRAVERSE(ghp->gh_depends, idx2, gdp)) {
1446 			uint_t	flags = gdp->gd_flags;
1447 
1448 			if ((flags & GPD_REMOVE) == 0)
1449 				continue;
1450 
1451 			lmp = gdp->gd_depend;
1452 			rmcnt++;
1453 
1454 			/*
1455 			 * If this object is the owner of the handle break that
1456 			 * association in case the handle is retained.
1457 			 */
1458 			if (ghp->gh_ownlmp == lmp) {
1459 				(void) aplist_delete_value(HANDLES(lmp), ghp);
1460 				ghp->gh_ownlmp = NULL;
1461 			}
1462 
1463 			(void) aplist_delete_value(GROUPS(lmp), ghp);
1464 			alist_delete(ghp->gh_depends, &idx2);
1465 
1466 			/*
1467 			 * Complete the link-map deletion if appropriate.
1468 			 */
1469 			if ((FLAGS(lmp) & FLG_RT_DELETE) &&
1470 			    ((flags & GPD_PARENT) == 0)) {
1471 				tls_modaddrem(lmp, TM_FLG_MODREM);
1472 				remove_so(LIST(lmp), lmp);
1473 			}
1474 		}
1475 
1476 		/*
1477 		 * If we've deleted all the dependencies of the handle, finalize
1478 		 * the cleanup by removing the handle itself.
1479 		 *
1480 		 * Otherwise we're left with a handle containing one or more
1481 		 * objects that can not be deleted (they're in use by other
1482 		 * handles, non-deletable, etc.), but require to remain a part
1483 		 * of this group to allow them to continue binding to one
1484 		 * another.
1485 		 *
1486 		 * If the handles reference count is zero, or represents a
1487 		 * link-map list (dlopen(0)), then move that handle to the
1488 		 * orphans list.  Should another dlclose() operation occur that
1489 		 * results in the removal of handle descriptors, these orphan
1490 		 * handles are re-examined to determine if their deletion can
1491 		 * be completed.
1492 		 */
1493 		if (ghp->gh_depends->al_nitems == 0) {
1494 			free(ghp->gh_depends);
1495 			free(ghp);
1496 
1497 		} else if ((ghp->gh_refcnt == 0) &&
1498 		    ((ghp->gh_flags & GPH_ZERO) == 0)) {
1499 			/*
1500 			 * Move this handle to the orphans list.
1501 			 */
1502 			(void) aplist_append(&hdl_alp[HDLIST_ORP], ghp,
1503 			    AL_CNT_HANDLES);
1504 
1505 			if (DBG_ENABLED) {
1506 				DBG_CALL(Dbg_file_hdl_title(DBG_HDL_ORPHAN));
1507 				for (ALIST_TRAVERSE(ghp->gh_depends, idx1, gdp))
1508 					DBG_CALL(Dbg_file_hdl_action(ghp,
1509 					    gdp->gd_depend, DBG_DEP_ORPHAN, 0));
1510 			}
1511 		}
1512 	}
1513 
1514 	/*
1515 	 * If no handle descriptors got removed there's no point in looking for
1516 	 * orphans to process.
1517 	 */
1518 	if (rmcnt == 0)
1519 		orphans = 0;
1520 
1521 	/*
1522 	 * Cleanup any alists we've created.
1523 	 */
1524 	remove_collect(ghalp, lmalp);
1525 
1526 	/*
1527 	 * If orphan processing isn't required we're done.  If our processing
1528 	 * originated from investigating orphans, return the number of handle
1529 	 * descriptors removed as an indication whether orphan processing
1530 	 * should continue.
1531 	 */
1532 	if (orphans == 0) {
1533 		if (removed)
1534 			*removed = rmcnt;
1535 		return (error);
1536 	}
1537 
1538 	/*
1539 	 * Traverse the orphans list as many times as necessary until no
1540 	 * handle removals occur.
1541 	 */
1542 	do {
1543 		APlist		*alp;
1544 		Aliste		idx;
1545 		Grp_hdl		*ghp, *oghp = NULL;
1546 		int		title = 0;
1547 
1548 		/*
1549 		 * Effectively clean the HDLIST_ORP list.  Any object that can't
1550 		 * be removed will be re-added to the list.
1551 		 */
1552 		alp = hdl_alp[HDLIST_ORP];
1553 		hdl_alp[HDLIST_ORP] = NULL;
1554 
1555 		rescan = 0;
1556 		for (APLIST_TRAVERSE(alp, idx, ghp)) {
1557 			int	_error, _remove;
1558 
1559 			if (title++ == 0)
1560 				DBG_CALL(Dbg_file_del_rescan(ghp->gh_ownlml));
1561 
1562 			if (oghp) {
1563 				(void) aplist_delete_value(alp, oghp);
1564 				oghp = NULL;
1565 			}
1566 
1567 			if (((_error = remove_hdl(ghp, clmp, &_remove)) != 0) &&
1568 			    (error == 0))
1569 				error = _error;
1570 
1571 			if (_remove)
1572 				rescan++;
1573 
1574 			oghp = ghp;
1575 		}
1576 		if (oghp) {
1577 			(void) aplist_delete_value(alp, oghp);
1578 			oghp = NULL;
1579 		}
1580 		if (alp)
1581 			free((void *)alp);
1582 
1583 	} while (rescan && aplist_nitems(hdl_alp[HDLIST_ORP]));
1584 
1585 	return (error);
1586 }
1587