Skip to content

Commit 4ed7de5

Browse files
committed
Stat file first to check directory
1 parent 7d14ed3 commit 4ed7de5

File tree

3 files changed

+25
-16
lines changed

3 files changed

+25
-16
lines changed

include/prism/util/pm_string.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
#include <fcntl.h>
2323
#include <sys/mman.h>
2424
#include <sys/stat.h>
25+
#elif defined(PRISM_HAS_FILESYSTEM)
26+
#include <fcntl.h>
27+
#include <sys/stat.h>
2528
#endif
2629

2730
/**

src/util/pm_string.c

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -254,38 +254,45 @@ pm_string_file_init(pm_string_t *string, const char *filepath) {
254254
*string = (pm_string_t) { .type = PM_STRING_OWNED, .source = source, .length = (size_t) file_size };
255255
return PM_STRING_INIT_SUCCESS;
256256
#elif defined(PRISM_HAS_FILESYSTEM)
257-
FILE *file = fopen(filepath, "rb");
258-
if (file == NULL) {
257+
// Open the file for reading
258+
int fd = open(filepath, O_RDONLY);
259+
if (fd == -1) {
259260
return PM_STRING_INIT_ERROR_GENERIC;
260261
}
261262

262-
fseek(file, 0, SEEK_END);
263-
long file_size = ftell(file);
264-
265-
if (file_size == -1) {
266-
fclose(file);
263+
// Stat the file to get the file size
264+
struct stat sb;
265+
if (fstat(fd, &sb) == -1) {
266+
close(fd);
267267
return PM_STRING_INIT_ERROR_GENERIC;
268268
}
269269

270-
if (file_size == 0) {
271-
fclose(file);
270+
// Ensure it is a file and not a directory
271+
if (S_ISDIR(sb.st_mode)) {
272+
close(fd);
273+
return PM_STRING_INIT_ERROR_DIRECTORY;
274+
}
275+
276+
// Check the size to see if it's empty
277+
size_t size = (size_t) sb.st_size;
278+
if (size == 0) {
279+
close(fd);
272280
const uint8_t source[] = "";
273281
*string = (pm_string_t) { .type = PM_STRING_CONSTANT, .source = source, .length = 0 };
274282
return PM_STRING_INIT_SUCCESS;
275283
}
276284

277-
size_t length = (size_t) file_size;
285+
size_t length = (size_t) size;
278286
uint8_t *source = xmalloc(length);
279287
if (source == NULL) {
280-
fclose(file);
288+
close(fd);
281289
return PM_STRING_INIT_ERROR_GENERIC;
282290
}
283291

284-
fseek(file, 0, SEEK_SET);
285-
size_t bytes_read = fread(source, length, 1, file);
286-
fclose(file);
292+
long bytes_read = (long) read(fd, source, length);
293+
close(fd);
287294

288-
if (bytes_read != 1) {
295+
if (bytes_read == -1) {
289296
xfree(source);
290297
return PM_STRING_INIT_ERROR_GENERIC;
291298
}

test/prism/api/parse_test.rb

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ def test_parse_directory
8787
rescue SystemCallError => error
8888
end
8989

90-
return if error.nil? || error.is_a?(Errno::ENOMEM)
9190
assert_kind_of Errno::EISDIR, error
9291
end
9392

0 commit comments

Comments
 (0)