• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <stdbool.h>
2 #include <stdint.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <alloca.h>
6 #include <errno.h>
7 
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 
13 #if CPUINFO_MOCK
14 	#include <cpuinfo-mock.h>
15 #endif
16 #include <linux/api.h>
17 #include <cpuinfo/log.h>
18 
19 
cpuinfo_linux_parse_small_file(const char * filename,size_t buffer_size,cpuinfo_smallfile_callback callback,void * context)20 bool cpuinfo_linux_parse_small_file(const char* filename, size_t buffer_size, cpuinfo_smallfile_callback callback, void* context) {
21 	int file = -1;
22 	bool status = false;
23 	char* buffer = (char*) alloca(buffer_size);
24 
25 	#if CPUINFO_LOG_DEBUG_PARSERS
26 		cpuinfo_log_debug("parsing small file %s", filename);
27 	#endif
28 
29 #if CPUINFO_MOCK
30 	file = cpuinfo_mock_open(filename, O_RDONLY);
31 #else
32 	file = open(filename, O_RDONLY);
33 #endif
34 	if (file == -1) {
35 		cpuinfo_log_info("failed to open %s: %s", filename, strerror(errno));
36 		goto cleanup;
37 	}
38 
39 	size_t buffer_position = 0;
40 	ssize_t bytes_read;
41 	do {
42 #if CPUINFO_MOCK
43 		bytes_read = cpuinfo_mock_read(file, &buffer[buffer_position], buffer_size - buffer_position);
44 #else
45 		bytes_read = read(file, &buffer[buffer_position], buffer_size - buffer_position);
46 #endif
47 		if (bytes_read < 0) {
48 			cpuinfo_log_info("failed to read file %s at position %zu: %s", filename, buffer_position, strerror(errno));
49 			goto cleanup;
50 		}
51 		buffer_position += (size_t) bytes_read;
52 		if (buffer_position >= buffer_size) {
53 			cpuinfo_log_error("failed to read file %s: insufficient buffer of size %zu", filename, buffer_size);
54 			goto cleanup;
55 		}
56 	} while (bytes_read != 0);
57 
58 	status = callback(buffer, &buffer[buffer_position], context);
59 
60 cleanup:
61 	if (file != -1) {
62 #if CPUINFO_MOCK
63 		cpuinfo_mock_close(file);
64 #else
65 		close(file);
66 #endif
67 		file = -1;
68 	}
69 	return status;
70 }
71