summaryrefslogtreecommitdiffstats
path: root/rtemstoolkit/rld-process.cpp
blob: 4160759f3edb63d06658000771b3424d1ed72284 (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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/*
 * Copyright (c) 2011, Chris Johns <chrisj@rtems.org>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "config.h"

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif

#ifndef WIFEXITED
#define WIFEXITED(S) (((S) & 0xff) == 0)
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
#endif
#ifndef WIFSIGNALED
#define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
#endif
#ifndef WTERMSIG
#define WTERMSIG(S) ((S) & 0x7f)
#endif
#ifndef WIFSTOPPED
#define WIFSTOPPED WIFEXITED
#endif
#ifndef WSTOPSIG
#define WSTOPSIG WEXITSTATUS
#endif

#if __WIN32__
#define CREATE_MODE (S_IRUSR | S_IWUSR)
#define OPEN_FLAGS  (O_BINARY)
#else
#define CREATE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)
#define OPEN_FLAGS  (0)
#endif

#include <iostream>

#include "rld.h"
#include "rld-process.h"

#include <libiberty.h>

namespace rld
{
  namespace process
  {
    /**
     * Global keep of temporary files if true. Used to help debug a system.
     */
    bool keep_temporary_files = false;

    /**
     * The temporary files.
     */
    temporary_files temporaries;

    temporary_files::temporary_files ()
    {
    }

    temporary_files::~temporary_files ()
    {
      try
      {
        clean_up ();
      }
      catch (...)
      {
      }
    }

    const std::string
    temporary_files::get (const std::string& suffix, bool keep)
    {
      char* temp = ::make_temp_file (suffix.c_str ());

      if (!temp)
        throw rld::error ("bad temp name", "temp-file");

      const std::string name = rld::find_replace (temp,
                                                  RLD_PATH_SEPARATOR_STR RLD_PATH_SEPARATOR_STR,
                                                  RLD_PATH_SEPARATOR_STR);
      tempfile_ref ref (name, keep);
      tempfiles.push_back (ref);

      ::free (temp);

      return name;
    }

    void
    temporary_files::unlink (const tempfile_ref& ref)
    {
      if (!keep_temporary_files && !ref.keep)
        rld::path::unlink (ref.name);
    }

    void
    temporary_files::erase (const std::string& name)
    {
      for (tempfile_container::iterator tfi = tempfiles.begin ();
           tfi != tempfiles.end ();
           ++tfi)
      {
        if ((*tfi).name == name)
        {
          unlink (*tfi);
          tempfiles.erase (tfi);
          break;
        }
      }
    }

    void
    temporary_files::keep (const std::string& name)
    {
      for (tempfile_container::iterator tfi = tempfiles.begin ();
           tfi != tempfiles.end ();
           ++tfi)
      {
        if ((*tfi).name == name)
        {
          (*tfi).keep = true;
          break;
        }
      }
    }

    void
    temporary_files::clean_up ()
    {
      for (tempfile_container::iterator tfi = tempfiles.begin ();
           tfi != tempfiles.end ();
           ++tfi)
      {
        unlink (*tfi);
      }
    }

    tempfile::tempfile (const std::string& suffix, bool _keep)
      : suffix (suffix),
        overridden (false),
        fd (-1),
        level (0)
    {
      _name = temporaries.get (suffix, _keep);
    }

    tempfile::tempfile (const std::string& name,
                        const std::string& suffix,
                        bool               _keep)
      : _name(name + suffix),
        suffix(suffix),
        overridden (false),
        fd (-1),
        level (0)
    {
    }

    tempfile::~tempfile ()
    {
      try
      {
        close ();
        temporaries.erase (_name);
      }
      catch (...)
      {
      }
    }

    void
    tempfile::open (bool writable)
    {
      if (fd < 0)
      {
        bool ok = rld::path::check_file (_name);
        int  flags = writable ? O_RDWR : O_RDONLY;
        int  mode = writable ? CREATE_MODE : 0;

        if (writable && overridden)
        {
          flags |= O_CREAT | O_TRUNC | O_APPEND;
        }
        else
        {
          if (!ok)
            throw rld::error ("Not found.", "tempfile open:" + _name);
        }

        level = 0;
        fd = ::open (_name.c_str (), flags, mode);
        if (fd < 0)
          throw rld::error (::strerror (errno), "tempfile open:" + _name);
      }
    }

    void
    tempfile::close ()
    {
      if (fd != -1)
      {
        ::close (fd);
        fd = -1;
        level = 0;
      }
    }

    void
    tempfile::override (const std::string& name_)
    {
      if (fd >= 0)
        throw rld::error ("Already open", "tempfile override");
      rld::path::unlink (_name);
      overridden = true;
      _name = name_ + suffix;
    }

    void
    tempfile::keep ()
    {
      temporaries.keep (_name);
    }

    const std::string&
    tempfile::name () const
    {
      return _name;
    }

    size_t
    tempfile::size ()
    {
      if (fd < 0)
        return 0;

      struct stat sb;
      if (::stat (_name.c_str (), &sb) == 0)
        return sb.st_size;

      return 0;
    }

    void
    tempfile::read (std::string& all)
    {
      all.clear ();
      if (fd != -1)
      {
        if (level)
          all.append (buf, level);
        level = 0;
        while (true)
        {
          int read = ::read (fd, buf, sizeof (buf) );
          if (read < 0)
            throw rld::error (::strerror (errno), "tempfile get read:" + _name);
          else if (read == 0)
            break;
          else
            all.append (buf, read);
        }
      }
    }

    void
    tempfile::read_line (std::string& line)
    {
      line.clear ();
      if (fd != -1)
      {
        bool reading = true;
        while (reading)
        {
          if (level < (sizeof (buf) - 1))
          {
            ::memset (buf + level, 0, sizeof (buf) - level);
            int read = ::read (fd, buf + level, sizeof (buf) - level - 1);
            if (read < 0)
              throw rld::error (::strerror (errno), "tempfile read:" + _name);
            else if (read == 0)
              reading = false;
            else
              level += read;
          }
          if (level)
          {
            char* lf = ::strchr (buf, '\n');
            int   len = level;
            if (lf)
            {
              len = lf - &buf[0] + 1;
              reading = false;
            }
            line.append (buf, len);
            level -= len;
            if (level)
              ::memmove (buf, &buf[len], level + 1);
          }
        }
      }
    }

    void
    tempfile::write (const std::string& s)
    {
      const char* p = s.c_str ();
      size_t      l = s.length ();
      while (l)
      {
        int written = ::write (fd, p, l);
        if (written < 0)
            throw rld::error (::strerror (errno), "tempfile write:" + _name);
        if (written == 0)
          break;
        l -= written;
      }
    }

    void
    tempfile::write_line (const std::string& s)
    {
      write (s);
      write (RLD_LINE_SEPARATOR);
    }

    void
    tempfile::write_lines (const rld::strings& ss)
    {
      for (rld::strings::const_iterator ssi = ss.begin ();
           ssi != ss.end ();
           ++ssi)
      {
        write_line (*ssi);
      }
    }

    void
    tempfile::output (std::ostream& out)
    {
      std::string prefix;
      output (prefix, out);
    }

    void
    tempfile::output (const std::string& prefix,
                      std::ostream&      out,
                      bool               line_numbers)
    {
      if (fd == -1)
      {
        std::string line;
        int         lc = 0;
        open ();
        while (true)
        {
          read_line (line);
          ++lc;
          if (line.empty () && (level == 0))
            break;
          if (!prefix.empty ())
            out << prefix << ": ";
          if (line_numbers)
            out << lc << ": ";
          out << line << std::flush;
        }
        close ();
      }
    }

    void
    set_keep_temporary_files ()
    {
      keep_temporary_files = true;
    }

    void
    temporaries_clean_up ()
    {
      temporaries.clean_up ();
    }

    void
    args_append (arg_container& args, const std::string& str)
    {
      rld::strings ss;
      rld::split (ss, str);
      for (rld::strings::iterator ssi = ss.begin ();
           ssi != ss.end ();
           ++ssi)
      {
        args.push_back (*ssi);
      }
    }

    status
    execute (const std::string& pname,
             const std::string& command,
             const std::string& outname,
             const std::string& errname)
    {
      arg_container args;
      parse_command_line (command, args);
      return execute (pname, args, outname, errname);
    }

    status
    execute (const std::string&   pname,
             const arg_container& args,
             const std::string&   outname,
             const std::string&   errname)
    {
      if (rld::verbose (RLD_VERBOSE_TRACE))
      {
        std::cout << "execute: ";
        for (size_t a = 0; a < args.size (); ++a)
          std::cout << args[a] << ' ';
        std::cout << std::endl;
      }

      const char** cargs = new const char* [args.size () + 1];

      for (size_t a = 0; a < args.size (); ++a)
        cargs[a] = args[a].c_str ();
      cargs[args.size ()] = 0;

      int err = 0;
      int s = 0;

      const char* serr = pex_one (PEX_LAST | PEX_SEARCH,
                                  args[0].c_str (),
                                  (char* const*) cargs,
                                  pname.c_str (),
                                  outname.c_str (),
                                  errname.c_str (),
                                  &s,
                                  &err);

      delete [] cargs;

      if (serr)
        throw rld::error ("execute: " + args[0], serr);
      else if (err)
        throw rld::error ("execute: " + args[0], ::strerror (err));

      status _status;

      if (rld::verbose (RLD_VERBOSE_TRACE))
        std::cout << "execute: status: ";

      if (WIFEXITED (s))
      {
        _status.type = status::normal;
        _status.code = WEXITSTATUS (s);
        if (rld::verbose (RLD_VERBOSE_TRACE))
          std::cout << _status.code << std::endl;
      }
      else if (WIFSIGNALED (s))
      {
        _status.type = status::signal;
        _status.code = WTERMSIG (s);
        if (rld::verbose (RLD_VERBOSE_TRACE))
          std::cout << "signal: " << _status.code << std::endl;
      }
      else if (WIFSTOPPED (s))
      {
        _status.type = status::stopped;
        _status.code = WSTOPSIG (s);
        if (rld::verbose (RLD_VERBOSE_TRACE))
          std::cout << "stopped: " << _status.code << std::endl;
      }
      else
        throw rld::error ("execute: " + args[0], "unknown status returned");

      return _status;
    }

    /*
     * The code is based on this C file:
     *  http://cybertiggyr.com/pcm/src/parse.c
     */
    void
    parse_command_line (const std::string& command, arg_container& args)
    {
      enum pstate
      {
        pstate_discard_space,
        pstate_accumulate_quoted,
        pstate_accumulate_raw
      };

      args.clear ();

      const char quote = '"';
      const char escape = '\\';
      pstate     state = pstate_discard_space;
      size_t     start = 0;
      size_t     i = 0;

      while (i < command.size ())
      {
        switch (state)
        {
          case pstate_discard_space:
            if (command[i] == quote)
            {
              ++i;
              start = i;
              state = pstate_accumulate_quoted;
            }
            else if (::isspace (command[i]))
            {
              ++i;
            }
            else /* includes escape */
            {
              start = i;
              state = pstate_accumulate_raw;
            }
            break;

          case pstate_accumulate_quoted:
            if (command[i] == quote)
            {
              args.push_back (command.substr (start, i - 1));
              ++i;
              state = pstate_discard_space;
            }
            else if ((command[i] == escape) && (command[i + 1] == quote))
            {
              i += 2;
            }
            else /* includes space */
            {
              ++i;
            }
            break;

          case pstate_accumulate_raw:
            if (command[i] == quote)
            {
              throw rld::error ("quote in token", "command parse");
            }
            else if ((command[i] == escape) && (command[i + 1] == quote))
            {
              i += 2;
            }
            else if (::isspace (command[i]))
            {
              args.push_back (command.substr (start, i - 1));
              ++i;
              state = pstate_discard_space;
            }
            else
            {
              ++i;
            }
            break;
        }
      }
    }
  }
}