3 * Duplicate multiple files
5 * (c) 2008 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the mLib utilities library.
12 * mLib is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * mLib is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with mLib; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- Header files ------------------------------------------------------*/
37 /*----- Data structures ---------------------------------------------------*/
39 typedef struct mdup_fdinfo {
42 /* Each @fdinfo@ structure refers to one of the caller's @fd@ structures.
46 struct mdup_fdinfo *eqnext, *eqprev;
47 /* The caller's request list can contain more than one entry with any given
48 * @cur@ descriptor. We group them together into an equivalence class,
49 * which is doubly linked using these fields.
52 struct mdup_fdinfo *up;
53 /* We require that there be at most one node with any given @want@
54 * descriptor (other than @-1@). There is therefore at most one node whose
55 * @want@ is equal to my @cur@. If such a node exists, @up@ points to it;
56 * otherwise @up@ is null.
59 struct mdup_fdinfo *down;
60 /* Obviously, @down@ links in the opposite direction from @up@. However,
61 * there may be several nodes whose @cur@ equals my @want@; therefore
62 * @down@ simply links to one of the nodes in the equivalence class.
64 * Unsurprisingly, @down@ is the direction we move during the depth-first
65 * traversal phase of the operation.
68 struct mdup_fdinfo *dlink;
69 /* Nodes with @want == -1@, and nodes where we've broken cycles, are
70 * considered `dynamic': their @cur@ has been chosen by @dup@ to be
71 * distinct from any existing descriptor, but may collide with a @want@.
72 * We check each proposed move against the list of dynamic nodes, and move
73 * them out of the way as necessary. Note that this is really a list of
74 * equivalence classes rather than single nodes.
78 /* The current state of this node. One of the @ST@ constants described
85 /* Node has not yet been processed.
89 /* Node has been reached by the depth-first traversal, but its descriptor
90 * has not yet been moved. This state is used to detect cycles using the
91 * depth-first traversal.
95 /* Node has been processed completely. We have @want == -1@ or
100 /* Node has been clobbered in order to break a cycle. The node's
101 * equivalence class has been remapped to a fresh descriptor which (we
102 * hope) is not equal to any node's @want@. All broken nodes are put on
103 * the dynamic list: if our hope turns out to be misplaced we can remap the
108 /*----- Main code ---------------------------------------------------------*/
110 /* --- @DO_EQUIVS@ --- *
112 * Perform @body@ once for each @g@ in the equivalence class of @f@.
115 #define DO_EQUIVS(g, f, body) do { \
116 mdup_fdinfo *f_ = (f), *g_ = f_; \
117 do { mdup_fdinfo *g = g_; g_ = g_->eqnext; body; } while (g_ != f_); \
122 * Arguments: @mdup_fdinfo *v@ = pointer to info vector
123 * @size_t n@ = size of vector
127 * Use: Dumps a scary-looking description of the state of @mdup@'s
140 static PRINTF_LIKE(4, 5) IGNORABLE
141 void dump(mdup_fdinfo *v, size_t n, mdup_fdinfo *dhead,
142 const char *fmt, ...)
146 static const char *state[] = { "READY", "MARK", "DONE", "BROKEN" };
149 #define INDEX(p) ((p) ? (int)((p) - (v)) : -1)
151 /* --- Dump the items, fairly raw --- */
154 fputs("*** ", stdout);
157 for (i = 0; i < n; i++) {
159 printf("%3d: %-6s %3d -> %3d; "
160 "equivs: %3d, %3d; up: %3d; down: %3d; dyn: %3d\n",
161 i, state[f->state], f->f->cur, f->f->want,
162 INDEX(f->eqprev), INDEX(f->eqnext),
163 INDEX(f->up), INDEX(f->down), INDEX(f->dlink));
179 * Arguments: @mdup_fdinfo *f@ = which node to process
180 * @mdup_fdinfo **dhead, ***dtail@ = the dynamic list
182 * Returns: Zero on success, @-1@ on some OS failure.
184 * Use: Recursive depth-first traversal of the descriptor graph.
186 * On exit, the node @f@ will be in state @ST_DONE@ or
190 static int dfs(mdup_fdinfo *f, mdup_fdinfo **dhead, mdup_fdinfo ***dtail)
198 /* --- Null pointers need no processing --- *
200 * Null pointers mark the end of descending chains.
206 /* --- Otherwise our behaviour depends on the node's state --- */
210 /* --- The standard processing, in several phases --- */
214 /* --- Mark the class as being in-progress --- */
216 DO_EQUIVS(g, f, { g->state = ST_MARK; });
218 /* --- Ensure that the our proposed destination is clear --- *
220 * The depth-first traversal will leave the node in @ST_DONE@ or
221 * @ST_BROKEN@ afterwards; either way, its @cur@ will not be same as
224 * Note that this can move @%\emph{us}@ to @ST_BROKEN@. This is not a
225 * significant problem.
228 DO_EQUIVS(g, f, { if (dfs(g->down, dhead, dtail)) return (-1); });
230 /* --- Now the real work can begin --- *
232 * For each node in the class, copy the descriptor from @cur@ to
233 * @want@. Before doing this, we must move out of the way any (other)
234 * dynamic nodes whose @cur@ matches our @want@.
236 * Interestingly, this is the only point in the function where we need
237 * nontrivial error handling: if something goes wrong with one of the
238 * @dup2@ calls, we must close the descriptors made so far this pass
245 for (d = *dhead; d; d = d->dlink) {
246 if (d != f && d->f->cur == ff->want) {
247 if ((fd = dup(ff->want)) < 0)
249 DO_EQUIVS(dd, d, { dd->f->cur = fd; });
253 if (ff->cur == ff->want)
255 else if (dup2(ofd, ff->want) < 0)
260 for (g = g->eqprev; g != f->eqprev; g = g->eqprev) {
261 if (g->f->want != g->f->cur)
269 /* --- We're done --- *
271 * If the original descriptor isn't wanted by anyone we can (and must)
272 * close it. Nodes can now move to @ST_DONE@.
278 g->f->cur = g->f->want;
283 /* --- We have encoutered a cycle --- *
285 * The caller wants our descriptor. We therefore shunt this entire
286 * equivalence class to a new descriptor, and link it onto the dynamic
287 * list. Mark it as broken so that we don't try to do anything
288 * complicated to it again.
293 if ((fd = dup(ofd)) < 0)
297 g->state = ST_BROKEN;
304 /* --- Nothing to be done here --- *
306 * @ST_DONE@ nodes have already been completely processed; @ST_BROKEN@
307 * nodes will be fixed up after the main traversal.
320 * Arguments: @mdup_fd *v@ = pointer to @mdup_fd@ vector
321 * @size_t n@ = size of vector
323 * Returns: Zero if successful, @-1@ on failure.
325 * Use: Rearranges file descriptors.
327 * The vector @v@ consists of a number of @mdup_fd@ structures.
328 * Each `slot' in the table represents a file. The slot's @cur@
329 * member names the current file descriptor for this file; the
330 * @want@ member is the file descriptor we want to use for it.
331 * if you want to keep a file alive but don't care which
332 * descriptor it ends up with, set @want = -1@. Several slots
333 * may specify the same @cur@ descriptor; but they all have to
334 * declare different @want@s (except that several slots may have
337 * On successful exit, the function will have rearranged the
338 * file descriptors as requested. To reflect this, the @cur@
339 * members will all be set to match the (non-@-1@) @want@
342 * If there is a failure, then some rearrangement may have been
343 * performed and some not; the @cur@ members are set to reflect
344 * which file descriptors are to be used. The old file
345 * descriptors are closed. (This is different from usual @dup@
346 * behaviour, of course, but essential for reliable error
347 * handling.) If you want to keep a particular source file
348 * descriptor open as well as make a new copy then specify two
349 * slots with the same @cur@, one with @want = cur@ and one with
350 * the desired output descriptor.
352 * This function works correctly even if the desired remappings
356 int mdup(mdup_fd *v, size_t n)
360 mdup_fdinfo *f, *g, *dhead, **dtail;
366 /* --- Allocate and initialize the table of info nodes --- *
368 * Each entry @ff@ in the caller's @v@ array will have a corresponding node
369 * @f@ in @vv@ with @f->f = ff@. Initially each node's links are null, and
370 * the node is in the @ST_READY@ state.
372 * We also initialize a list given by @dhead@ and @dtail@ containing the
373 * entries with `dynamically-assigned' descriptors -- i.e., those whose
374 * values we made up using @dup@. The list lets us detect collisions with
375 * explicitly requested descriptors and move the dynamic ones out of the
379 if ((vv = malloc(sizeof(*vv) * n)) == 0)
384 for (i = 0; i < n; i++) {
388 f->eqnext = f->eqprev = 0;
392 /* --- Pass one: link the graph together --- *
394 * Once this pass is complete, the following properties will hold.
396 * * The nodes which have the same @cur@ are linked together by their
397 * @eqnext@ and @eqprev@ fields into a doubly-linked circular list
398 * representing this equivalence class.
400 * * @f->up == g@ if and only if @f->f->cur == g->f->want@. (Note that
401 * @want@ fields are unique according to our interface. We detect
402 * violations and exit with @errno == EINVAL@.)
404 * * If @f->up == g@ then there exists a @ff@ in the same equivalence
405 * class (and therefore on @f@'s @eqnext@ list) as @f@ with
409 for (i = 0; i < n; i++) {
412 f->eqnext = f->eqprev = f;
413 for (j = 0; j < n; j++) {
417 if (f->f->cur == g->f->cur) {
419 g->eqnext = f->eqnext;
421 f->eqnext->eqprev = g;
425 if (g->f->want == -1)
427 else if (f->f->want == g->f->want) {
430 } else if (f->f->cur == g->f->want) {
438 /* --- Pass two: handle don't-care requests --- *
440 * By the end of this pass, we have the following properties.
442 * * Every node will be marked @ST_DONE@. This is a temporary abuse of
443 * the @ST_DONE@ state which will be rectified during the next pass.
445 * * Every node with @want == -1@ will have @cur@ set to a freshly
446 * allocated file descriptor distinct from every previously open file.
449 for (i = 0; i < n; i++) {
462 if ((fd = dup(ofd)) < 0)
474 /* --- Pass three: restore equivalence classes and @down@ links --- *
476 * This pass re-establishes the properties from pass one. Because we've
477 * changed some @cur@ members, the equivalence classes will have changed,
478 * so we must fix up the @eqnext@ lists and @down@ links.
480 * Nodes with @want == -1@ are now finished with (modulo tweaking
481 * dynamically allocated descriptors as we process the others), so we leave
482 * them in @ST_DONE@; other nodes are restored to @ST_READY@.
485 for (i = 0; i < n; i++) {
488 if (ff->want == -1) {
489 f->eqnext->eqprev = f->eqprev;
490 f->eqprev->eqnext = f->eqnext;
491 f->eqnext = f->eqprev = f;
498 /* --- Pass four: main depth-first traversal --- *
500 * See the description of the function @dfs@ above. After this pass, every
501 * node is in state @ST_DONE@ or @ST_BROKEN@.
504 for (i = 0; i < n; i++) {
505 if (dfs(&vv[i], &dhead, &dtail))
509 /* --- Finished --- */
517 /*----- That's all, folks -------------------------------------------------*/