xref: /libCEED/rust/libceed-sys/c-src/interface/ceed-jit-tools.c (revision 2b730f8b5a9c809740a0b3b302db43a719c636b1)
1 // Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3 //
4 // SPDX-License-Identifier: BSD-2-Clause
5 //
6 // This file is part of CEED:  http://github.com/ceed
7 
8 #include <ceed-impl.h>
9 #include <ceed/backend.h>
10 #include <ceed/ceed.h>
11 #include <ceed/jit-tools.h>
12 #include <stdbool.h>
13 #include <stdio.h>
14 #include <string.h>
15 
16 /**
17   @brief Check if valid file exists at path given
18 
19   @param ceed                  A Ceed object for error handling
20   @param[in]  source_file_path Absolute path to source file
21   @param[out] is_valid         Boolean flag indicating if file can be opend
22 
23   @return An error code: 0 - success, otherwise - failure
24 
25   @ref Backend
26 **/
27 int CeedCheckFilePath(Ceed ceed, const char *source_file_path, bool *is_valid) {
28   // Sometimes we have path/to/file.h:function_name
29   // Create tempory file path without name, if needed
30   char *source_file_path_only;
31   char *last_colon = strrchr(source_file_path, ':');
32   if (last_colon) {
33     size_t source_file_path_length = (last_colon - source_file_path + 1);
34 
35     CeedCall(CeedCalloc(source_file_path_length, &source_file_path_only));
36     memcpy(source_file_path_only, source_file_path, source_file_path_length - 1);
37   } else {
38     source_file_path_only = (char *)source_file_path;
39   }
40 
41   // Debug
42   CeedDebug256(ceed, 1, "Checking for source file: ");
43   CeedDebug(ceed, "%s\n", source_file_path_only);
44 
45   // Check for valid file path
46   FILE *source_file;
47   source_file = fopen(source_file_path_only, "rb");
48   *is_valid   = !!source_file;
49 
50   if (*is_valid) {
51     // Debug
52     CeedDebug256(ceed, 1, "Found JiT source file: ");
53     CeedDebug(ceed, "%s\n", source_file_path_only);
54 
55     fclose(source_file);
56   }
57 
58   // Free temp file path, if used
59   if (last_colon) CeedCall(CeedFree(&source_file_path_only));
60 
61   return CEED_ERROR_SUCCESS;
62 }
63 
64 /**
65   @brief Load source file into initialized string buffer, including full text
66            of local files in place of `#include "local.h"`
67 
68   @param ceed                  A Ceed object for error handling
69   @param[in]  source_file_path Absolute path to source file
70   @param[out] buffer           String buffer for source file contents
71 
72   @return An error code: 0 - success, otherwise - failure
73 
74   @ref Backend
75 **/
76 int CeedLoadSourceToInitializedBuffer(Ceed ceed, const char *source_file_path, char **buffer) {
77   FILE *source_file;
78   long  file_size, file_offset = 0;
79   char *temp_buffer;
80 
81   // Debug
82   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
83   CeedDebug256(ceed, 1, "Current source file: ");
84   CeedDebug(ceed, "%s\n", source_file_path);
85   CeedDebug256(ceed, 1, "Current buffer:\n");
86   CeedDebug(ceed, "%s\n", *buffer);
87 
88   // Read file to temporary buffer
89   source_file = fopen(source_file_path, "rb");
90   if (!source_file) {
91     // LCOV_EXCL_START
92     return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't open source file: %s", source_file_path);
93     // LCOV_EXCL_STOP
94   }
95   // -- Compute size of source
96   fseek(source_file, 0L, SEEK_END);
97   file_size = ftell(source_file);
98   rewind(source_file);
99   //  -- Allocate memory for entire source file
100   CeedCall(CeedCalloc(file_size + 1, &temp_buffer));
101   // -- Copy the file into the buffer
102   if (1 != fread(temp_buffer, file_size, 1, source_file)) {
103     // LCOV_EXCL_START
104     fclose(source_file);
105     CeedCall(CeedFree(&temp_buffer));
106     return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't read source file: %s", source_file_path);
107     // LCOV_EXCL_STOP
108   }
109   fclose(source_file);
110 
111   // Search for headers to include
112   const char *first_hash = strchr(temp_buffer, '#');
113   while (first_hash) {
114     // -- Check for 'include' keyword
115     const char *next_e     = strchr(first_hash, 'e');
116     char        keyword[8] = "";
117     if (next_e && next_e - first_hash >= 7) memcpy(keyword, &next_e[-6], 7);
118     bool is_hash_include = !strcmp(keyword, "include");
119     // ---- Spaces allowed in '#  include <header.h>'
120     if (next_e) {
121       for (CeedInt i = 1; first_hash - next_e + i < -6; i++) {
122         is_hash_include &= first_hash[i] == ' ';
123       }
124     }
125     if (is_hash_include) {
126       // -- Copy into buffer all preceding #
127       long current_size = strlen(*buffer);
128       long copy_size    = first_hash - &temp_buffer[file_offset];
129       CeedCall(CeedRealloc(current_size + copy_size + 2, buffer));
130       memcpy(&(*buffer)[current_size], "\n", 2);
131       memcpy(&(*buffer)[current_size + 1], &temp_buffer[file_offset], copy_size);
132       memcpy(&(*buffer)[current_size + copy_size], "", 1);
133       // -- Load local "header.h"
134       char *next_quote        = strchr(first_hash, '"');
135       char *next_new_line     = strchr(first_hash, '\n');
136       bool  is_local_header   = is_hash_include && next_quote && (next_new_line - next_quote > 0);
137       char *next_left_chevron = strchr(first_hash, '<');
138       bool  is_ceed_header    = is_hash_include && next_left_chevron && (next_new_line - next_left_chevron > 0) &&
139                             (!strncmp(next_left_chevron, "<ceed/jit-source/", 17) || !strncmp(next_left_chevron, "<ceed/types.h>", 14) ||
140                              !strncmp(next_left_chevron, "<ceed/ceed-f32.h>", 17) || !strncmp(next_left_chevron, "<ceed/ceed-f64.h>", 17));
141       if (is_local_header || is_ceed_header) {
142         // ---- Build source path
143         char *include_source_path;
144         if (is_local_header) {
145           long root_length           = strrchr(source_file_path, '/') - source_file_path;
146           long include_file_name_len = strchr(&next_quote[1], '"') - next_quote - 1;
147           CeedCall(CeedCalloc(root_length + include_file_name_len + 2, &include_source_path));
148           memcpy(include_source_path, source_file_path, root_length + 1);
149           memcpy(&include_source_path[root_length + 1], &next_quote[1], include_file_name_len);
150           memcpy(&include_source_path[root_length + include_file_name_len + 1], "", 1);
151         } else {
152           char *next_right_chevron = strchr(first_hash, '>');
153           char *ceed_relative_path;
154           long  ceed_relative_path_length = next_right_chevron - next_left_chevron - 1;
155           CeedCall(CeedCalloc(ceed_relative_path_length + 1, &ceed_relative_path));
156           memcpy(ceed_relative_path, &next_left_chevron[1], ceed_relative_path_length);
157           CeedCall(CeedGetJitAbsolutePath(ceed, ceed_relative_path, &include_source_path));
158           CeedCall(CeedFree(&ceed_relative_path));
159         }
160         // ---- Recursive call to load source to buffer
161         CeedDebug256(ceed, 2, "JiT Including: %s\n", include_source_path);
162         CeedCall(CeedLoadSourceToInitializedBuffer(ceed, include_source_path, buffer));
163         CeedCall(CeedFree(&include_source_path));
164       }
165       file_offset = strchr(first_hash, '\n') - temp_buffer + 1;
166     }
167     // -- Next hash
168     first_hash = strchr(&first_hash[1], '#');
169   }
170   // Copy rest of source file into buffer
171   long current_size = strlen(*buffer);
172   long copy_size    = strlen(&temp_buffer[file_offset]);
173   CeedCall(CeedRealloc(current_size + copy_size + 2, buffer));
174   memcpy(&(*buffer)[current_size], "\n", 2);
175   memcpy(&(*buffer)[current_size + 1], &temp_buffer[file_offset], copy_size);
176   memcpy(&(*buffer)[current_size + copy_size + 1], "", 1);
177 
178   // Cleanup
179   CeedCall(CeedFree(&temp_buffer));
180 
181   // Debug
182   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
183   CeedDebug256(ceed, 1, "Current source file: ");
184   CeedDebug(ceed, "%s\n", source_file_path);
185   CeedDebug256(ceed, 1, "Final buffer:\n");
186   CeedDebug(ceed, "%s\n", *buffer);
187 
188   return CEED_ERROR_SUCCESS;
189 }
190 
191 /**
192   @brief Initalize and load source file into string buffer, including full text
193            of local files in place of `#include "local.h"`.
194          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
195 
196   @param ceed                  A Ceed object for error handling
197   @param[in]  source_file_path Absolute path to source file
198   @param[out] buffer           String buffer for source file contents
199 
200   @return An error code: 0 - success, otherwise - failure
201 
202   @ref Backend
203 **/
204 int CeedLoadSourceToBuffer(Ceed ceed, const char *source_file_path, char **buffer) {
205   // Initalize buffer
206   CeedCall(CeedCalloc(1, buffer));
207 
208   // Load to initalized buffer
209   CeedCall(CeedLoadSourceToInitializedBuffer(ceed, source_file_path, buffer));
210 
211   return CEED_ERROR_SUCCESS;
212 }
213 
214 /**
215   @brief Build an absolute filepath from a base filepath and an absolute filepath.
216            This helps construct source file paths for `CeedLoadSourceToBuffer()`.
217          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
218 
219   @param ceed                     A Ceed object for error handling
220   @param[in]  base_file_path      Absolute path to current file
221   @param[in]  relative_file_path  Relative path to target file
222   @param[out] new_file_path       String buffer for absolute path to target file
223 
224   @return An error code: 0 - success, otherwise - failure
225 
226   @ref Backend
227 **/
228 int CeedPathConcatenate(Ceed ceed, const char *base_file_path, const char *relative_file_path, char **new_file_path) {
229   char  *last_slash  = strrchr(base_file_path, '/');
230   size_t base_length = (last_slash - base_file_path + 1), relative_length = strlen(relative_file_path),
231          new_file_path_length = base_length + relative_length + 1;
232 
233   CeedCall(CeedCalloc(new_file_path_length, new_file_path));
234   memcpy(*new_file_path, base_file_path, base_length);
235   memcpy(&((*new_file_path)[base_length]), relative_file_path, relative_length);
236 
237   return CEED_ERROR_SUCCESS;
238 }
239 
240 /**
241   @brief Find the relative filepath to an installed JiT file
242 
243   @param[in]  absolute_file_path Absolute path to installed JiT file
244   @param[out] relative_file_path Relative path to installed JiT file
245 
246   @return An error code: 0 - success, otherwise - failure
247 
248   @ref Backend
249 **/
250 int CeedGetJitRelativePath(const char *absolute_file_path, const char **relative_file_path) {
251   *(relative_file_path) = strstr(absolute_file_path, "ceed/jit-source");
252 
253   if (!*relative_file_path) {
254     // LCOV_EXCL_START
255     return CeedError(NULL, CEED_ERROR_MAJOR, "Couldn't find relative path including 'ceed/jit-source' for: %s", absolute_file_path);
256     // LCOV_EXCL_STOP
257   }
258   return CEED_ERROR_SUCCESS;
259 }
260 
261 /**
262   @brief Build an absolute filepath to a JiT file
263 
264   @param ceed                    A Ceed object for error handling
265   @param[in]  relative_file_path Relative path to installed JiT file
266   @param[out] absolute_file_path String buffer for absolute path to target file
267 
268   @return An error code: 0 - success, otherwise - failure
269 
270   @ref Backend
271 **/
272 int CeedGetJitAbsolutePath(Ceed ceed, const char *relative_file_path, char **absolute_file_path) {
273   Ceed ceed_parent;
274 
275   // Debug
276   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
277   CeedDebug256(ceed, 1, "Relative JiT source file: ");
278   CeedDebug(ceed, "%s\n", relative_file_path);
279 
280   CeedCall(CeedGetParent(ceed, &ceed_parent));
281   for (CeedInt i = 0; i < ceed_parent->num_jit_source_roots; i++) {
282     bool is_valid;
283 
284     // Debug
285     CeedDebug256(ceed, 1, "Checking JiT root: ");
286     CeedDebug(ceed, "%s\n", ceed_parent->jit_source_roots[i]);
287 
288     // Build and check absolute path with current root
289     CeedCall(CeedPathConcatenate(ceed, ceed_parent->jit_source_roots[i], relative_file_path, absolute_file_path));
290     CeedCall(CeedCheckFilePath(ceed, *absolute_file_path, &is_valid));
291 
292     if (is_valid) return CEED_ERROR_SUCCESS;
293     else CeedCall(CeedFree(absolute_file_path));
294   }
295 
296   // LCOV_EXCL_START
297   return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't find matching JiT source file: %s", relative_file_path);
298   // LCOV_EXCL_STOP
299 }
300