libsigrok  0.5.2
sigrok hardware access and backend library
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
resource.c
Go to the documentation of this file.
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <glib.h>
24 #include <glib/gstdio.h>
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27 
28 /** @cond PRIVATE */
29 #define LOG_PREFIX "resource"
30 /** @endcond */
31 
32 /**
33  * @file
34  *
35  * Access to resource files.
36  */
37 
38 /**
39  * Get a list of paths where we look for resource (e.g. firmware) files.
40  *
41  * @param res_type The type of resource to get the search paths for.
42  *
43  * @return List of strings that must be freed after use, including the strings.
44  *
45  * @since 0.5.1
46  */
47 SR_API GSList *sr_resourcepaths_get(int res_type)
48 {
49  const char *subdir = NULL;
50  GSList *l = NULL;
51  const char *env;
52  const char *const *datadirs;
53 
54  if (res_type == SR_RESOURCE_FIRMWARE) {
55  subdir = "sigrok-firmware";
56 
57  env = g_getenv("SIGROK_FIRMWARE_DIR");
58  if (env)
59  l = g_slist_append(l, g_strdup(env));
60  }
61 
62  l = g_slist_append(l, g_build_filename(g_get_user_data_dir(), subdir, NULL));
63 
64 #ifdef FIRMWARE_DIR
65  if (res_type == SR_RESOURCE_FIRMWARE) {
66  /*
67  * Scan the hard-coded directory before the system directories to
68  * avoid picking up possibly outdated files from a system install.
69  */
70  l = g_slist_append(l, g_strdup(FIRMWARE_DIR));
71  }
72 #endif
73 
74  datadirs = g_get_system_data_dirs();
75  while (*datadirs)
76  l = g_slist_append(l, g_build_filename(*datadirs++, subdir, NULL));
77 
78  return l;
79 }
80 
81 /**
82  * Retrieve the size of the open stream @a file.
83  *
84  * This function only works on seekable streams. However, the set of seekable
85  * streams is generally congruent with the set of streams that have a size.
86  * Code that needs to work with any type of stream (including pipes) should
87  * require neither seekability nor advance knowledge of the size.
88  * On failure, the return value is negative and errno is set.
89  *
90  * @param file An I/O stream opened in binary mode.
91  * @return The size of @a file in bytes, or a negative value on failure.
92  *
93  * @private
94  */
95 SR_PRIV int64_t sr_file_get_size(FILE *file)
96 {
97  off_t filepos, filesize;
98 
99  /* ftello() and fseeko() are not standard C, but part of POSIX.1-2001.
100  * Thus, if these functions are available at all, they can reasonably
101  * be expected to also conform to POSIX semantics. In particular, this
102  * means that ftello() after fseeko(..., SEEK_END) has a defined result
103  * and can be used to get the size of a seekable stream.
104  * On Windows, the result is fully defined only for binary streams.
105  */
106  filepos = ftello(file);
107  if (filepos < 0)
108  return -1;
109 
110  if (fseeko(file, 0, SEEK_END) < 0)
111  return -1;
112 
113  filesize = ftello(file);
114  if (filesize < 0)
115  return -1;
116 
117  if (fseeko(file, filepos, SEEK_SET) < 0)
118  return -1;
119 
120  return filesize;
121 }
122 
123 static FILE *try_open_file(const char *datadir, const char *subdir,
124  const char *name)
125 {
126  char *filename;
127  FILE *file;
128 
129  if (subdir)
130  filename = g_build_filename(datadir, subdir, name, NULL);
131  else
132  filename = g_build_filename(datadir, name, NULL);
133 
134  file = g_fopen(filename, "rb");
135 
136  if (file)
137  sr_info("Opened '%s'.", filename);
138  else
139  sr_spew("Attempt to open '%s' failed: %s",
140  filename, g_strerror(errno));
141  g_free(filename);
142 
143  return file;
144 }
145 
146 static int resource_open_default(struct sr_resource *res,
147  const char *name, void *cb_data)
148 {
149  GSList *paths, *p = NULL;
150  int64_t filesize;
151  FILE *file = NULL;
152 
153  (void)cb_data;
154 
155  paths = sr_resourcepaths_get(res->type);
156 
157  /* Currently, the enum only defines SR_RESOURCE_FIRMWARE. */
158  if (res->type != SR_RESOURCE_FIRMWARE) {
159  sr_err("%s: unknown type %d.", __func__, res->type);
160  return SR_ERR_ARG;
161  }
162 
163  p = paths;
164  while (p && !file) {
165  file = try_open_file((const char *)(p->data), NULL, name);
166  p = p->next;
167  }
168  g_slist_free_full(paths, g_free);
169 
170  if (!file) {
171  sr_dbg("Failed to locate '%s'.", name);
172  return SR_ERR;
173  }
174 
175  filesize = sr_file_get_size(file);
176  if (filesize < 0) {
177  sr_err("Failed to obtain size of '%s': %s",
178  name, g_strerror(errno));
179  fclose(file);
180  return SR_ERR;
181  }
182  res->size = filesize;
183  res->handle = file;
184 
185  return SR_OK;
186 }
187 
188 static int resource_close_default(struct sr_resource *res, void *cb_data)
189 {
190  FILE *file;
191 
192  (void)cb_data;
193 
194  file = res->handle;
195  if (!file) {
196  sr_err("%s: invalid handle.", __func__);
197  return SR_ERR_ARG;
198  }
199 
200  if (fclose(file) < 0) {
201  sr_err("Failed to close file: %s", g_strerror(errno));
202  return SR_ERR;
203  }
204  res->handle = NULL;
205 
206  return SR_OK;
207 }
208 
209 static gssize resource_read_default(const struct sr_resource *res,
210  void *buf, size_t count, void *cb_data)
211 {
212  FILE *file;
213  size_t n_read;
214 
215  (void)cb_data;
216 
217  file = res->handle;
218  if (!file) {
219  sr_err("%s: invalid handle.", __func__);
220  return SR_ERR_ARG;
221  }
222  if (count > G_MAXSSIZE) {
223  sr_err("%s: count %zu too large.", __func__, count);
224  return SR_ERR_ARG;
225  }
226 
227  n_read = fread(buf, 1, count, file);
228 
229  if (n_read != count && ferror(file)) {
230  sr_err("Failed to read resource file: %s", g_strerror(errno));
231  return SR_ERR;
232  }
233  return n_read;
234 }
235 
236 /**
237  * Install resource access hooks.
238  *
239  * @param ctx libsigrok context. Must not be NULL.
240  * @param open_cb Resource open callback, or NULL to unset.
241  * @param close_cb Resource close callback, or NULL to unset.
242  * @param read_cb Resource read callback, or NULL to unset.
243  * @param cb_data User data pointer passed to callbacks.
244  *
245  * @retval SR_OK Success.
246  * @retval SR_ERR_ARG Invalid argument.
247  *
248  * @since 0.4.0
249  */
253  sr_resource_read_callback read_cb, void *cb_data)
254 {
255  if (!ctx) {
256  sr_err("%s: ctx was NULL.", __func__);
257  return SR_ERR_ARG;
258  }
259  if (open_cb && close_cb && read_cb) {
260  ctx->resource_open_cb = open_cb;
261  ctx->resource_close_cb = close_cb;
262  ctx->resource_read_cb = read_cb;
263  ctx->resource_cb_data = cb_data;
264  } else if (!open_cb && !close_cb && !read_cb) {
265  ctx->resource_open_cb = &resource_open_default;
266  ctx->resource_close_cb = &resource_close_default;
267  ctx->resource_read_cb = &resource_read_default;
268  ctx->resource_cb_data = ctx;
269  } else {
270  sr_err("%s: inconsistent callback pointers.", __func__);
271  return SR_ERR_ARG;
272  }
273  return SR_OK;
274 }
275 
276 /**
277  * Open resource.
278  *
279  * @param ctx libsigrok context. Must not be NULL.
280  * @param[out] res Resource descriptor to fill in. Must not be NULL.
281  * @param type Resource type ID.
282  * @param name Name of the resource. Must not be NULL.
283  *
284  * @retval SR_OK Success.
285  * @retval SR_ERR_ARG Invalid argument.
286  * @retval SR_ERR Other error.
287  *
288  * @private
289  */
290 SR_PRIV int sr_resource_open(struct sr_context *ctx,
291  struct sr_resource *res, int type, const char *name)
292 {
293  int ret;
294 
295  res->size = 0;
296  res->handle = NULL;
297  res->type = type;
298 
299  ret = (*ctx->resource_open_cb)(res, name, ctx->resource_cb_data);
300 
301  if (ret != SR_OK)
302  sr_err("Failed to open resource '%s' (use loglevel 5/spew for"
303  " details).", name);
304 
305  return ret;
306 }
307 
308 /**
309  * Close resource.
310  *
311  * @param ctx libsigrok context. Must not be NULL.
312  * @param[inout] res Resource descriptor. Must not be NULL.
313  *
314  * @retval SR_OK Success.
315  * @retval SR_ERR_ARG Invalid argument.
316  * @retval SR_ERR Other error.
317  *
318  * @private
319  */
320 SR_PRIV int sr_resource_close(struct sr_context *ctx, struct sr_resource *res)
321 {
322  int ret;
323 
324  ret = (*ctx->resource_close_cb)(res, ctx->resource_cb_data);
325 
326  if (ret != SR_OK)
327  sr_err("Failed to close resource.");
328 
329  return ret;
330 }
331 
332 /**
333  * Read resource data.
334  *
335  * @param ctx libsigrok context. Must not be NULL.
336  * @param[in] res Resource descriptor. Must not be NULL.
337  * @param[out] buf Buffer to store @a count bytes into. Must not be NULL.
338  * @param count Number of bytes to read.
339  *
340  * @return The number of bytes actually read, or a negative value on error.
341  * @retval SR_ERR_ARG Invalid argument.
342  * @retval SR_ERR Other error.
343  *
344  * @private
345  */
346 SR_PRIV gssize sr_resource_read(struct sr_context *ctx,
347  const struct sr_resource *res, void *buf, size_t count)
348 {
349  gssize n_read;
350 
351  n_read = (*ctx->resource_read_cb)(res, buf, count,
352  ctx->resource_cb_data);
353  if (n_read < 0)
354  sr_err("Failed to read resource.");
355 
356  return n_read;
357 }
358 
359 /**
360  * Load a resource into memory.
361  *
362  * @param ctx libsigrok context. Must not be NULL.
363  * @param type Resource type ID.
364  * @param name Name of the resource. Must not be NULL.
365  * @param[out] size Size in bytes of the returned buffer. Must not be NULL.
366  * @param max_size Size limit. Error out if the resource is larger than this.
367  *
368  * @return A buffer containing the resource data, or NULL on failure. Must
369  * be freed by the caller using g_free().
370  *
371  * @private
372  */
373 SR_PRIV void *sr_resource_load(struct sr_context *ctx,
374  int type, const char *name, size_t *size, size_t max_size)
375 {
376  struct sr_resource res;
377  void *buf;
378  size_t res_size;
379  gssize n_read;
380 
381  if (sr_resource_open(ctx, &res, type, name) != SR_OK)
382  return NULL;
383 
384  if (res.size > max_size) {
385  sr_err("Size %" PRIu64 " of '%s' exceeds limit %zu.",
386  res.size, name, max_size);
387  sr_resource_close(ctx, &res);
388  return NULL;
389  }
390  res_size = res.size;
391 
392  buf = g_try_malloc(res_size);
393  if (!buf) {
394  sr_err("Failed to allocate buffer for '%s'.", name);
395  sr_resource_close(ctx, &res);
396  return NULL;
397  }
398 
399  n_read = sr_resource_read(ctx, &res, buf, res_size);
400  sr_resource_close(ctx, &res);
401 
402  if (n_read < 0 || (size_t)n_read != res_size) {
403  if (n_read >= 0)
404  sr_err("Failed to read '%s': premature end of file.",
405  name);
406  g_free(buf);
407  return NULL;
408  }
409 
410  *size = res_size;
411  return buf;
412 }
413 
414 /** @} */
void * handle
File handle or equivalent; set by resource open callback.
Definition: libsigrok.h:569
Generic/unspecified error.
Definition: libsigrok.h:68
uint64_t size
Size of resource in bytes; set by resource open callback.
Definition: libsigrok.h:567
const char * name
Definition: libsigrok.h:546
gssize(* sr_resource_read_callback)(const struct sr_resource *res, void *buf, size_t count, void *cb_data)
Definition: proto.h:235
No error.
Definition: libsigrok.h:67
The public libsigrok header file to be used by frontends.
int type
Resource type (SR_RESOURCE_FIRMWARE, ...)
Definition: libsigrok.h:571
int(* sr_resource_open_callback)(struct sr_resource *res, const char *name, void *cb_data)
Definition: proto.h:231
GSList * sr_resourcepaths_get(int res_type)
Get a list of paths where we look for resource (e.g.
Definition: resource.c:47
Resource descriptor.
Definition: libsigrok.h:565
#define SR_PRIV
Definition: libsigrok.h:128
int sr_resource_set_hooks(struct sr_context *ctx, sr_resource_open_callback open_cb, sr_resource_close_callback close_cb, sr_resource_read_callback read_cb, void *cb_data)
Install resource access hooks.
Definition: resource.c:250
int(* sr_resource_close_callback)(struct sr_resource *res, void *cb_data)
Definition: proto.h:233
Function argument error.
Definition: libsigrok.h:70
Opaque structure representing a libsigrok context.
#define SR_API
Definition: libsigrok.h:121