xref: /libCEED/interface/ceed-jit-tools.c (revision 6574a04ff2135c3834f1b6ef9a4ec7566c4782db)
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   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, 2, "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, 1, "---------- Ceed JiT ----------\n");
178   CeedDebug256(ceed, 1, "Current source file: ");
179   CeedDebug(ceed, "%s\n", source_file_path);
180   CeedDebug256(ceed, 1, "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          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
189 
190   @param[in]  ceed             Ceed object for error handling
191   @param[in]  source_file_path Absolute path to source file
192   @param[out] buffer           String buffer for source file contents
193 
194   @return An error code: 0 - success, otherwise - failure
195 
196   @ref Backend
197 **/
198 int CeedLoadSourceToBuffer(Ceed ceed, const char *source_file_path, char **buffer) {
199   // Initialize buffer
200   CeedCall(CeedCalloc(1, buffer));
201 
202   // Load to initalized buffer
203   CeedCall(CeedLoadSourceToInitializedBuffer(ceed, source_file_path, buffer));
204 
205   return CEED_ERROR_SUCCESS;
206 }
207 
208 /**
209   @brief Build an absolute filepath from a base filepath and an absolute filepath.
210            This helps construct source file paths for `CeedLoadSourceToBuffer()`.
211          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
212 
213   @param[in]  ceed               Ceed object for error handling
214   @param[in]  base_file_path     Absolute path to current file
215   @param[in]  relative_file_path Relative path to target file
216   @param[out] new_file_path      String buffer for absolute path to target file
217 
218   @return An error code: 0 - success, otherwise - failure
219 
220   @ref Backend
221 **/
222 int CeedPathConcatenate(Ceed ceed, const char *base_file_path, const char *relative_file_path, char **new_file_path) {
223   char  *last_slash  = strrchr(base_file_path, '/');
224   size_t base_length = (last_slash - base_file_path + 1), relative_length = strlen(relative_file_path),
225          new_file_path_length = base_length + relative_length + 1;
226 
227   CeedCall(CeedCalloc(new_file_path_length, new_file_path));
228   memcpy(*new_file_path, base_file_path, base_length);
229   memcpy(&((*new_file_path)[base_length]), relative_file_path, relative_length);
230 
231   return CEED_ERROR_SUCCESS;
232 }
233 
234 /**
235   @brief Find the relative filepath to an installed JiT file
236 
237   @param[in]  absolute_file_path Absolute path to installed JiT file
238   @param[out] relative_file_path Relative path to installed JiT file
239 
240   @return An error code: 0 - success, otherwise - failure
241 
242   @ref Backend
243 **/
244 int CeedGetJitRelativePath(const char *absolute_file_path, const char **relative_file_path) {
245   *(relative_file_path) = strstr(absolute_file_path, "ceed/jit-source");
246   CeedCheck(*relative_file_path, NULL, CEED_ERROR_MAJOR, "Couldn't find relative path including 'ceed/jit-source' for: %s", absolute_file_path);
247   return CEED_ERROR_SUCCESS;
248 }
249 
250 /**
251   @brief Build an absolute filepath to a JiT file
252 
253   @param[in]  ceed               Ceed object for error handling
254   @param[in]  relative_file_path Relative path to installed JiT file
255   @param[out] absolute_file_path String buffer for absolute path to target file
256 
257   @return An error code: 0 - success, otherwise - failure
258 
259   @ref Backend
260 **/
261 int CeedGetJitAbsolutePath(Ceed ceed, const char *relative_file_path, char **absolute_file_path) {
262   Ceed ceed_parent;
263 
264   // Debug
265   CeedDebug256(ceed, 1, "---------- Ceed JiT ----------\n");
266   CeedDebug256(ceed, 1, "Relative JiT source file: ");
267   CeedDebug(ceed, "%s\n", relative_file_path);
268 
269   CeedCall(CeedGetParent(ceed, &ceed_parent));
270   for (CeedInt i = 0; i < ceed_parent->num_jit_source_roots; i++) {
271     bool is_valid;
272 
273     // Debug
274     CeedDebug256(ceed, 1, "Checking JiT root: ");
275     CeedDebug(ceed, "%s\n", ceed_parent->jit_source_roots[i]);
276 
277     // Build and check absolute path with current root
278     CeedCall(CeedPathConcatenate(ceed, ceed_parent->jit_source_roots[i], relative_file_path, absolute_file_path));
279     CeedCall(CeedCheckFilePath(ceed, *absolute_file_path, &is_valid));
280 
281     if (is_valid) return CEED_ERROR_SUCCESS;
282     else CeedCall(CeedFree(absolute_file_path));
283   }
284 
285   // LCOV_EXCL_START
286   return CeedError(ceed, CEED_ERROR_MAJOR, "Couldn't find matching JiT source file: %s", relative_file_path);
287   // LCOV_EXCL_STOP
288 }
289