Rizin
unix-like reverse engineering framework and cli tools
cpipe.c
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: 2009-2020 pancake <pancake@nopcode.org>
2 // SPDX-License-Identifier: LGPL-3.0-only
3 
4 #include <rz_cons.h>
5 #include <limits.h>
6 
7 // TODO: remove globals, and make this stackable
8 // cons_pipe should be using a stack pipe_push, pipe_pop
9 static int backup_fd = -1;
10 static int backup_fdn = 1;
11 
12 #ifndef O_BINARY
13 #define O_BINARY 0
14 #endif
15 
16 static bool __dupDescriptor(int fd, int fdn) {
17 #if __WINDOWS__
18  backup_fd = 2002 - (fd - 2); // windows xp has 2048 as limit fd
19  return _dup2(fdn, backup_fd) != -1;
20 #else
21  backup_fd = sysconf(_SC_OPEN_MAX) - (fd - 2); // portable getdtablesize()
22  if (backup_fd < 2) {
23  backup_fd = 2002 - (fd - 2); // fallback
24  }
25  return dup2(fdn, backup_fd) != -1;
26 #endif
27 }
28 
29 RZ_API int rz_cons_pipe_open(const char *file, int fdn, int append) {
30  if (fdn < 1) {
31  return -1;
32  }
33  const int fd_flags = O_BINARY | O_RDWR | O_CREAT | (append ? O_APPEND : O_TRUNC);
34  int fd = rz_sys_open(file, fd_flags, 0644);
35  if (fd == -1) {
36  eprintf("rz_cons_pipe_open: Cannot open file '%s'\n", file);
37  return -1;
38  }
39  if (backup_fd != -1) {
41  // already set in __dupDescriptor // backup_fd = -1;
42  }
43  backup_fdn = fdn;
44  if (!__dupDescriptor(fd, fdn)) {
45  eprintf("Cannot dup stdout to %d\n", fdn);
46  return -1;
47  }
48  close(fdn);
49  dup2(fd, fdn);
50  return fd;
51 }
52 
54  if (fd != -1) {
55  close(fd);
56  if (backup_fd != -1) {
59  backup_fd = -1;
60  }
61  }
62 }
#define append(x, y)
Definition: cmd_print.c:1740
RZ_API void rz_cons_pipe_close(int fd)
Definition: cpipe.c:53
#define O_BINARY
Definition: cpipe.c:13
static int backup_fd
Definition: cpipe.c:9
RZ_API int rz_cons_pipe_open(const char *file, int fdn, int append)
Definition: cpipe.c:29
static int backup_fdn
Definition: cpipe.c:10
static bool __dupDescriptor(int fd, int fdn)
Definition: cpipe.c:16
#define RZ_API
static static fork const void static count close
Definition: sflib.h:33
static static fork const void static count static fd const char static mode const char static pathname const char static path const char static dev const char static group static getpid static getuid void void static data static pause const char static mode static sync const char const char static newpath const char static pathname unsigned long static filedes void static end_data_segment static handler static getegid char static len static pgid const char static path dup2
Definition: sflib.h:94
#define eprintf(x, y...)
Definition: rlcc.c:7
RZ_API int rz_sys_open(const char *path, int perm, int mode)
Definition: sys.c:1740
#define O_CREAT
Definition: sftypes.h:489
#define O_RDWR
Definition: sftypes.h:488
#define O_TRUNC
Definition: sftypes.h:492
#define O_APPEND
Definition: sftypes.h:493
Definition: gzappend.c:170
static const z80_opcode fd[]
Definition: z80_tab.h:997