xref: /libCEED/interface/ceed-jit-tools.c (revision b5404d5da366e284b3ef54a63de743df457e0da0)
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.h>
10 #include <ceed/backend.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[in]  ceed             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 opened
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 temporary 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 of local files in place of `#include "local.h"`
66 
67   @param[in]  ceed             Ceed object for error handling
68   @param[in]  source_file_path Absolute path to source file
69   @param[out] buffer           String buffer for source file contents
70 
71   @return An error code: 0 - success, otherwise - failure
72 
73   @ref Backend
74 **/
75 int CeedLoadSourceToInitializedBuffer(Ceed ceed, const char *source_file_path, char **buffer) {
76   FILE *source_file;
77   long  file_size, file_offset = 0;
78   char *temp_buffer;
79 
80   // Debug
81   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
82   CeedDebug256(ceed, 1, "Current source file: ");
83   CeedDebug(ceed, "%s\n", source_file_path);
84   CeedDebug256(ceed, 1, "Current buffer:\n");
85   CeedDebug(ceed, "%s\n", *buffer);
86 
87   // Read file to temporary buffer
88   source_file = fopen(source_file_path, "rb");
89   if (!source_file) {
90     // LCOV_EXCL_START
91     return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't open source file: %s", source_file_path);
92     // LCOV_EXCL_STOP
93   }
94   // -- Compute size of source
95   fseek(source_file, 0L, SEEK_END);
96   file_size = ftell(source_file);
97   rewind(source_file);
98   //  -- Allocate memory for entire source file
99   CeedCall(CeedCalloc(file_size + 1, &temp_buffer));
100   // -- Copy the file into the buffer
101   if (1 != fread(temp_buffer, file_size, 1, source_file)) {
102     // LCOV_EXCL_START
103     fclose(source_file);
104     CeedCall(CeedFree(&temp_buffer));
105     return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't read source file: %s", source_file_path);
106     // LCOV_EXCL_STOP
107   }
108   fclose(source_file);
109 
110   // Search for headers to include
111   const char *first_hash = strchr(temp_buffer, '#');
112   while (first_hash) {
113     // -- Check for 'include' keyword
114     const char *next_e     = strchr(first_hash, 'e');
115     char        keyword[8] = "";
116     if (next_e && next_e - first_hash >= 7) memcpy(keyword, &next_e[-6], 7);
117     bool is_hash_include = !strcmp(keyword, "include");
118     // ---- Spaces allowed in '#  include <header.h>'
119     if (next_e) {
120       for (CeedInt i = 1; first_hash - next_e + i < -6; i++) {
121         is_hash_include &= first_hash[i] == ' ';
122       }
123     }
124     if (is_hash_include) {
125       // -- Copy into buffer all preceding #
126       long current_size = strlen(*buffer);
127       long copy_size    = first_hash - &temp_buffer[file_offset];
128       CeedCall(CeedRealloc(current_size + copy_size + 2, buffer));
129       memcpy(&(*buffer)[current_size], "\n", 2);
130       memcpy(&(*buffer)[current_size + 1], &temp_buffer[file_offset], copy_size);
131       memcpy(&(*buffer)[current_size + copy_size], "", 1);
132       // -- Load local "header.h"
133       char *next_quote        = strchr(first_hash, '"');
134       char *next_new_line     = strchr(first_hash, '\n');
135       bool  is_local_header   = is_hash_include && next_quote && (next_new_line - next_quote > 0);
136       char *next_left_chevron = strchr(first_hash, '<');
137       bool  is_ceed_header    = is_hash_include && next_left_chevron && (next_new_line - next_left_chevron > 0) &&
138                             (!strncmp(next_left_chevron, "<ceed/jit-source/", 17) || !strncmp(next_left_chevron, "<ceed/types.h>", 14) ||
139                              !strncmp(next_left_chevron, "<ceed/ceed-f32.h>", 17) || !strncmp(next_left_chevron, "<ceed/ceed-f64.h>", 17));
140       if (is_local_header || is_ceed_header) {
141         // ---- Build source path
142         char *include_source_path;
143         if (is_local_header) {
144           long root_length           = strrchr(source_file_path, '/') - source_file_path;
145           long include_file_name_len = strchr(&next_quote[1], '"') - next_quote - 1;
146           CeedCall(CeedCalloc(root_length + include_file_name_len + 2, &include_source_path));
147           memcpy(include_source_path, source_file_path, root_length + 1);
148           memcpy(&include_source_path[root_length + 1], &next_quote[1], include_file_name_len);
149           memcpy(&include_source_path[root_length + include_file_name_len + 1], "", 1);
150         } else {
151           char *next_right_chevron = strchr(first_hash, '>');
152           char *ceed_relative_path;
153           long  ceed_relative_path_length = next_right_chevron - next_left_chevron - 1;
154           CeedCall(CeedCalloc(ceed_relative_path_length + 1, &ceed_relative_path));
155           memcpy(ceed_relative_path, &next_left_chevron[1], ceed_relative_path_length);
156           CeedCall(CeedGetJitAbsolutePath(ceed, ceed_relative_path, &include_source_path));
157           CeedCall(CeedFree(&ceed_relative_path));
158         }
159         // ---- Recursive call to load source to buffer
160         CeedDebug256(ceed, 2, "JiT Including: %s\n", include_source_path);
161         CeedCall(CeedLoadSourceToInitializedBuffer(ceed, include_source_path, buffer));
162         CeedCall(CeedFree(&include_source_path));
163       }
164       file_offset = strchr(first_hash, '\n') - temp_buffer + 1;
165     }
166     // -- Next hash
167     first_hash = strchr(&first_hash[1], '#');
168   }
169   // Copy rest of source file into buffer
170   long current_size = strlen(*buffer);
171   long copy_size    = strlen(&temp_buffer[file_offset]);
172   CeedCall(CeedRealloc(current_size + copy_size + 2, buffer));
173   memcpy(&(*buffer)[current_size], "\n", 2);
174   memcpy(&(*buffer)[current_size + 1], &temp_buffer[file_offset], copy_size);
175   memcpy(&(*buffer)[current_size + copy_size + 1], "", 1);
176 
177   // Cleanup
178   CeedCall(CeedFree(&temp_buffer));
179 
180   // Debug
181   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
182   CeedDebug256(ceed, 1, "Current source file: ");
183   CeedDebug(ceed, "%s\n", source_file_path);
184   CeedDebug256(ceed, 1, "Final buffer:\n");
185   CeedDebug(ceed, "%s\n", *buffer);
186 
187   return CEED_ERROR_SUCCESS;
188 }
189 
190 /**
191   @brief Initialize and load source file into string buffer, including full text of local files in place of `#include "local.h"`.
192          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
193 
194   @param[in]  ceed             Ceed object for error handling
195   @param[in]  source_file_path Absolute path to source file
196   @param[out] buffer           String buffer for source file contents
197 
198   @return An error code: 0 - success, otherwise - failure
199 
200   @ref Backend
201 **/
202 int CeedLoadSourceToBuffer(Ceed ceed, const char *source_file_path, char **buffer) {
203   // Initialize buffer
204   CeedCall(CeedCalloc(1, buffer));
205 
206   // Load to initalized buffer
207   CeedCall(CeedLoadSourceToInitializedBuffer(ceed, source_file_path, buffer));
208 
209   return CEED_ERROR_SUCCESS;
210 }
211 
212 /**
213   @brief Build an absolute filepath from a base filepath and an absolute filepath.
214            This helps construct source file paths for `CeedLoadSourceToBuffer()`.
215          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
216 
217   @param[in]  ceed               Ceed object for error handling
218   @param[in]  base_file_path     Absolute path to current file
219   @param[in]  relative_file_path Relative path to target file
220   @param[out] new_file_path      String buffer for absolute path to target file
221 
222   @return An error code: 0 - success, otherwise - failure
223 
224   @ref Backend
225 **/
226 int CeedPathConcatenate(Ceed ceed, const char *base_file_path, const char *relative_file_path, char **new_file_path) {
227   char  *last_slash  = strrchr(base_file_path, '/');
228   size_t base_length = (last_slash - base_file_path + 1), relative_length = strlen(relative_file_path),
229          new_file_path_length = base_length + relative_length + 1;
230 
231   CeedCall(CeedCalloc(new_file_path_length, new_file_path));
232   memcpy(*new_file_path, base_file_path, base_length);
233   memcpy(&((*new_file_path)[base_length]), relative_file_path, relative_length);
234 
235   return CEED_ERROR_SUCCESS;
236 }
237 
238 /**
239   @brief Find the relative filepath to an installed JiT file
240 
241   @param[in]  absolute_file_path Absolute path to installed JiT file
242   @param[out] relative_file_path Relative path to installed JiT file
243 
244   @return An error code: 0 - success, otherwise - failure
245 
246   @ref Backend
247 **/
248 int CeedGetJitRelativePath(const char *absolute_file_path, const char **relative_file_path) {
249   *(relative_file_path) = strstr(absolute_file_path, "ceed/jit-source");
250 
251   if (!*relative_file_path) {
252     // LCOV_EXCL_START
253     return CeedError(NULL, CEED_ERROR_MAJOR, "Couldn't find relative path including 'ceed/jit-source' for: %s", absolute_file_path);
254     // LCOV_EXCL_STOP
255   }
256   return CEED_ERROR_SUCCESS;
257 }
258 
259 /**
260   @brief Build an absolute filepath to a JiT file
261 
262   @param[in]  ceed               Ceed object for error handling
263   @param[in]  relative_file_path Relative path to installed JiT file
264   @param[out] absolute_file_path String buffer for absolute path to target file
265 
266   @return An error code: 0 - success, otherwise - failure
267 
268   @ref Backend
269 **/
270 int CeedGetJitAbsolutePath(Ceed ceed, const char *relative_file_path, char **absolute_file_path) {
271   Ceed ceed_parent;
272 
273   // Debug
274   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
275   CeedDebug256(ceed, 1, "Relative JiT source file: ");
276   CeedDebug(ceed, "%s\n", relative_file_path);
277 
278   CeedCall(CeedGetParent(ceed, &ceed_parent));
279   for (CeedInt i = 0; i < ceed_parent->num_jit_source_roots; i++) {
280     bool is_valid;
281 
282     // Debug
283     CeedDebug256(ceed, 1, "Checking JiT root: ");
284     CeedDebug(ceed, "%s\n", ceed_parent->jit_source_roots[i]);
285 
286     // Build and check absolute path with current root
287     CeedCall(CeedPathConcatenate(ceed, ceed_parent->jit_source_roots[i], relative_file_path, absolute_file_path));
288     CeedCall(CeedCheckFilePath(ceed, *absolute_file_path, &is_valid));
289 
290     if (is_valid) return CEED_ERROR_SUCCESS;
291     else CeedCall(CeedFree(absolute_file_path));
292   }
293 
294   // LCOV_EXCL_START
295   return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't find matching JiT source file: %s", relative_file_path);
296   // LCOV_EXCL_STOP
297 }
298