summaryrefslogtreecommitdiff
path: root/nuttx/binfmt/pcode.c
blob: b2cac58806545be9afa7758d6e362de669c713f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/****************************************************************************
 * binfmt/pcode.c
 *
 *   Copyright (C) 2014 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <sys/mount.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <debug.h>

#include <apps/prun.h>

#include <nuttx/kmalloc.h>
#include <nuttx/poff.h>
#include <nuttx/fs/ramdisk.h>
#include <nuttx/binfmt/binfmt.h>
#include <nuttx/binfmt/pcode.h>

#ifdef CONFIG_PCODE

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
/* Check configuration.  This is not all of the configuration settings that
 * are required -- only the more obvious.
 */

#if CONFIG_NFILE_DESCRIPTORS < 1
#  error You must provide file descriptors via CONFIG_NFILE_DESCRIPTORS in your configuration file
#endif

#ifdef CONFIG_BINFMT_DISABLE
#  error The binary loader is disabled (CONFIG_BINFMT_DISABLE)!
#endif

#ifndef CONFIG_PCODE
#  error You must select CONFIG_PCODE in your configuration file
#endif

#ifndef CONFIG_SCHED_ONEXIT
#  error CONFIG_SCHED_ONEXIT is required
#endif

#ifndef CONFIG_PCODE_VARSTACKSIZE
# define CONFIG_PCODE_VARSTACKSIZE 1024
#endif

#ifndef CONFIG_PCODE_STRSTACKSIZE
# define CONFIG_PCODE_STRSTACKSIZE 128
#endif

#ifdef CONFIG_PCODE_TEST_FS
#  ifndef CONFIG_FS_ROMFS
#    error You must select CONFIG_FS_ROMFS in your configuration file
#  endif

#  ifdef CONFIG_DISABLE_MOUNTPOINT
#    error You must not disable mountpoints via CONFIG_DISABLE_MOUNTPOINT in your configuration file
#  endif

#  ifndef CONFIG_PCODE_TEST_DEVMINOR
#    define CONFIG_PCODE_TEST_DEVMINOR 0
#  endif

#  ifndef CONFIG_PCODE_TEST_DEVPATH
#    define CONFIG_PCODE_TEST_DEVPATH "/dev/ram0"
#  endif

#  ifndef CONFIG_PCODE_TEST_MOUNTPOINT
#    define CONFIG_PCODE_TEST_MOUNTPOINT "/bin"
#  endif
#endif

/* Describe the ROMFS file system */

#define SECTORSIZE   512
#define NSECTORS(b)  (((b)+SECTORSIZE-1)/SECTORSIZE)

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

struct binfmt_handoff_s
{
  sem_t exclsem;              /* Supports mutually exclusive access */
  FAR struct binary_s *binp;  /* Binary format being handed off */
  FAR char *fullpath;         /* Full path to the P-Code file */
};

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

static int pcode_load(FAR struct binary_s *binp);
static int pcode_unload(FAR struct binary_s *binp);

/****************************************************************************
 * Private Data
 ****************************************************************************/

static struct binfmt_s g_pcode_binfmt =
{
  NULL,          /* next */
  pcode_load,    /* load */
  pcode_unload,  /* unload */
};

struct binfmt_handoff_s g_pcode_handoff;

#ifdef CONFIG_PCODE_TEST_FS
#  include "romfs.h"
#endif

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: pcode_mount_testfs
 *
 * Description:
 *   If so configured, then mount the P-Code test file system
 *
 ****************************************************************************/

#ifdef CONFIG_PCODE_TEST_FS
static int pcode_mount_testfs(void)
{
  int ret;

  /* Create a ROM disk for the ROMFS filesystem */

  bvdbg("Registering romdisk at /dev/ram%d\n", CONFIG_PCODE_TEST_DEVMINOR);
  ret = romdisk_register(CONFIG_PCODE_TEST_DEVMINOR, (FAR uint8_t *)romfs_img,
                         NSECTORS(ROMFS_IMG_LEN), SECTORSIZE);
  if (ret < 0)
    {
      bdbg("ERROR: romdisk_register failed: %d\n", ret);
      return ret;
    }

  /* Mount the test file system */

  bvdbg("Mounting ROMFS filesystem at target=%s with source=%s\n",
         CONFIG_PCODE_TEST_MOUNTPOINT, CONFIG_PCODE_TEST_DEVPATH);

  ret = mount(CONFIG_PCODE_TEST_DEVPATH, CONFIG_PCODE_TEST_MOUNTPOINT,
              "romfs", MS_RDONLY, NULL);
  if (ret < 0)
    {
      int errval = get_errno();
      DEBUGASSERT(errval > 0);

      bdbg("ERROR: mount(%s,%s,romfs) failed: %d\n",
           CONFIG_PCODE_TEST_DEVPATH, CONFIG_PCODE_TEST_MOUNTPOINT, errval);
      return -errval;
    }

  /* Does the system support the PATH variable?  Has the PATH variable
   * already been set?  If YES and NO, then set the PATH variable to
   * the ROMFS mountpoint.
   */

#if defined(CONFIG_BINFMT_EXEPATH) && !defined(CONFIG_PATH_INITIAL)
  (void)setenv("PATH", CONFIG_PCODE_TEST_MOUNTPOINT, 1);
#endif

  return OK;
}
#else
#  define pcode_mount_testfs() (OK)
#endif

