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