xref: /netbsd-src/external/cddl/osnet/dist/tools/ctf/cvt/ctfmerge.c (revision 6cf6fe02a981b55727c49c3d37b0d8191a98c0ee)
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  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Given several files containing CTF data, merge and uniquify that data into
30  * a single CTF section in an output file.
31  *
32  * Merges can proceed independently.  As such, we perform the merges in parallel
33  * using a worker thread model.  A given glob of CTF data (either all of the CTF
34  * data from a single input file, or the result of one or more merges) can only
35  * be involved in a single merge at any given time, so the process decreases in
36  * parallelism, especially towards the end, as more and more files are
37  * consolidated, finally resulting in a single merge of two large CTF graphs.
38  * Unfortunately, the last merge is also the slowest, as the two graphs being
39  * merged are each the product of merges of half of the input files.
40  *
41  * The algorithm consists of two phases, described in detail below.  The first
42  * phase entails the merging of CTF data in groups of eight.  The second phase
43  * takes the results of Phase I, and merges them two at a time.  This disparity
44  * is due to an observation that the merge time increases at least quadratically
45  * with the size of the CTF data being merged.  As such, merges of CTF graphs
46  * newly read from input files are much faster than merges of CTF graphs that
47  * are themselves the results of prior merges.
48  *
49  * A further complication is the need to ensure the repeatability of CTF merges.
50  * That is, a merge should produce the same output every time, given the same
51  * input.  In both phases, this consistency requirement is met by imposing an
52  * ordering on the merge process, thus ensuring that a given set of input files
53  * are merged in the same order every time.
54  *
55  *   Phase I
56  *
57  *   The main thread reads the input files one by one, transforming the CTF
58  *   data they contain into tdata structures.  When a given file has been read
59  *   and parsed, it is placed on the work queue for retrieval by worker threads.
60  *
61  *   Central to Phase I is the Work In Progress (wip) array, which is used to
62  *   merge batches of files in a predictable order.  Files are read by the main
63  *   thread, and are merged into wip array elements in round-robin order.  When
64  *   the number of files merged into a given array slot equals the batch size,
65  *   the merged CTF graph in that array is added to the done slot in order by
66  *   array slot.
67  *
68  *   For example, consider a case where we have five input files, a batch size
69  *   of two, a wip array size of two, and two worker threads (T1 and T2).
70  *
71  *    1. The wip array elements are assigned initial batch numbers 0 and 1.
72  *    2. T1 reads an input file from the input queue (wq_queue).  This is the
73  *       first input file, so it is placed into wip[0].  The second file is
74  *       similarly read and placed into wip[1].  The wip array slots now contain
75  *       one file each (wip_nmerged == 1).
76  *    3. T1 reads the third input file, which it merges into wip[0].  The
77  *       number of files in wip[0] is equal to the batch size.
78  *    4. T2 reads the fourth input file, which it merges into wip[1].  wip[1]
79  *       is now full too.
80  *    5. T2 attempts to place the contents of wip[1] on the done queue
81  *       (wq_done_queue), but it can't, since the batch ID for wip[1] is 1.
82  *       Batch 0 needs to be on the done queue before batch 1 can be added, so
83  *       T2 blocks on wip[1]'s cv.
84  *    6. T1 attempts to place the contents of wip[0] on the done queue, and
85  *       succeeds, updating wq_lastdonebatch to 0.  It clears wip[0], and sets
86  *       its batch ID to 2.  T1 then signals wip[1]'s cv to awaken T2.
87  *    7. T2 wakes up, notices that wq_lastdonebatch is 0, which means that
88  *       batch 1 can now be added.  It adds wip[1] to the done queue, clears
89  *       wip[1], and sets its batch ID to 3.  It signals wip[0]'s cv, and
90  *       restarts.
91  *
92  *   The above process continues until all input files have been consumed.  At
93  *   this point, a pair of barriers are used to allow a single thread to move
94  *   any partial batches from the wip array to the done array in batch ID order.
95  *   When this is complete, wq_done_queue is moved to wq_queue, and Phase II
96  *   begins.
97  *
98  *	Locking Semantics (Phase I)
99  *
100  *	The input queue (wq_queue) and the done queue (wq_done_queue) are
101  *	protected by separate mutexes - wq_queue_lock and wq_done_queue.  wip
102  *	array slots are protected by their own mutexes, which must be grabbed
103  *	before releasing the input queue lock.  The wip array lock is dropped
104  *	when the thread restarts the loop.  If the array slot was full, the
105  *	array lock will be held while the slot contents are added to the done
106  *	queue.  The done queue lock is used to protect the wip slot cv's.
107  *
108  *	The pow number is protected by the queue lock.  The master batch ID
109  *	and last completed batch (wq_lastdonebatch) counters are protected *in
110  *	Phase I* by the done queue lock.
111  *
112  *   Phase II
113  *
114  *   When Phase II begins, the queue consists of the merged batches from the
115  *   first phase.  Assume we have five batches:
116  *
117  *	Q:	a b c d e
118  *
119  *   Using the same batch ID mechanism we used in Phase I, but without the wip
120  *   array, worker threads remove two entries at a time from the beginning of
121  *   the queue.  These two entries are merged, and are added back to the tail
122  *   of the queue, as follows:
123  *
124  *	Q:	a b c d e	# start
125  *	Q:	c d e ab	# a, b removed, merged, added to end
126  *	Q:	e ab cd		# c, d removed, merged, added to end
127  *	Q:	cd eab		# e, ab removed, merged, added to end
128  *	Q:	cdeab		# cd, eab removed, merged, added to end
129  *
130  *   When one entry remains on the queue, with no merges outstanding, Phase II
131  *   finishes.  We pre-determine the stopping point by pre-calculating the
132  *   number of nodes that will appear on the list.  In the example above, the
133  *   number (wq_ninqueue) is 9.  When ninqueue is 1, we conclude Phase II by
134  *   signaling the main thread via wq_done_cv.
135  *
136  *	Locking Semantics (Phase II)
137  *
138  *	The queue (wq_queue), ninqueue, and the master batch ID and last
139  *	completed batch counters are protected by wq_queue_lock.  The done
140  *	queue and corresponding lock are unused in Phase II as is the wip array.
141  *
142  *   Uniquification
143  *
144  *   We want the CTF data that goes into a given module to be as small as
145  *   possible.  For example, we don't want it to contain any type data that may
146  *   be present in another common module.  As such, after creating the master
147  *   tdata_t for a given module, we can, if requested by the user, uniquify it
148  *   against the tdata_t from another module (genunix in the case of the SunOS
149  *   kernel).  We perform a merge between the tdata_t for this module and the
150  *   tdata_t from genunix.  Nodes found in this module that are not present in
151  *   genunix are added to a third tdata_t - the uniquified tdata_t.
152  *
153  *   Additive Merges
154  *
155  *   In some cases, for example if we are issuing a new version of a common
156  *   module in a patch, we need to make sure that the CTF data already present
157  *   in that module does not change.  Changes to this data would void the CTF
158  *   data in any module that uniquified against the common module.  To preserve
159  *   the existing data, we can perform what is known as an additive merge.  In
160  *   this case, a final uniquification is performed against the CTF data in the
161  *   previous version of the module.  The result will be the placement of new
162  *   and changed data after the existing data, thus preserving the existing type
163  *   ID space.
164  *
165  *   Saving the result
166  *
167  *   When the merges are complete, the resulting tdata_t is placed into the
168  *   output file, replacing the .SUNW_ctf section (if any) already in that file.
169  *
170  * The person who changes the merging thread code in this file without updating
171  * this comment will not live to see the stock hit five.
172  */
173 
174 #if HAVE_NBTOOL_CONFIG_H
175 # include "nbtool_config.h"
176 #endif
177 
178 #include <stdio.h>
179 #include <stdlib.h>
180 #include <unistd.h>
181 #include <pthread.h>
182 #include <assert.h>
183 #if defined(sun)
184 #include <synch.h>
185 #endif
186 #include <signal.h>
187 #include <libgen.h>
188 #include <string.h>
189 #include <errno.h>
190 #if defined(sun)
191 #include <alloca.h>
192 #endif
193 #include <sys/param.h>
194 #include <sys/types.h>
195 #include <sys/mman.h>
196 #if defined(sun)
197 #include <sys/sysconf.h>
198 #endif
199 
200 #include "ctf_headers.h"
201 #include "ctftools.h"
202 #include "ctfmerge.h"
203 #include "traverse.h"
204 #include "memory.h"
205 #include "fifo.h"
206 #include "barrier.h"
207 
208 #pragma init(bigheap)
209 
210 #define	MERGE_PHASE1_BATCH_SIZE		8
211 #define	MERGE_PHASE1_MAX_SLOTS		5
212 #define	MERGE_INPUT_THROTTLE_LEN	10
213 
214 const char *progname;
215 static char *outfile = NULL;
216 static char *tmpname = NULL;
217 static int dynsym;
218 int debug_level = DEBUG_LEVEL;
219 static size_t maxpgsize = 0x400000;
220 static int maxslots = MERGE_PHASE1_MAX_SLOTS;
221 
222 
223 void
224 usage(void)
225 {
226 	(void) fprintf(stderr,
227 	    "Usage: %s [-fgstv] -l label | -L labelenv -o outfile file ...\n"
228 	    "       %s [-fgstv] -l label | -L labelenv -o outfile -d uniqfile\n"
229 	    "       %*s [-g] [-D uniqlabel] file ...\n"
230 	    "       %s [-fgstv] -l label | -L labelenv -o outfile -w withfile "
231 	    "file ...\n"
232 	    "       %s [-g] -c srcfile destfile\n"
233 	    "\n"
234 	    "  Note: if -L labelenv is specified and labelenv is not set in\n"
235 	    "  the environment, a default value is used.\n",
236 	    progname, progname, (int)strlen(progname), " ",
237 	    progname, progname);
238 }
239 
240 #if defined(sun)
241 static void
242 bigheap(void)
243 {
244 	size_t big, *size;
245 	int sizes;
246 	struct memcntl_mha mha;
247 
248 	/*
249 	 * First, get the available pagesizes.
250 	 */
251 	if ((sizes = getpagesizes(NULL, 0)) == -1)
252 		return;
253 
254 	if (sizes == 1 || (size = alloca(sizeof (size_t) * sizes)) == NULL)
255 		return;
256 
257 	if (getpagesizes(size, sizes) == -1)
258 		return;
259 
260 	while (size[sizes - 1] > maxpgsize)
261 		sizes--;
262 
263 	/* set big to the largest allowed page size */
264 	big = size[sizes - 1];
265 	if (big & (big - 1)) {
266 		/*
267 		 * The largest page size is not a power of two for some
268 		 * inexplicable reason; return.
269 		 */
270 		return;
271 	}
272 
273 	/*
274 	 * Now, align our break to the largest page size.
275 	 */
276 	if (brk((void *)((((uintptr_t)sbrk(0) - 1) & ~(big - 1)) + big)) != 0)
277 		return;
278 
279 	/*
280 	 * set the preferred page size for the heap
281 	 */
282 	mha.mha_cmd = MHA_MAPSIZE_BSSBRK;
283 	mha.mha_flags = 0;
284 	mha.mha_pagesize = big;
285 
286 	(void) memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mha, 0, 0);
287 }
288 #endif
289 
290 static void
291 finalize_phase_one(workqueue_t *wq)
292 {
293 	int startslot, i;
294 
295 	/*
296 	 * wip slots are cleared out only when maxbatchsz td's have been merged
297 	 * into them.  We're not guaranteed that the number of files we're
298 	 * merging is a multiple of maxbatchsz, so there will be some partial
299 	 * groups in the wip array.  Move them to the done queue in batch ID
300 	 * order, starting with the slot containing the next batch that would
301 	 * have been placed on the done queue, followed by the others.
302 	 * One thread will be doing this while the others wait at the barrier
303 	 * back in worker_thread(), so we don't need to worry about pesky things
304 	 * like locks.
305 	 */
306 
307 	for (startslot = -1, i = 0; i < wq->wq_nwipslots; i++) {
308 		if (wq->wq_wip[i].wip_batchid == wq->wq_lastdonebatch + 1) {
309 			startslot = i;
310 			break;
311 		}
312 	}
313 
314 	assert(startslot != -1);
315 
316 	for (i = startslot; i < startslot + wq->wq_nwipslots; i++) {
317 		int slotnum = i % wq->wq_nwipslots;
318 		wip_t *wipslot = &wq->wq_wip[slotnum];
319 
320 		if (wipslot->wip_td != NULL) {
321 			debug(2, "clearing slot %d (%d) (saving %d)\n",
322 			    slotnum, i, wipslot->wip_nmerged);
323 		} else
324 			debug(2, "clearing slot %d (%d)\n", slotnum, i);
325 
326 		if (wipslot->wip_td != NULL) {
327 			fifo_add(wq->wq_donequeue, wipslot->wip_td);
328 			wq->wq_wip[slotnum].wip_td = NULL;
329 		}
330 	}
331 
332 	wq->wq_lastdonebatch = wq->wq_next_batchid++;
333 
334 	debug(2, "phase one done: donequeue has %d items\n",
335 	    fifo_len(wq->wq_donequeue));
336 }
337 
338 static void
339 init_phase_two(workqueue_t *wq)
340 {
341 	int num;
342 
343 	/*
344 	 * We're going to continually merge the first two entries on the queue,
345 	 * placing the result on the end, until there's nothing left to merge.
346 	 * At that point, everything will have been merged into one.  The
347 	 * initial value of ninqueue needs to be equal to the total number of
348 	 * entries that will show up on the queue, both at the start of the
349 	 * phase and as generated by merges during the phase.
350 	 */
351 	wq->wq_ninqueue = num = fifo_len(wq->wq_donequeue);
352 	while (num != 1) {
353 		wq->wq_ninqueue += num / 2;
354 		num = num / 2 + num % 2;
355 	}
356 
357 	/*
358 	 * Move the done queue to the work queue.  We won't be using the done
359 	 * queue in phase 2.
360 	 */
361 	assert(fifo_len(wq->wq_queue) == 0);
362 	fifo_free(wq->wq_queue, NULL);
363 	wq->wq_queue = wq->wq_donequeue;
364 }
365 
366 static void
367 wip_save_work(workqueue_t *wq, wip_t *slot, int slotnum)
368 {
369 	pthread_mutex_lock(&wq->wq_donequeue_lock);
370 
371 	while (wq->wq_lastdonebatch + 1 < slot->wip_batchid)
372 		pthread_cond_wait(&slot->wip_cv, &wq->wq_donequeue_lock);
373 	assert(wq->wq_lastdonebatch + 1 == slot->wip_batchid);
374 
375 	fifo_add(wq->wq_donequeue, slot->wip_td);
376 	wq->wq_lastdonebatch++;
377 	pthread_cond_signal(&wq->wq_wip[(slotnum + 1) %
378 	    wq->wq_nwipslots].wip_cv);
379 
380 	/* reset the slot for next use */
381 	slot->wip_td = NULL;
382 	slot->wip_batchid = wq->wq_next_batchid++;
383 
384 	pthread_mutex_unlock(&wq->wq_donequeue_lock);
385 }
386 
387 static void
388 wip_add_work(wip_t *slot, tdata_t *pow)
389 {
390 	if (slot->wip_td == NULL) {
391 		slot->wip_td = pow;
392 		slot->wip_nmerged = 1;
393 	} else {
394 		debug(2, "%d: merging %p into %p\n", pthread_self(),
395 		    (void *)pow, (void *)slot->wip_td);
396 
397 		merge_into_master(pow, slot->wip_td, NULL, 0);
398 		tdata_free(pow);
399 
400 		slot->wip_nmerged++;
401 	}
402 }
403 
404 static void
405 worker_runphase1(workqueue_t *wq)
406 {
407 	wip_t *wipslot;
408 	tdata_t *pow;
409 	int wipslotnum, pownum;
410 
411 	for (;;) {
412 		pthread_mutex_lock(&wq->wq_queue_lock);
413 
414 		while (fifo_empty(wq->wq_queue)) {
415 			if (wq->wq_nomorefiles == 1) {
416 				pthread_cond_broadcast(&wq->wq_work_avail);
417 				pthread_mutex_unlock(&wq->wq_queue_lock);
418 
419 				/* on to phase 2 ... */
420 				return;
421 			}
422 
423 			pthread_cond_wait(&wq->wq_work_avail,
424 			    &wq->wq_queue_lock);
425 		}
426 
427 		/* there's work to be done! */
428 		pow = fifo_remove(wq->wq_queue);
429 		pownum = wq->wq_nextpownum++;
430 		pthread_cond_broadcast(&wq->wq_work_removed);
431 
432 		assert(pow != NULL);
433 
434 		/* merge it into the right slot */
435 		wipslotnum = pownum % wq->wq_nwipslots;
436 		wipslot = &wq->wq_wip[wipslotnum];
437 
438 		pthread_mutex_lock(&wipslot->wip_lock);
439 
440 		pthread_mutex_unlock(&wq->wq_queue_lock);
441 
442 		wip_add_work(wipslot, pow);
443 
444 		if (wipslot->wip_nmerged == wq->wq_maxbatchsz)
445 			wip_save_work(wq, wipslot, wipslotnum);
446 
447 		pthread_mutex_unlock(&wipslot->wip_lock);
448 	}
449 }
450 
451 static void
452 worker_runphase2(workqueue_t *wq)
453 {
454 	tdata_t *pow1, *pow2;
455 	int batchid;
456 
457 	for (;;) {
458 		pthread_mutex_lock(&wq->wq_queue_lock);
459 
460 		if (wq->wq_ninqueue == 1) {
461 			pthread_cond_broadcast(&wq->wq_work_avail);
462 			pthread_mutex_unlock(&wq->wq_queue_lock);
463 
464 			debug(2, "%d: entering p2 completion barrier\n",
465 			    pthread_self());
466 			if (barrier_wait(&wq->wq_bar1)) {
467 				pthread_mutex_lock(&wq->wq_queue_lock);
468 				wq->wq_alldone = 1;
469 				pthread_cond_signal(&wq->wq_alldone_cv);
470 				pthread_mutex_unlock(&wq->wq_queue_lock);
471 			}
472 
473 			return;
474 		}
475 
476 		if (fifo_len(wq->wq_queue) < 2) {
477 			pthread_cond_wait(&wq->wq_work_avail,
478 			    &wq->wq_queue_lock);
479 			pthread_mutex_unlock(&wq->wq_queue_lock);
480 			continue;
481 		}
482 
483 		/* there's work to be done! */
484 		pow1 = fifo_remove(wq->wq_queue);
485 		pow2 = fifo_remove(wq->wq_queue);
486 		wq->wq_ninqueue -= 2;
487 
488 		batchid = wq->wq_next_batchid++;
489 
490 		pthread_mutex_unlock(&wq->wq_queue_lock);
491 
492 		debug(2, "%d: merging %p into %p\n", pthread_self(),
493 		    (void *)pow1, (void *)pow2);
494 		merge_into_master(pow1, pow2, NULL, 0);
495 		tdata_free(pow1);
496 
497 		/*
498 		 * merging is complete.  place at the tail of the queue in
499 		 * proper order.
500 		 */
501 		pthread_mutex_lock(&wq->wq_queue_lock);
502 		while (wq->wq_lastdonebatch + 1 != batchid) {
503 			pthread_cond_wait(&wq->wq_done_cv,
504 			    &wq->wq_queue_lock);
505 		}
506 
507 		wq->wq_lastdonebatch = batchid;
508 
509 		fifo_add(wq->wq_queue, pow2);
510 		debug(2, "%d: added %p to queue, len now %d, ninqueue %d\n",
511 		    pthread_self(), (void *)pow2, fifo_len(wq->wq_queue),
512 		    wq->wq_ninqueue);
513 		pthread_cond_broadcast(&wq->wq_done_cv);
514 		pthread_cond_signal(&wq->wq_work_avail);
515 		pthread_mutex_unlock(&wq->wq_queue_lock);
516 	}
517 }
518 
519 /*
520  * Main loop for worker threads.
521  */
522 static void
523 worker_thread(workqueue_t *wq)
524 {
525 	worker_runphase1(wq);
526 
527 	debug(2, "%d: entering first barrier\n", pthread_self());
528 
529 	if (barrier_wait(&wq->wq_bar1)) {
530 
531 		debug(2, "%d: doing work in first barrier\n", pthread_self());
532 
533 		finalize_phase_one(wq);
534 
535 		init_phase_two(wq);
536 
537 		debug(2, "%d: ninqueue is %d, %d on queue\n", pthread_self(),
538 		    wq->wq_ninqueue, fifo_len(wq->wq_queue));
539 	}
540 
541 	debug(2, "%d: entering second barrier\n", pthread_self());
542 
543 	(void) barrier_wait(&wq->wq_bar2);
544 
545 	debug(2, "%d: phase 1 complete\n", pthread_self());
546 
547 	worker_runphase2(wq);
548 }
549 
550 /*
551  * Pass a tdata_t tree, built from an input file, off to the work queue for
552  * consumption by worker threads.
553  */
554 static int
555 merge_ctf_cb(tdata_t *td, char *name, void *arg)
556 {
557 	workqueue_t *wq = arg;
558 
559 	debug(3, "Adding tdata %p for processing\n", (void *)td);
560 
561 	pthread_mutex_lock(&wq->wq_queue_lock);
562 	while (fifo_len(wq->wq_queue) > wq->wq_ithrottle) {
563 		debug(2, "Throttling input (len = %d, throttle = %d)\n",
564 		    fifo_len(wq->wq_queue), wq->wq_ithrottle);
565 		pthread_cond_wait(&wq->wq_work_removed, &wq->wq_queue_lock);
566 	}
567 
568 	fifo_add(wq->wq_queue, td);
569 	debug(1, "Thread %d announcing %s\n", pthread_self(), name);
570 	pthread_cond_broadcast(&wq->wq_work_avail);
571 	pthread_mutex_unlock(&wq->wq_queue_lock);
572 
573 	return (1);
574 }
575 
576 /*
577  * This program is intended to be invoked from a Makefile, as part of the build.
578  * As such, in the event of a failure or user-initiated interrupt (^C), we need
579  * to ensure that a subsequent re-make will cause ctfmerge to be executed again.
580  * Unfortunately, ctfmerge will usually be invoked directly after (and as part
581  * of the same Makefile rule as) a link, and will operate on the linked file
582  * in place.  If we merely exit upon receipt of a SIGINT, a subsequent make
583  * will notice that the *linked* file is newer than the object files, and thus
584  * will not reinvoke ctfmerge.  The only way to ensure that a subsequent make
585  * reinvokes ctfmerge, is to remove the file to which we are adding CTF
586  * data (confusingly named the output file).  This means that the link will need
587  * to happen again, but links are generally fast, and we can't allow the merge
588  * to be skipped.
589  *
590  * Another possibility would be to block SIGINT entirely - to always run to
591  * completion.  The run time of ctfmerge can, however, be measured in minutes
592  * in some cases, so this is not a valid option.
593  */
594 static void
595 handle_sig(int sig)
596 {
597 	terminate("Caught signal %d - exiting\n", sig);
598 }
599 
600 static void
601 terminate_cleanup(void)
602 {
603 	int dounlink = getenv("CTFMERGE_TERMINATE_NO_UNLINK") ? 0 : 1;
604 
605 	if (tmpname != NULL && dounlink)
606 		unlink(tmpname);
607 
608 	if (outfile == NULL)
609 		return;
610 
611 #if !defined(__FreeBSD__)
612 	if (dounlink) {
613 		fprintf(stderr, "Removing %s\n", outfile);
614 		unlink(outfile);
615 	}
616 #endif
617 }
618 
619 static void
620 copy_ctf_data(char *srcfile, char *destfile, int keep_stabs)
621 {
622 	tdata_t *srctd;
623 
624 	if (read_ctf(&srcfile, 1, NULL, read_ctf_save_cb, &srctd, 1) == 0)
625 		terminate("No CTF data found in source file %s\n", srcfile);
626 
627 	tmpname = mktmpname(destfile, ".ctf");
628 	write_ctf(srctd, destfile, tmpname, CTF_COMPRESS | CTF_SWAP_BYTES | keep_stabs);
629 	if (rename(tmpname, destfile) != 0) {
630 		terminate("Couldn't rename temp file %s to %s", tmpname,
631 		    destfile);
632 	}
633 	free(tmpname);
634 	tdata_free(srctd);
635 }
636 
637 static void
638 wq_init(workqueue_t *wq, int nfiles)
639 {
640 	int throttle, nslots, i;
641 
642 	if (getenv("CTFMERGE_MAX_SLOTS"))
643 		nslots = atoi(getenv("CTFMERGE_MAX_SLOTS"));
644 	else
645 		nslots = maxslots;
646 
647 	if (getenv("CTFMERGE_PHASE1_BATCH_SIZE"))
648 		wq->wq_maxbatchsz = atoi(getenv("CTFMERGE_PHASE1_BATCH_SIZE"));
649 	else
650 		wq->wq_maxbatchsz = MERGE_PHASE1_BATCH_SIZE;
651 
652 	nslots = MIN(nslots, (nfiles + wq->wq_maxbatchsz - 1) /
653 	    wq->wq_maxbatchsz);
654 
655 	wq->wq_wip = xcalloc(sizeof (wip_t) * nslots);
656 	wq->wq_nwipslots = nslots;
657 #ifdef _SC_NPROCESSORS_ONLN
658 	wq->wq_nthreads = MIN(sysconf(_SC_NPROCESSORS_ONLN) * 3 / 2, nslots);
659 #else
660 	wq->wq_nthreads = 2;
661 #endif
662 	wq->wq_thread = xmalloc(sizeof (pthread_t) * wq->wq_nthreads);
663 
664 	if (getenv("CTFMERGE_INPUT_THROTTLE"))
665 		throttle = atoi(getenv("CTFMERGE_INPUT_THROTTLE"));
666 	else
667 		throttle = MERGE_INPUT_THROTTLE_LEN;
668 	wq->wq_ithrottle = throttle * wq->wq_nthreads;
669 
670 	debug(1, "Using %d slots, %d threads\n", wq->wq_nwipslots,
671 	    wq->wq_nthreads);
672 
673 	wq->wq_next_batchid = 0;
674 
675 	for (i = 0; i < nslots; i++) {
676 		pthread_mutex_init(&wq->wq_wip[i].wip_lock, NULL);
677 		wq->wq_wip[i].wip_batchid = wq->wq_next_batchid++;
678 	}
679 
680 	pthread_mutex_init(&wq->wq_queue_lock, NULL);
681 	wq->wq_queue = fifo_new();
682 	pthread_cond_init(&wq->wq_work_avail, NULL);
683 	pthread_cond_init(&wq->wq_work_removed, NULL);
684 	wq->wq_ninqueue = nfiles;
685 	wq->wq_nextpownum = 0;
686 
687 	pthread_mutex_init(&wq->wq_donequeue_lock, NULL);
688 	wq->wq_donequeue = fifo_new();
689 	wq->wq_lastdonebatch = -1;
690 
691 	pthread_cond_init(&wq->wq_done_cv, NULL);
692 
693 	pthread_cond_init(&wq->wq_alldone_cv, NULL);
694 	wq->wq_alldone = 0;
695 
696 	barrier_init(&wq->wq_bar1, wq->wq_nthreads);
697 	barrier_init(&wq->wq_bar2, wq->wq_nthreads);
698 
699 	wq->wq_nomorefiles = 0;
700 }
701 
702 static void
703 start_threads(workqueue_t *wq)
704 {
705 	sigset_t sets;
706 	int i;
707 
708 	sigemptyset(&sets);
709 	sigaddset(&sets, SIGINT);
710 	sigaddset(&sets, SIGQUIT);
711 	sigaddset(&sets, SIGTERM);
712 	pthread_sigmask(SIG_BLOCK, &sets, NULL);
713 
714 	for (i = 0; i < wq->wq_nthreads; i++) {
715 		pthread_create(&wq->wq_thread[i], NULL,
716 		    (void *(*)(void *))worker_thread, wq);
717 	}
718 
719 #if defined(sun)
720 	sigset(SIGINT, handle_sig);
721 	sigset(SIGQUIT, handle_sig);
722 	sigset(SIGTERM, handle_sig);
723 #else
724 	signal(SIGINT, handle_sig);
725 	signal(SIGQUIT, handle_sig);
726 	signal(SIGTERM, handle_sig);
727 #endif
728 	pthread_sigmask(SIG_UNBLOCK, &sets, NULL);
729 }
730 
731 static void
732 join_threads(workqueue_t *wq)
733 {
734 	int i;
735 
736 	for (i = 0; i < wq->wq_nthreads; i++) {
737 		pthread_join(wq->wq_thread[i], NULL);
738 	}
739 }
740 
741 static int
742 strcompare(const void *p1, const void *p2)
743 {
744 	char *s1 = *((char **)p1);
745 	char *s2 = *((char **)p2);
746 
747 	return (strcmp(s1, s2));
748 }
749 
750 /*
751  * Core work queue structure; passed to worker threads on thread creation
752  * as the main point of coordination.  Allocate as a static structure; we
753  * could have put this into a local variable in main, but passing a pointer
754  * into your stack to another thread is fragile at best and leads to some
755  * hard-to-debug failure modes.
756  */
757 static workqueue_t wq;
758 
759 int
760 main(int argc, char **argv)
761 {
762 	tdata_t *mstrtd, *savetd;
763 	char *uniqfile = NULL, *uniqlabel = NULL;
764 	char *withfile = NULL;
765 	char *label = NULL;
766 	char **ifiles, **tifiles;
767 	int verbose = 0, docopy = 0;
768 	int write_fuzzy_match = 0;
769 	int keep_stabs = 0;
770 	int require_ctf = 0;
771 	int nifiles, nielems;
772 	int c, i, idx, tidx, err;
773 
774 	progname = basename(argv[0]);
775 
776 	if (getenv("CTFMERGE_DEBUG_LEVEL"))
777 		debug_level = atoi(getenv("CTFMERGE_DEBUG_LEVEL"));
778 
779 	err = 0;
780 	while ((c = getopt(argc, argv, ":cd:D:fgl:L:o:tvw:sS:")) != EOF) {
781 		switch (c) {
782 		case 'c':
783 			docopy = 1;
784 			break;
785 		case 'd':
786 			/* Uniquify against `uniqfile' */
787 			uniqfile = optarg;
788 			break;
789 		case 'D':
790 			/* Uniquify against label `uniqlabel' in `uniqfile' */
791 			uniqlabel = optarg;
792 			break;
793 		case 'f':
794 			write_fuzzy_match = CTF_FUZZY_MATCH;
795 			break;
796 		case 'g':
797 			keep_stabs = CTF_KEEP_STABS;
798 			break;
799 		case 'l':
800 			/* Label merged types with `label' */
801 			label = optarg;
802 			break;
803 		case 'L':
804 			/* Label merged types with getenv(`label`) */
805 			if ((label = getenv(optarg)) == NULL)
806 				label = CTF_DEFAULT_LABEL;
807 			break;
808 		case 'o':
809 			/* Place merged types in CTF section in `outfile' */
810 			outfile = optarg;
811 			break;
812 		case 't':
813 			/* Insist *all* object files built from C have CTF */
814 			require_ctf = 1;
815 			break;
816 		case 'v':
817 			/* More debugging information */
818 			verbose = 1;
819 			break;
820 		case 'w':
821 			/* Additive merge with data from `withfile' */
822 			withfile = optarg;
823 			break;
824 		case 's':
825 			/* use the dynsym rather than the symtab */
826 			dynsym = CTF_USE_DYNSYM;
827 			break;
828 		case 'S':
829 			maxslots = atoi(optarg);
830 			break;
831 		default:
832 			usage();
833 			exit(2);
834 		}
835 	}
836 
837 	/* Validate arguments */
838 	if (docopy) {
839 		if (uniqfile != NULL || uniqlabel != NULL || label != NULL ||
840 		    outfile != NULL || withfile != NULL || dynsym != 0)
841 			err++;
842 
843 		if (argc - optind != 2)
844 			err++;
845 	} else {
846 		if (uniqfile != NULL && withfile != NULL)
847 			err++;
848 
849 		if (uniqlabel != NULL && uniqfile == NULL)
850 			err++;
851 
852 		if (outfile == NULL || label == NULL)
853 			err++;
854 
855 		if (argc - optind == 0)
856 			err++;
857 	}
858 
859 	if (err) {
860 		usage();
861 		exit(2);
862 	}
863 
864 	if (getenv("STRIPSTABS_KEEP_STABS") != NULL)
865 		keep_stabs = CTF_KEEP_STABS;
866 
867 	if (uniqfile && access(uniqfile, R_OK) != 0) {
868 		warning("Uniquification file %s couldn't be opened and "
869 		    "will be ignored.\n", uniqfile);
870 		uniqfile = NULL;
871 	}
872 	if (withfile && access(withfile, R_OK) != 0) {
873 		warning("With file %s couldn't be opened and will be "
874 		    "ignored.\n", withfile);
875 		withfile = NULL;
876 	}
877 	if (outfile && access(outfile, R_OK|W_OK) != 0)
878 		terminate("Cannot open output file %s for r/w", outfile);
879 
880 	/*
881 	 * This is ugly, but we don't want to have to have a separate tool
882 	 * (yet) just for copying an ELF section with our specific requirements,
883 	 * so we shoe-horn a copier into ctfmerge.
884 	 */
885 	if (docopy) {
886 		copy_ctf_data(argv[optind], argv[optind + 1], keep_stabs);
887 
888 		exit(0);
889 	}
890 
891 	set_terminate_cleanup(terminate_cleanup);
892 
893 	/* Sort the input files and strip out duplicates */
894 	nifiles = argc - optind;
895 	ifiles = xmalloc(sizeof (char *) * nifiles);
896 	tifiles = xmalloc(sizeof (char *) * nifiles);
897 
898 	for (i = 0; i < nifiles; i++)
899 		tifiles[i] = argv[optind + i];
900 	qsort(tifiles, nifiles, sizeof (char *), (int (*)())strcompare);
901 
902 	ifiles[0] = tifiles[0];
903 	for (idx = 0, tidx = 1; tidx < nifiles; tidx++) {
904 		if (strcmp(ifiles[idx], tifiles[tidx]) != 0)
905 			ifiles[++idx] = tifiles[tidx];
906 	}
907 	nifiles = idx + 1;
908 
909 	/* Make sure they all exist */
910 	if ((nielems = count_files(ifiles, nifiles)) < 0)
911 		terminate("Some input files were inaccessible\n");
912 
913 	/* Prepare for the merge */
914 	wq_init(&wq, nielems);
915 
916 	start_threads(&wq);
917 
918 	/*
919 	 * Start the merge
920 	 *
921 	 * We're reading everything from each of the object files, so we
922 	 * don't need to specify labels.
923 	 */
924 	if (read_ctf(ifiles, nifiles, NULL, merge_ctf_cb,
925 	    &wq, require_ctf) == 0) {
926 		/*
927 		 * If we're verifying that C files have CTF, it's safe to
928 		 * assume that in this case, we're building only from assembly
929 		 * inputs.
930 		 */
931 		if (require_ctf)
932 			exit(0);
933 		terminate("No ctf sections found to merge\n");
934 	}
935 
936 	pthread_mutex_lock(&wq.wq_queue_lock);
937 	wq.wq_nomorefiles = 1;
938 	pthread_cond_broadcast(&wq.wq_work_avail);
939 	pthread_mutex_unlock(&wq.wq_queue_lock);
940 
941 	pthread_mutex_lock(&wq.wq_queue_lock);
942 	while (wq.wq_alldone == 0)
943 		pthread_cond_wait(&wq.wq_alldone_cv, &wq.wq_queue_lock);
944 	pthread_mutex_unlock(&wq.wq_queue_lock);
945 
946 	join_threads(&wq);
947 
948 	/*
949 	 * All requested files have been merged, with the resulting tree in
950 	 * mstrtd.  savetd is the tree that will be placed into the output file.
951 	 *
952 	 * Regardless of whether we're doing a normal uniquification or an
953 	 * additive merge, we need a type tree that has been uniquified
954 	 * against uniqfile or withfile, as appropriate.
955 	 *
956 	 * If we're doing a uniquification, we stuff the resulting tree into
957 	 * outfile.  Otherwise, we add the tree to the tree already in withfile.
958 	 */
959 	assert(fifo_len(wq.wq_queue) == 1);
960 	mstrtd = fifo_remove(wq.wq_queue);
961 
962 	if (verbose || debug_level) {
963 		debug(2, "Statistics for td %p\n", (void *)mstrtd);
964 
965 		iidesc_stats(mstrtd->td_iihash);
966 	}
967 
968 	if (uniqfile != NULL || withfile != NULL) {
969 		char *reffile, *reflabel = NULL;
970 		tdata_t *reftd;
971 
972 		if (uniqfile != NULL) {
973 			reffile = uniqfile;
974 			reflabel = uniqlabel;
975 		} else
976 			reffile = withfile;
977 
978 		if (read_ctf(&reffile, 1, reflabel, read_ctf_save_cb,
979 		    &reftd, require_ctf) == 0) {
980 			terminate("No CTF data found in reference file %s\n",
981 			    reffile);
982 		}
983 
984 		savetd = tdata_new();
985 
986 		if (CTF_TYPE_ISCHILD(reftd->td_nextid))
987 			terminate("No room for additional types in master\n");
988 
989 		savetd->td_nextid = withfile ? reftd->td_nextid :
990 		    CTF_INDEX_TO_TYPE(1, TRUE);
991 		merge_into_master(mstrtd, reftd, savetd, 0);
992 
993 		tdata_label_add(savetd, label, CTF_LABEL_LASTIDX);
994 
995 		if (withfile) {
996 			/*
997 			 * savetd holds the new data to be added to the withfile
998 			 */
999 			tdata_t *withtd = reftd;
1000 
1001 			tdata_merge(withtd, savetd);
1002 
1003 			savetd = withtd;
1004 		} else {
1005 			char uniqname[MAXPATHLEN];
1006 			labelent_t *parle;
1007 
1008 			parle = tdata_label_top(reftd);
1009 
1010 			savetd->td_parlabel = xstrdup(parle->le_name);
1011 
1012 			strncpy(uniqname, reffile, sizeof (uniqname));
1013 			uniqname[MAXPATHLEN - 1] = '\0';
1014 			savetd->td_parname = xstrdup(basename(uniqname));
1015 		}
1016 
1017 	} else {
1018 		/*
1019 		 * No post processing.  Write the merged tree as-is into the
1020 		 * output file.
1021 		 */
1022 		tdata_label_free(mstrtd);
1023 		tdata_label_add(mstrtd, label, CTF_LABEL_LASTIDX);
1024 
1025 		savetd = mstrtd;
1026 	}
1027 
1028 	tmpname = mktmpname(outfile, ".ctf");
1029 	write_ctf(savetd, outfile, tmpname,
1030 	    CTF_COMPRESS | CTF_SWAP_BYTES | write_fuzzy_match | dynsym | keep_stabs);
1031 	if (rename(tmpname, outfile) != 0)
1032 		terminate("Couldn't rename output temp file %s", tmpname);
1033 	free(tmpname);
1034 
1035 	return (0);
1036 }
1037