-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfd_mgmt.cpp
More file actions
111 lines (87 loc) · 2.07 KB
/
Copy pathfd_mgmt.cpp
File metadata and controls
111 lines (87 loc) · 2.07 KB
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
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include "fd_mgmt.hpp"
enum fstat {
FSTAT_EMPTY,
FSTAT_USED,
FSTAT_CLOSED,
FSTAT_NUM
};
struct fd_entry {
time_t access_time;
enum fstat fstat;
pthread_mutex_t lock;
};
#define MAX_NR_OPEN_FILES 2048
extern int loglevel;
extern FILE *debugfp;
static inline void debug_log(const char *action, int fd)
{
if (loglevel > 0 ) {
char name[17] = "";
prctl(PR_GET_NAME, name);
fprintf(debugfp, "[pid %d %s] %s %s (%d)\n", getpid(), name, __FUNCTION__, action, fd);
}
}
struct fd_entry fd_entry[MAX_NR_OPEN_FILES];
void mgmt_create_fd(int fd)
{
struct fd_entry *fde = &fd_entry[fd];
pthread_mutex_lock(&fde->lock);
debug_log("create", fd);
fde->fstat = FSTAT_USED;
fde->access_time = time(NULL);
pthread_mutex_unlock(&fde->lock);
}
void mgmt_close_fd(int fd)
{
struct fd_entry *fde = &fd_entry[fd];
pthread_mutex_lock(&fde->lock);
debug_log("close", fd);
if (fde->fstat != FSTAT_USED) {
fprintf(debugfp, "[pid %d] fd %d is in %d stated\n",
getpid(), fd, fde->fstat);
//abort();
}
fde->fstat = FSTAT_CLOSED;
pthread_mutex_unlock(&fde->lock);
}
void mgmt_access_fd(int fd)
{
struct fd_entry *fde = &fd_entry[fd];
pthread_mutex_lock(&fde->lock);
debug_log("access", fd);
if (fde->fstat != FSTAT_USED) {
fprintf(debugfp, "[pid %d] fd %d is in %d state(not used)\n",
getpid(), fd, fde->fstat);
//abort();
}
fde->access_time = time(NULL);
pthread_mutex_unlock(&fde->lock);
}
static void init_all_fds() __attribute__((constructor(200)));
static void init_all_fds()
{
int i;
struct fd_entry *fde;
struct stat buf;
for (i = 0, fde = &fd_entry[0]; i < MAX_NR_OPEN_FILES; ++i, ++fde) {
/*
* test whether this @i fd is opend before.
* such as opend by ld, or aready opened before execve
*/
if (fstat(i, &buf) == -1 && errno == EBADF) {
fde->fstat = FSTAT_EMPTY;
} else {
fde->fstat = FSTAT_USED;
debug_log("In Used", i);
}
pthread_mutex_init(&fde->lock, NULL);
fde->access_time = 0;
}
}