MCPcopy Create free account
hub / github.com/DeusData/codebase-memory-mcp / read_file

Function read_file

src/pipeline/pass_definitions.c:42–103  ·  view source on GitHub ↗

Read entire file into heap-allocated buffer. Returns NULL on error. * Caller must free(). Sets *out_len to byte count. *out_size receives the * on-disk size and *out_status the failure reason, so the caller can attribute * a skip to the right phase/reason (read vs oversized) instead of a silent * drop. Both out params may be NULL. */

Source from the content-addressed store, hash-verified

40 * a skip to the right phase/reason (read vs oversized) instead of a silent
41 * drop. Both out params may be NULL. */
42static char *read_file(const char *path, int *out_len, long *out_size,
43 cbm_read_status_t *out_status) {
44 if (out_size) {
45 *out_size = 0;
46 }
47 if (out_status) {
48 *out_status = CBM_READ_OK;
49 }
50 FILE *f = cbm_fopen(path, "rb");
51 if (!f) {
52 if (out_status) {
53 *out_status = CBM_READ_OPEN_FAIL;
54 }
55 return NULL;
56 }
57
58 (void)fseek(f, 0, SEEK_END);
59 long size = ftell(f);
60 (void)fseek(f, 0, SEEK_SET);
61 if (out_size) {
62 *out_size = size;
63 }
64
65 if (size <= 0) {
66 (void)fclose(f);
67 if (out_status) {
68 *out_status = CBM_READ_EMPTY;
69 }
70 return NULL;
71 }
72 if (size > cbm_max_file_bytes()) { /* generous, env-configurable cap (B4) */
73 (void)fclose(f);
74 if (out_status) {
75 *out_status = CBM_READ_OVERSIZED;
76 }
77 return NULL;
78 }
79
80 /* +16 padding: tree-sitter's lexer peeks a few bytes past the final UTF-8
81 * character when computing lookahead, reading beyond the logical end.
82 * Over-allocate and zero the tail so that read stays in-bounds (ASan
83 * flags it as a heap-buffer-overflow otherwise; harmless but real UB). */
84 enum { CBM_TS_LOOKAHEAD_PAD = 16 };
85 char *buf = malloc((size_t)size + CBM_TS_LOOKAHEAD_PAD);
86 if (!buf) {
87 (void)fclose(f);
88 if (out_status) {
89 *out_status = CBM_READ_OOM;
90 }
91 return NULL;
92 }
93
94 size_t nread = fread(buf, SKIP_ONE, size, f);
95 (void)fclose(f);
96
97 if (nread > (size_t)size) {
98 nread = (size_t)size;
99 }

Callers 1

Calls 2

cbm_fopenFunction · 0.85
cbm_max_file_bytesFunction · 0.85

Tested by

no test coverage detected