summaryrefslogtreecommitdiffstats
path: root/segment.c
blob: d83b03763cd0023458a088c48cb1a2118f4792d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2008 rPath, Inc. - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 *   Boston MA 02110-1301, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * segment.c
 *
 * Sort segments according to base address
 * Eventually add support here for merging segments
 */

#include "wraplinux.h"

#include <stdlib.h>
#include <alloca.h>
#include "segment.h"

static int comp_seg(const void *a, const void *b)
{
	const struct segment * const *ap = a;
	const struct segment * const *bp = b;

	if ((*ap)->address < (*bp)->address)
		return -1;
	else if ((*ap)->address > (*bp)->address)
		return 1;
	else
		return 0;
}

struct segment *sort_segments(struct segment *list)
{
	struct segment **ptrs;
	int nsegments, i;
	struct segment *sp, **spp;

	nsegments = 0;
	for (sp = list; sp; sp = sp->next)
		nsegments++;

	ptrs = alloca(nsegments * sizeof *ptrs);
	spp = ptrs;
	for (sp = list; sp; sp = sp->next)
		*spp++ = sp;

	qsort(ptrs, nsegments, sizeof *ptrs, comp_seg);

	for (i = 0; i < nsegments-1; i++)
		ptrs[i]->next = ptrs[i+1];
	ptrs[i]->next = NULL;

	return ptrs[0];
}