summaryrefslogtreecommitdiff
path: root/src/util/slbt_dump_machine.c
blob: 1b4221191aff13dbe451fc3249bbf86dd6e888d2 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*******************************************************************/
/*  slibtool: a strong libtool implementation, written in C        */
/*  Copyright (C) 2016--2024  SysDeer Technologies, LLC            */
/*  Released under the Standard MIT License; see COPYING.SLIBTOOL. */
/*******************************************************************/

#include <stdio.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/wait.h>

#include <slibtool/slibtool.h>
#include "slibtool_spawn_impl.h"
#include "slibtool_snprintf_impl.h"

static void slbt_util_dump_machine_child(
	char *	program,
	int	fd[2])
{
	char *	compiler;
	char *	argv[3];

	close(fd[0]);

	if ((compiler = strrchr(program,'/')))
		compiler++;
	else
		compiler = program;

	argv[0] = compiler;
	argv[1] = "-dumpmachine";
	argv[2] = 0;

	if ((fd[0] = openat(AT_FDCWD,"/dev/null",O_RDONLY,0)) >= 0)
		if (dup2(fd[0],0) == 0)
			if (dup2(fd[1],1) == 1)
				execvp(program,argv);

	_exit(EXIT_FAILURE);
}

int slbt_util_dump_machine(
	const char *	compiler,
	char *		machine,
	size_t		buflen)
{
	ssize_t	ret;
	pid_t	pid;
	pid_t	rpid;
	int	code;
	int	fd[2];
	char *	mark;
	char	program[PATH_MAX];

	/* setup */
	if (!machine || !buflen || !--buflen) {
		errno = EINVAL;
		return -1;
	}

	if (slbt_snprintf(program,sizeof(program),
			"%s",compiler) < 0)
		return -1;

	/* fork */
	if (pipe(fd))
		return -1;

	if ((pid = slbt_fork()) < 0) {
		close(fd[0]);
		close(fd[1]);
		return -1;
	}

	/* child */
	if (pid == 0)
		slbt_util_dump_machine_child(
			program,
			fd);

	/* parent */
	close(fd[1]);

	mark = machine;

	for (; buflen; ) {
		ret = read(fd[0],mark,buflen);

		while ((ret < 0) && (errno == EINTR))
			ret = read(fd[0],mark,buflen);

		if (ret > 0) {
			buflen -= ret;
			mark   += ret;

		} else if (ret == 0) {
			close(fd[0]);
			buflen = 0;

		} else {
			close(fd[0]);
			return -1;
		}
	}

	/* execve verification */
	rpid = waitpid(
		pid,
		&code,
		0);

	if ((rpid != pid) || code) {
		errno = ESTALE;
		return -1;
	}

	/* newline verification */
	if ((mark == machine) || (*--mark != '\n')) {
		errno = ERANGE;
		return -1;
	}

	*mark = 0;

	/* portbld <--> unknown synonym? */
	if ((mark = strstr(machine,"-portbld-")))
		memcpy(mark,"-unknown",8);

	/* all done */
	return 0;
}