Path: blob/main/cddl/contrib/opensolaris/tools/ctf/cvt/ctfmerge.c
39586 views
/*1* CDDL HEADER START2*3* The contents of this file are subject to the terms of the4* Common Development and Distribution License (the "License").5* You may not use this file except in compliance with the License.6*7* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE8* or http://www.opensolaris.org/os/licensing.9* See the License for the specific language governing permissions10* and limitations under the License.11*12* When distributing Covered Code, include this CDDL HEADER in each13* file and include the License file at usr/src/OPENSOLARIS.LICENSE.14* If applicable, add the following below this CDDL HEADER, with the15* fields enclosed by brackets "[]" replaced with your own identifying16* information: Portions Copyright [yyyy] [name of copyright owner]17*18* CDDL HEADER END19*/20/*21* Copyright 2008 Sun Microsystems, Inc. All rights reserved.22* Use is subject to license terms.23*/2425#pragma ident "%Z%%M% %I% %E% SMI"2627/*28* Given several files containing CTF data, merge and uniquify that data into29* a single CTF section in an output file.30*31* Merges can proceed independently. As such, we perform the merges in parallel32* using a worker thread model. A given glob of CTF data (either all of the CTF33* data from a single input file, or the result of one or more merges) can only34* be involved in a single merge at any given time, so the process decreases in35* parallelism, especially towards the end, as more and more files are36* consolidated, finally resulting in a single merge of two large CTF graphs.37* Unfortunately, the last merge is also the slowest, as the two graphs being38* merged are each the product of merges of half of the input files.39*40* The algorithm consists of two phases, described in detail below. The first41* phase entails the merging of CTF data in groups of eight. The second phase42* takes the results of Phase I, and merges them two at a time. This disparity43* is due to an observation that the merge time increases at least quadratically44* with the size of the CTF data being merged. As such, merges of CTF graphs45* newly read from input files are much faster than merges of CTF graphs that46* are themselves the results of prior merges.47*48* A further complication is the need to ensure the repeatability of CTF merges.49* That is, a merge should produce the same output every time, given the same50* input. In both phases, this consistency requirement is met by imposing an51* ordering on the merge process, thus ensuring that a given set of input files52* are merged in the same order every time.53*54* Phase I55*56* The main thread reads the input files one by one, transforming the CTF57* data they contain into tdata structures. When a given file has been read58* and parsed, it is placed on the work queue for retrieval by worker threads.59*60* Central to Phase I is the Work In Progress (wip) array, which is used to61* merge batches of files in a predictable order. Files are read by the main62* thread, and are merged into wip array elements in round-robin order. When63* the number of files merged into a given array slot equals the batch size,64* the merged CTF graph in that array is added to the done slot in order by65* array slot.66*67* For example, consider a case where we have five input files, a batch size68* of two, a wip array size of two, and two worker threads (T1 and T2).69*70* 1. The wip array elements are assigned initial batch numbers 0 and 1.71* 2. T1 reads an input file from the input queue (wq_queue). This is the72* first input file, so it is placed into wip[0]. The second file is73* similarly read and placed into wip[1]. The wip array slots now contain74* one file each (wip_nmerged == 1).75* 3. T1 reads the third input file, which it merges into wip[0]. The76* number of files in wip[0] is equal to the batch size.77* 4. T2 reads the fourth input file, which it merges into wip[1]. wip[1]78* is now full too.79* 5. T2 attempts to place the contents of wip[1] on the done queue80* (wq_done_queue), but it can't, since the batch ID for wip[1] is 1.81* Batch 0 needs to be on the done queue before batch 1 can be added, so82* T2 blocks on wip[1]'s cv.83* 6. T1 attempts to place the contents of wip[0] on the done queue, and84* succeeds, updating wq_lastdonebatch to 0. It clears wip[0], and sets85* its batch ID to 2. T1 then signals wip[1]'s cv to awaken T2.86* 7. T2 wakes up, notices that wq_lastdonebatch is 0, which means that87* batch 1 can now be added. It adds wip[1] to the done queue, clears88* wip[1], and sets its batch ID to 3. It signals wip[0]'s cv, and89* restarts.90*91* The above process continues until all input files have been consumed. At92* this point, a pair of barriers are used to allow a single thread to move93* any partial batches from the wip array to the done array in batch ID order.94* When this is complete, wq_done_queue is moved to wq_queue, and Phase II95* begins.96*97* Locking Semantics (Phase I)98*99* The input queue (wq_queue) and the done queue (wq_done_queue) are100* protected by separate mutexes - wq_queue_lock and wq_done_queue. wip101* array slots are protected by their own mutexes, which must be grabbed102* before releasing the input queue lock. The wip array lock is dropped103* when the thread restarts the loop. If the array slot was full, the104* array lock will be held while the slot contents are added to the done105* queue. The done queue lock is used to protect the wip slot cv's.106*107* The pow number is protected by the queue lock. The master batch ID108* and last completed batch (wq_lastdonebatch) counters are protected *in109* Phase I* by the done queue lock.110*111* Phase II112*113* When Phase II begins, the queue consists of the merged batches from the114* first phase. Assume we have five batches:115*116* Q: a b c d e117*118* Using the same batch ID mechanism we used in Phase I, but without the wip119* array, worker threads remove two entries at a time from the beginning of120* the queue. These two entries are merged, and are added back to the tail121* of the queue, as follows:122*123* Q: a b c d e # start124* Q: c d e ab # a, b removed, merged, added to end125* Q: e ab cd # c, d removed, merged, added to end126* Q: cd eab # e, ab removed, merged, added to end127* Q: cdeab # cd, eab removed, merged, added to end128*129* When one entry remains on the queue, with no merges outstanding, Phase II130* finishes. We pre-determine the stopping point by pre-calculating the131* number of nodes that will appear on the list. In the example above, the132* number (wq_ninqueue) is 9. When ninqueue is 1, we conclude Phase II by133* signaling the main thread via wq_done_cv.134*135* Locking Semantics (Phase II)136*137* The queue (wq_queue), ninqueue, and the master batch ID and last138* completed batch counters are protected by wq_queue_lock. The done139* queue and corresponding lock are unused in Phase II as is the wip array.140*141* Uniquification142*143* We want the CTF data that goes into a given module to be as small as144* possible. For example, we don't want it to contain any type data that may145* be present in another common module. As such, after creating the master146* tdata_t for a given module, we can, if requested by the user, uniquify it147* against the tdata_t from another module (genunix in the case of the SunOS148* kernel). We perform a merge between the tdata_t for this module and the149* tdata_t from genunix. Nodes found in this module that are not present in150* genunix are added to a third tdata_t - the uniquified tdata_t.151*152* Additive Merges153*154* In some cases, for example if we are issuing a new version of a common155* module in a patch, we need to make sure that the CTF data already present156* in that module does not change. Changes to this data would void the CTF157* data in any module that uniquified against the common module. To preserve158* the existing data, we can perform what is known as an additive merge. In159* this case, a final uniquification is performed against the CTF data in the160* previous version of the module. The result will be the placement of new161* and changed data after the existing data, thus preserving the existing type162* ID space.163*164* Saving the result165*166* When the merges are complete, the resulting tdata_t is placed into the167* output file, replacing the .SUNW_ctf section (if any) already in that file.168*169* The person who changes the merging thread code in this file without updating170* this comment will not live to see the stock hit five.171*/172173#include <stdio.h>174#include <stdlib.h>175#include <unistd.h>176#include <pthread.h>177#include <assert.h>178#ifdef illumos179#include <synch.h>180#endif181#include <signal.h>182#include <libgen.h>183#include <string.h>184#include <errno.h>185#ifdef illumos186#include <alloca.h>187#endif188#include <sys/param.h>189#include <sys/types.h>190#include <sys/mman.h>191#ifdef illumos192#include <sys/sysconf.h>193#endif194195#include "ctf_headers.h"196#include "ctftools.h"197#include "ctfmerge.h"198#include "traverse.h"199#include "memory.h"200#include "fifo.h"201#include "barrier.h"202203#pragma init(bigheap)204205#define MERGE_PHASE1_BATCH_SIZE 8206#define MERGE_PHASE1_MAX_SLOTS 5207#define MERGE_INPUT_THROTTLE_LEN 10208209const char *progname;210static char *outfile = NULL;211static char *tmpname = NULL;212static int dynsym;213int debug_level = DEBUG_LEVEL;214static size_t maxpgsize = 0x400000;215216217void218usage(void)219{220(void) fprintf(stderr,221"Usage: %s [-fgstv] -l label | -L labelenv -o outfile file ...\n"222" %s [-fgstv] -l label | -L labelenv -o outfile -d uniqfile\n"223" %*s [-g] [-D uniqlabel] file ...\n"224" %s [-fgstv] -l label | -L labelenv -o outfile -w withfile "225"file ...\n"226" %s [-g] -c srcfile destfile\n"227"\n"228" Note: if -L labelenv is specified and labelenv is not set in\n"229" the environment, a default value is used.\n",230progname, progname, (int)strlen(progname), " ",231progname, progname);232}233234#ifdef illumos235static void236bigheap(void)237{238size_t big, *size;239int sizes;240struct memcntl_mha mha;241242/*243* First, get the available pagesizes.244*/245if ((sizes = getpagesizes(NULL, 0)) == -1)246return;247248if (sizes == 1 || (size = alloca(sizeof (size_t) * sizes)) == NULL)249return;250251if (getpagesizes(size, sizes) == -1)252return;253254while (size[sizes - 1] > maxpgsize)255sizes--;256257/* set big to the largest allowed page size */258big = size[sizes - 1];259if (big & (big - 1)) {260/*261* The largest page size is not a power of two for some262* inexplicable reason; return.263*/264return;265}266267/*268* Now, align our break to the largest page size.269*/270if (brk((void *)((((uintptr_t)sbrk(0) - 1) & ~(big - 1)) + big)) != 0)271return;272273/*274* set the preferred page size for the heap275*/276mha.mha_cmd = MHA_MAPSIZE_BSSBRK;277mha.mha_flags = 0;278mha.mha_pagesize = big;279280(void) memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mha, 0, 0);281}282#endif /* illumos */283284static void285finalize_phase_one(workqueue_t *wq)286{287int startslot, i;288289/*290* wip slots are cleared out only when maxbatchsz td's have been merged291* into them. We're not guaranteed that the number of files we're292* merging is a multiple of maxbatchsz, so there will be some partial293* groups in the wip array. Move them to the done queue in batch ID294* order, starting with the slot containing the next batch that would295* have been placed on the done queue, followed by the others.296* One thread will be doing this while the others wait at the barrier297* back in worker_thread(), so we don't need to worry about pesky things298* like locks.299*/300301for (startslot = -1, i = 0; i < wq->wq_nwipslots; i++) {302if (wq->wq_wip[i].wip_batchid == wq->wq_lastdonebatch + 1) {303startslot = i;304break;305}306}307308assert(startslot != -1);309310for (i = startslot; i < startslot + wq->wq_nwipslots; i++) {311int slotnum = i % wq->wq_nwipslots;312wip_t *wipslot = &wq->wq_wip[slotnum];313314if (wipslot->wip_td != NULL) {315debug(2, "clearing slot %d (%d) (saving %d)\n",316slotnum, i, wipslot->wip_nmerged);317} else318debug(2, "clearing slot %d (%d)\n", slotnum, i);319320if (wipslot->wip_td != NULL) {321fifo_add(wq->wq_donequeue, wipslot->wip_td);322wq->wq_wip[slotnum].wip_td = NULL;323}324}325326wq->wq_lastdonebatch = wq->wq_next_batchid++;327328debug(2, "phase one done: donequeue has %d items\n",329fifo_len(wq->wq_donequeue));330}331332static void333init_phase_two(workqueue_t *wq)334{335int num;336337/*338* We're going to continually merge the first two entries on the queue,339* placing the result on the end, until there's nothing left to merge.340* At that point, everything will have been merged into one. The341* initial value of ninqueue needs to be equal to the total number of342* entries that will show up on the queue, both at the start of the343* phase and as generated by merges during the phase.344*/345wq->wq_ninqueue = num = fifo_len(wq->wq_donequeue);346while (num != 1) {347wq->wq_ninqueue += num / 2;348num = num / 2 + num % 2;349}350351/*352* Move the done queue to the work queue. We won't be using the done353* queue in phase 2.354*/355assert(fifo_len(wq->wq_queue) == 0);356fifo_free(wq->wq_queue, NULL);357wq->wq_queue = wq->wq_donequeue;358}359360static void361wip_save_work(workqueue_t *wq, wip_t *slot, int slotnum)362{363pthread_mutex_lock(&wq->wq_donequeue_lock);364365while (wq->wq_lastdonebatch + 1 < slot->wip_batchid)366pthread_cond_wait(&slot->wip_cv, &wq->wq_donequeue_lock);367assert(wq->wq_lastdonebatch + 1 == slot->wip_batchid);368369fifo_add(wq->wq_donequeue, slot->wip_td);370wq->wq_lastdonebatch++;371pthread_cond_signal(&wq->wq_wip[(slotnum + 1) %372wq->wq_nwipslots].wip_cv);373374/* reset the slot for next use */375slot->wip_td = NULL;376slot->wip_batchid = wq->wq_next_batchid++;377378pthread_mutex_unlock(&wq->wq_donequeue_lock);379}380381static void382wip_add_work(wip_t *slot, tdata_t *pow)383{384if (slot->wip_td == NULL) {385slot->wip_td = pow;386slot->wip_nmerged = 1;387} else {388debug(2, "%d: merging %p into %p\n", pthread_self(),389(void *)pow, (void *)slot->wip_td);390391merge_into_master(pow, slot->wip_td, NULL, 0);392tdata_free(pow);393394slot->wip_nmerged++;395}396}397398static void399worker_runphase1(workqueue_t *wq)400{401wip_t *wipslot;402tdata_t *pow;403int wipslotnum, pownum;404405for (;;) {406pthread_mutex_lock(&wq->wq_queue_lock);407408while (fifo_empty(wq->wq_queue)) {409if (wq->wq_nomorefiles == 1) {410pthread_cond_broadcast(&wq->wq_work_avail);411pthread_mutex_unlock(&wq->wq_queue_lock);412413/* on to phase 2 ... */414return;415}416417pthread_cond_wait(&wq->wq_work_avail,418&wq->wq_queue_lock);419}420421/* there's work to be done! */422pow = fifo_remove(wq->wq_queue);423pownum = wq->wq_nextpownum++;424pthread_cond_broadcast(&wq->wq_work_removed);425426assert(pow != NULL);427428/* merge it into the right slot */429wipslotnum = pownum % wq->wq_nwipslots;430wipslot = &wq->wq_wip[wipslotnum];431432pthread_mutex_lock(&wipslot->wip_lock);433434pthread_mutex_unlock(&wq->wq_queue_lock);435436wip_add_work(wipslot, pow);437438if (wipslot->wip_nmerged == wq->wq_maxbatchsz)439wip_save_work(wq, wipslot, wipslotnum);440441pthread_mutex_unlock(&wipslot->wip_lock);442}443}444445static void446worker_runphase2(workqueue_t *wq)447{448tdata_t *pow1, *pow2;449int batchid;450451for (;;) {452pthread_mutex_lock(&wq->wq_queue_lock);453454if (wq->wq_ninqueue == 1) {455pthread_cond_broadcast(&wq->wq_work_avail);456pthread_mutex_unlock(&wq->wq_queue_lock);457458debug(2, "%d: entering p2 completion barrier\n",459pthread_self());460if (barrier_wait(&wq->wq_bar1)) {461pthread_mutex_lock(&wq->wq_queue_lock);462wq->wq_alldone = 1;463pthread_cond_signal(&wq->wq_alldone_cv);464pthread_mutex_unlock(&wq->wq_queue_lock);465}466467return;468}469470if (fifo_len(wq->wq_queue) < 2) {471pthread_cond_wait(&wq->wq_work_avail,472&wq->wq_queue_lock);473pthread_mutex_unlock(&wq->wq_queue_lock);474continue;475}476477/* there's work to be done! */478pow1 = fifo_remove(wq->wq_queue);479pow2 = fifo_remove(wq->wq_queue);480wq->wq_ninqueue -= 2;481482batchid = wq->wq_next_batchid++;483484pthread_mutex_unlock(&wq->wq_queue_lock);485486debug(2, "%d: merging %p into %p\n", pthread_self(),487(void *)pow1, (void *)pow2);488merge_into_master(pow1, pow2, NULL, 0);489tdata_free(pow1);490491/*492* merging is complete. place at the tail of the queue in493* proper order.494*/495pthread_mutex_lock(&wq->wq_queue_lock);496while (wq->wq_lastdonebatch + 1 != batchid) {497pthread_cond_wait(&wq->wq_done_cv,498&wq->wq_queue_lock);499}500501wq->wq_lastdonebatch = batchid;502503fifo_add(wq->wq_queue, pow2);504debug(2, "%d: added %p to queue, len now %d, ninqueue %d\n",505pthread_self(), (void *)pow2, fifo_len(wq->wq_queue),506wq->wq_ninqueue);507pthread_cond_broadcast(&wq->wq_done_cv);508pthread_cond_signal(&wq->wq_work_avail);509pthread_mutex_unlock(&wq->wq_queue_lock);510}511}512513/*514* Main loop for worker threads.515*/516static void517worker_thread(workqueue_t *wq)518{519worker_runphase1(wq);520521debug(2, "%d: entering first barrier\n", pthread_self());522523if (barrier_wait(&wq->wq_bar1)) {524525debug(2, "%d: doing work in first barrier\n", pthread_self());526527finalize_phase_one(wq);528529init_phase_two(wq);530531debug(2, "%d: ninqueue is %d, %d on queue\n", pthread_self(),532wq->wq_ninqueue, fifo_len(wq->wq_queue));533}534535debug(2, "%d: entering second barrier\n", pthread_self());536537(void) barrier_wait(&wq->wq_bar2);538539debug(2, "%d: phase 1 complete\n", pthread_self());540541worker_runphase2(wq);542}543544/*545* Pass a tdata_t tree, built from an input file, off to the work queue for546* consumption by worker threads.547*/548static int549merge_ctf_cb(tdata_t *td, char *name, void *arg)550{551workqueue_t *wq = arg;552553debug(3, "Adding tdata %p for processing\n", (void *)td);554555pthread_mutex_lock(&wq->wq_queue_lock);556while (fifo_len(wq->wq_queue) > wq->wq_ithrottle) {557debug(2, "Throttling input (len = %d, throttle = %d)\n",558fifo_len(wq->wq_queue), wq->wq_ithrottle);559pthread_cond_wait(&wq->wq_work_removed, &wq->wq_queue_lock);560}561562fifo_add(wq->wq_queue, td);563debug(1, "Thread %d announcing %s\n", pthread_self(), name);564pthread_cond_broadcast(&wq->wq_work_avail);565pthread_mutex_unlock(&wq->wq_queue_lock);566567return (1);568}569570/*571* This program is intended to be invoked from a Makefile, as part of the build.572* As such, in the event of a failure or user-initiated interrupt (^C), we need573* to ensure that a subsequent re-make will cause ctfmerge to be executed again.574* Unfortunately, ctfmerge will usually be invoked directly after (and as part575* of the same Makefile rule as) a link, and will operate on the linked file576* in place. If we merely exit upon receipt of a SIGINT, a subsequent make577* will notice that the *linked* file is newer than the object files, and thus578* will not reinvoke ctfmerge. The only way to ensure that a subsequent make579* reinvokes ctfmerge, is to remove the file to which we are adding CTF580* data (confusingly named the output file). This means that the link will need581* to happen again, but links are generally fast, and we can't allow the merge582* to be skipped.583*584* Another possibility would be to block SIGINT entirely - to always run to585* completion. The run time of ctfmerge can, however, be measured in minutes586* in some cases, so this is not a valid option.587*/588static void589handle_sig(int sig)590{591terminate("Caught signal %d - exiting\n", sig);592}593594static void595terminate_cleanup(void)596{597int dounlink = getenv("CTFMERGE_TERMINATE_NO_UNLINK") ? 0 : 1;598599if (tmpname != NULL && dounlink)600unlink(tmpname);601602if (outfile == NULL)603return;604605#if !defined(__FreeBSD__)606if (dounlink) {607fprintf(stderr, "Removing %s\n", outfile);608unlink(outfile);609}610#endif611}612613static void614copy_ctf_data(char *srcfile, char *destfile, int keep_stabs)615{616tdata_t *srctd;617618if (read_ctf(&srcfile, 1, NULL, read_ctf_save_cb, &srctd, 1) == 0)619terminate("No CTF data found in source file %s\n", srcfile);620621tmpname = mktmpname(destfile, ".ctf");622write_ctf(srctd, destfile, tmpname, CTF_COMPRESS | CTF_SWAP_BYTES | keep_stabs);623if (rename(tmpname, destfile) != 0) {624terminate("Couldn't rename temp file %s to %s", tmpname,625destfile);626}627free(tmpname);628tdata_free(srctd);629}630631static void632wq_init(workqueue_t *wq, int nfiles)633{634int throttle, nslots, i;635636if (getenv("CTFMERGE_MAX_SLOTS"))637nslots = atoi(getenv("CTFMERGE_MAX_SLOTS"));638else639nslots = MERGE_PHASE1_MAX_SLOTS;640641if (getenv("CTFMERGE_PHASE1_BATCH_SIZE"))642wq->wq_maxbatchsz = atoi(getenv("CTFMERGE_PHASE1_BATCH_SIZE"));643else644wq->wq_maxbatchsz = MERGE_PHASE1_BATCH_SIZE;645646nslots = MIN(nslots, (nfiles + wq->wq_maxbatchsz - 1) /647wq->wq_maxbatchsz);648649wq->wq_wip = xcalloc(sizeof (wip_t) * nslots);650wq->wq_nwipslots = nslots;651wq->wq_nthreads = MIN(sysconf(_SC_NPROCESSORS_ONLN) * 3 / 2, nslots);652wq->wq_thread = xmalloc(sizeof (pthread_t) * wq->wq_nthreads);653654if (getenv("CTFMERGE_INPUT_THROTTLE"))655throttle = atoi(getenv("CTFMERGE_INPUT_THROTTLE"));656else657throttle = MERGE_INPUT_THROTTLE_LEN;658wq->wq_ithrottle = throttle * wq->wq_nthreads;659660debug(1, "Using %d slots, %d threads\n", wq->wq_nwipslots,661wq->wq_nthreads);662663wq->wq_next_batchid = 0;664665for (i = 0; i < nslots; i++) {666pthread_mutex_init(&wq->wq_wip[i].wip_lock, NULL);667pthread_cond_init(&wq->wq_wip[i].wip_cv, NULL);668wq->wq_wip[i].wip_batchid = wq->wq_next_batchid++;669}670671pthread_mutex_init(&wq->wq_queue_lock, NULL);672wq->wq_queue = fifo_new();673pthread_cond_init(&wq->wq_work_avail, NULL);674pthread_cond_init(&wq->wq_work_removed, NULL);675wq->wq_ninqueue = nfiles;676wq->wq_nextpownum = 0;677678pthread_mutex_init(&wq->wq_donequeue_lock, NULL);679wq->wq_donequeue = fifo_new();680wq->wq_lastdonebatch = -1;681682pthread_cond_init(&wq->wq_done_cv, NULL);683684pthread_cond_init(&wq->wq_alldone_cv, NULL);685wq->wq_alldone = 0;686687barrier_init(&wq->wq_bar1, wq->wq_nthreads);688barrier_init(&wq->wq_bar2, wq->wq_nthreads);689690wq->wq_nomorefiles = 0;691}692693static void694start_threads(workqueue_t *wq)695{696sigset_t sets;697int i;698699sigemptyset(&sets);700sigaddset(&sets, SIGINT);701sigaddset(&sets, SIGQUIT);702sigaddset(&sets, SIGTERM);703pthread_sigmask(SIG_BLOCK, &sets, NULL);704705for (i = 0; i < wq->wq_nthreads; i++) {706pthread_create(&wq->wq_thread[i], NULL,707(void *(*)(void *))worker_thread, wq);708}709710#ifdef illumos711sigset(SIGINT, handle_sig);712sigset(SIGQUIT, handle_sig);713sigset(SIGTERM, handle_sig);714#else715signal(SIGINT, handle_sig);716signal(SIGQUIT, handle_sig);717signal(SIGTERM, handle_sig);718#endif719pthread_sigmask(SIG_UNBLOCK, &sets, NULL);720}721722static void723join_threads(workqueue_t *wq)724{725int i;726727for (i = 0; i < wq->wq_nthreads; i++) {728pthread_join(wq->wq_thread[i], NULL);729}730}731732static int733strcompare(const void *p1, const void *p2)734{735char *s1 = *((char **)p1);736char *s2 = *((char **)p2);737738return (strcmp(s1, s2));739}740741/*742* Core work queue structure; passed to worker threads on thread creation743* as the main point of coordination. Allocate as a static structure; we744* could have put this into a local variable in main, but passing a pointer745* into your stack to another thread is fragile at best and leads to some746* hard-to-debug failure modes.747*/748static workqueue_t wq;749750int751main(int argc, char **argv)752{753tdata_t *mstrtd, *savetd;754char *uniqfile = NULL, *uniqlabel = NULL;755char *withfile = NULL;756char *label = NULL;757char **ifiles, **tifiles;758int verbose = 0, docopy = 0;759int write_fuzzy_match = 0;760int keep_stabs = 0;761int require_ctf = 0;762int nifiles, nielems;763int c, i, idx, tidx, err;764765progname = basename(argv[0]);766767if (getenv("CTFMERGE_DEBUG_LEVEL"))768debug_level = atoi(getenv("CTFMERGE_DEBUG_LEVEL"));769770err = 0;771while ((c = getopt(argc, argv, ":cd:D:fgl:L:o:tvw:s")) != EOF) {772switch (c) {773case 'c':774docopy = 1;775break;776case 'd':777/* Uniquify against `uniqfile' */778uniqfile = optarg;779break;780case 'D':781/* Uniquify against label `uniqlabel' in `uniqfile' */782uniqlabel = optarg;783break;784case 'f':785write_fuzzy_match = CTF_FUZZY_MATCH;786break;787case 'g':788keep_stabs = CTF_KEEP_STABS;789break;790case 'l':791/* Label merged types with `label' */792label = optarg;793break;794case 'L':795/* Label merged types with getenv(`label`) */796if ((label = getenv(optarg)) == NULL)797label = CTF_DEFAULT_LABEL;798break;799case 'o':800/* Place merged types in CTF section in `outfile' */801outfile = optarg;802break;803case 't':804/* Insist *all* object files built from C have CTF */805require_ctf = 1;806break;807case 'v':808/* More debugging information */809verbose = 1;810break;811case 'w':812/* Additive merge with data from `withfile' */813withfile = optarg;814break;815case 's':816/* use the dynsym rather than the symtab */817dynsym = CTF_USE_DYNSYM;818break;819default:820usage();821exit(2);822}823}824825/* Validate arguments */826if (docopy) {827if (uniqfile != NULL || uniqlabel != NULL || label != NULL ||828outfile != NULL || withfile != NULL || dynsym != 0)829err++;830831if (argc - optind != 2)832err++;833} else {834if (uniqfile != NULL && withfile != NULL)835err++;836837if (uniqlabel != NULL && uniqfile == NULL)838err++;839840if (outfile == NULL || label == NULL)841err++;842843if (argc - optind == 0)844err++;845}846847if (err) {848usage();849exit(2);850}851852if (getenv("STRIPSTABS_KEEP_STABS") != NULL)853keep_stabs = CTF_KEEP_STABS;854855if (uniqfile && access(uniqfile, R_OK) != 0) {856warning("Uniquification file %s couldn't be opened and "857"will be ignored.\n", uniqfile);858uniqfile = NULL;859}860if (withfile && access(withfile, R_OK) != 0) {861warning("With file %s couldn't be opened and will be "862"ignored.\n", withfile);863withfile = NULL;864}865if (outfile && access(outfile, R_OK|W_OK) != 0)866terminate("Cannot open output file %s for r/w", outfile);867868/*869* This is ugly, but we don't want to have to have a separate tool870* (yet) just for copying an ELF section with our specific requirements,871* so we shoe-horn a copier into ctfmerge.872*/873if (docopy) {874copy_ctf_data(argv[optind], argv[optind + 1], keep_stabs);875876exit(0);877}878879set_terminate_cleanup(terminate_cleanup);880881/* Sort the input files and strip out duplicates */882nifiles = argc - optind;883ifiles = xmalloc(sizeof (char *) * nifiles);884tifiles = xmalloc(sizeof (char *) * nifiles);885886for (i = 0; i < nifiles; i++)887tifiles[i] = argv[optind + i];888qsort(tifiles, nifiles, sizeof (char *), strcompare);889890ifiles[0] = tifiles[0];891for (idx = 0, tidx = 1; tidx < nifiles; tidx++) {892if (strcmp(ifiles[idx], tifiles[tidx]) != 0)893ifiles[++idx] = tifiles[tidx];894}895nifiles = idx + 1;896897/* Make sure they all exist */898if ((nielems = count_files(ifiles, nifiles)) < 0)899terminate("Some input files were inaccessible\n");900901/* Prepare for the merge */902wq_init(&wq, nielems);903904start_threads(&wq);905906/*907* Start the merge908*909* We're reading everything from each of the object files, so we910* don't need to specify labels.911*/912if (read_ctf(ifiles, nifiles, NULL, merge_ctf_cb,913&wq, require_ctf) == 0) {914warning("No ctf sections found to merge\n");915exit(0);916}917918pthread_mutex_lock(&wq.wq_queue_lock);919wq.wq_nomorefiles = 1;920pthread_cond_broadcast(&wq.wq_work_avail);921pthread_mutex_unlock(&wq.wq_queue_lock);922923pthread_mutex_lock(&wq.wq_queue_lock);924while (wq.wq_alldone == 0)925pthread_cond_wait(&wq.wq_alldone_cv, &wq.wq_queue_lock);926pthread_mutex_unlock(&wq.wq_queue_lock);927928join_threads(&wq);929930/*931* All requested files have been merged, with the resulting tree in932* mstrtd. savetd is the tree that will be placed into the output file.933*934* Regardless of whether we're doing a normal uniquification or an935* additive merge, we need a type tree that has been uniquified936* against uniqfile or withfile, as appropriate.937*938* If we're doing a uniquification, we stuff the resulting tree into939* outfile. Otherwise, we add the tree to the tree already in withfile.940*/941assert(fifo_len(wq.wq_queue) == 1);942mstrtd = fifo_remove(wq.wq_queue);943944if (verbose || debug_level) {945debug(2, "Statistics for td %p\n", (void *)mstrtd);946947iidesc_stats(mstrtd->td_iihash);948}949950if (uniqfile != NULL || withfile != NULL) {951char *reffile, *reflabel = NULL;952tdata_t *reftd;953954if (uniqfile != NULL) {955reffile = uniqfile;956reflabel = uniqlabel;957} else958reffile = withfile;959960if (read_ctf(&reffile, 1, reflabel, read_ctf_save_cb,961&reftd, require_ctf) == 0) {962terminate("No CTF data found in reference file %s\n",963reffile);964}965966savetd = tdata_new();967968if (CTF_V3_TYPE_ISCHILD(reftd->td_nextid))969terminate("No room for additional types in master\n");970971savetd->td_nextid = withfile ? reftd->td_nextid :972CTF_V3_INDEX_TO_TYPE(1, TRUE);973merge_into_master(mstrtd, reftd, savetd, 0);974975tdata_label_add(savetd, label, CTF_LABEL_LASTIDX);976977if (withfile) {978/*979* savetd holds the new data to be added to the withfile980*/981tdata_t *withtd = reftd;982983tdata_merge(withtd, savetd);984985savetd = withtd;986} else {987char uniqname[MAXPATHLEN];988labelent_t *parle;989990parle = tdata_label_top(reftd);991992savetd->td_parlabel = xstrdup(parle->le_name);993994strncpy(uniqname, reffile, sizeof (uniqname));995uniqname[MAXPATHLEN - 1] = '\0';996savetd->td_parname = xstrdup(basename(uniqname));997}998999} else {1000/*1001* No post processing. Write the merged tree as-is into the1002* output file.1003*/1004tdata_label_free(mstrtd);1005tdata_label_add(mstrtd, label, CTF_LABEL_LASTIDX);10061007savetd = mstrtd;1008}10091010tmpname = mktmpname(outfile, ".ctf");1011write_ctf(savetd, outfile, tmpname,1012CTF_COMPRESS | CTF_SWAP_BYTES | write_fuzzy_match | dynsym | keep_stabs);1013if (rename(tmpname, outfile) != 0)1014terminate("Couldn't rename output temp file %s", tmpname);1015free(tmpname);10161017return (0);1018}101910201021