/****************************************************************************
 * Name: pcode_onexit
 *
 * Description:
 *   This is the proxy program that runs and starts the P-Code interpreter.
 *
 ****************************************************************************/

#if !defined(CONFIG_BUILD_PROTECTED) && !defined(CONFIG_BUILD_KERNEL)
static void pcode_onexit(int exitcode, FAR void *arg)
{
  FAR struct binary_s *binp = (FAR struct binary_s *)arg;
  DEBUGASSERT(binp);

  /* And unload the module */

  unload_module(binp);
}
#endif

/****************************************************************************
 * Name: pcode_proxy
 *
 * Description:
 *   This is the proxy program that runs and starts the P-Code interpreter.
 *
 * REVISIT:  There are issues here when CONFIG_BUILD_PROTECTED or
 * CONFIG_BUILD_KERNEL are selected.  Also this implementation is too highly
 * couple to logic in the apps/ directory.
 *
 ****************************************************************************/

#if !defined(CONFIG_BUILD_PROTECTED) && !defined(CONFIG_BUILD_KERNEL)
static int pcode_proxy(int argc, char **argv)
{
  FAR struct binary_s *binp;
  FAR char *fullpath;
  int ret;

  /* Get the struct binary_s instance from the handoff structure */

  binp                     = g_pcode_handoff.binp;
  g_pcode_handoff.binp     = NULL;
  fullpath                 = g_pcode_handoff.fullpath;
  g_pcode_handoff.fullpath = NULL;

  sem_post(&g_pcode_handoff.exclsem);
  DEBUGASSERT(binp && fullpath);

  bvdbg("Executing %s\n", fullpath);

  /* Set-up the on-exit handler that will unload the module on exit */

  ret = on_exit(pcode_onexit, binp);
  if (ret < 0)
    {
      bdbg("ERROR: on_exit failed: %d\n", get_errno());
      kmm_free(fullpath);
      return EXIT_FAILURE;
    }

  /* Load the P-code file and execute it */

  ret = prun(fullpath, CONFIG_PCODE_VARSTACKSIZE, CONFIG_PCODE_STRSTACKSIZE);

  /* We no longer need the fullpath */

  kmm_free(fullpath);

  /* Check the result of the interpretation */

  if (ret < 0)
    {
      bdbg("ERROR: Execution failed\n");
      return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
#else
#  error Missing logic for the case of CONFIG_BUILD_PROTECTED/KERNEL
#endif

/****************************************************************************
 * Name: pcode_load
 *
 * Description:
 *   Verify that the file is a pcode binary.
 *
 ****************************************************************************/

static int pcode_load(struct binary_s *binp)
{
  FAR struct poff_fileheader_s hdr;
  FAR uint8_t *ptr;
  size_t remaining;
  ssize_t nread;
  int fd;
  int ret;

  bvdbg("Loading file: %s\n", binp->filename);

  /* Open the binary file for reading (only) */

  fd = open(binp->filename, O_RDONLY);
  if (fd < 0)
    {
      int errval = get_errno();
      bdbg("ERROR: Failed to open binary %s: %d\n", binp->filename, errval);
      return -errval;
    }

  /* Read the POFF file header */

  for (remaining = sizeof(struct poff_fileheader_s), ptr = (FAR uint8_t *)&hdr;
       remaining > 0; )
    {
      /* Read the next GULP */

      nread = read(fd, ptr, remaining);
      if (nread < 0)
        {
          /* If errno is EINTR, then this is not an error; the read() was
           * simply interrupted by a signal.
           */

          int errval = get_errno();
          DEBUGASSERT(errval > 0);

          if (errval != EINTR)
            {
              bdbg("ERROR: read failed: %d\n", errval);
              ret = -errval;
              goto errout_with_fd;
            }

          bdbg("Interrupted by a signal\n");
        }
      else
        {
          /* Set up for the next gulp */

          DEBUGASSERT(nread > 0 && nread <=remaining);
          remaining -= nread;
          ptr += nread;
        }
    }

#ifdef CONFIG_PCODE_DUMPBUFFER
  lib_dumpbuffer("POFF File Header", &hdr, sizeof(poff_fileheader_s));
#endif

  /* Verify that the file is a P-Code executable */

  if (memcmp(&hdr.fh_ident, FHI_POFF_MAG, 4) != 0 || hdr.fh_type != FHT_EXEC)
    {
      dbg("ERROR: File is not a P-code executable: %d\n");
      ret = -ENOEXEC;
      goto errout_with_fd;
    }

  /* Return the load information.
   * REVISIT:  There are issues here when CONFIG_BUILD_PROTECTED or
   * CONFIG_BUILD_KERNEL are selected.
   */

  binp->entrypt   = pcode_proxy;
  binp->stacksize = CONFIG_PCODE_STACKSIZE;
  binp->priority  = CONFIG_PCODE_PRIORITY;

  /* Get exclusive access to the p-code handoff structure */

  do
    {
      ret = sem_wait(&g_pcode_handoff.exclsem);
      DEBUGASSERT(ret == OK || get_errno() == EINTR);
    }
  while (ret < 0);

  /* Save the data that we need to handoff to the child thread */

  DEBUGASSERT(g_pcode_handoff.binp == NULL &&
              g_pcode_handoff.fullpath == NULL);

  /* Duplicate the full path to the binary */

  g_pcode_handoff.fullpath = strdup(binp->filename);
  if (!g_pcode_handoff.fullpath)
    {
      bdbg("ERROR: Failed to duplicate the full path: %d\n",
           binp->filename);

      sem_post(&g_pcode_handoff.exclsem);
      ret = -ENOMEM;
      goto errout_with_fd;
    }

  g_pcode_handoff.binp = binp;

  /* Successfully identified (but not really loaded) a p-code binary */

  ret = OK;

errout_with_fd:
  close(fd);
  return ret;
}

/****************************************************************************
 * Name: pcode_unload
 *
 * Description:
 *   Called when the pcode binary is unloaded.  This is necessary primarily
 *   to handler error conditions where unload_module is called after
 *   pcode_load without having executed the P-Code module.
 *
 ****************************************************************************/

static int pcode_unload(struct binary_s *binp)
{
  /* Increment the semaphore count back to one if appropriate */

  if (g_pcode_handoff.binp)
    {
      g_pcode_handoff.binp = NULL;
      sem_post(&g_pcode_handoff.exclsem);
    }

  return OK;
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: pcode_initialize
 *
 * Description:
 *   P-code support is built based on the configuration.  However, in order
 *   to use this binary format, this function must be called during system
 *   initialization in order to register the P-Code binary format.
 *
 * Returned Value:
 *   This is a NuttX internal function so it follows the convention that
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int pcode_initialize(void)
{
  int ret;

  /* Initialize globals */

  sem_init(&g_pcode_handoff.exclsem, 0, 1);

  /* Mount the test file system */

  ret = pcode_mount_testfs();
  if (ret < 0)
    {
      bdbg("ERROR: Failed to mount test file system: %d\n", ret);
      return ret;
    }

  /* Register ourselves as a binfmt loader */

  bvdbg("Registering P-Code Loader\n");

  ret = register_binfmt(&g_pcode_binfmt);
  if (ret != 0)
    {
      bdbg("Failed to register binfmt: %d\n", ret);
    }

  return ret;
}

/****************************************************************************
 * Name: pcode_uninitialize
 *
 * Description:
 *   Unregister the pcode binary loader
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

void pcode_uninitialize(void)
{
  int ret;

  /* Unregister the binary format */

  ret = unregister_binfmt(&g_pcode_binfmt);
  if (ret < 0)
    {
      int errval = get_errno();
      DEBUGASSERT(errval > 0);

      bdbg("ERROR: unregister_binfmt() failed: %d\n", errval);
      UNUSED(errval);
    }

#ifdef CONFIG_PCODE_TEST_FS
  ret = umount(CONFIG_PCODE_TEST_MOUNTPOINT);
  if (ret < 0)
    {
      int errval = get_errno();
      DEBUGASSERT(errval > 0);

      bdbg("ERROR: umount(%s) failed: %d\n", CONFIG_PCODE_TEST_MOUNTPOINT, errval);
      UNUSED(errval);
    }
#endif

  /* Uninitialize globals */

  sem_destroy(&g_pcode_handoff.exclsem);
}

#endif /* CONFIG_PCODE */