There were several memory leaks inside jfsck(), they've probably been there for a...
[libjio.git] / common.c
blob01119efd3ec5eab7844a55451f4d7bf2f1e9793b
2 /*
3 * libjio - A library for Journaled I/O
4 * Alberto Bertogli (albertogli@telpin.com.ar)
6 * Common functions
7 */
9 #include <sys/types.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <string.h>
13 #include <libgen.h>
14 #include <limits.h>
15 #include <stdio.h>
16 #include <stdlib.h>
18 #include "common.h"
21 /* like lockf, but lock always from the beginning of the file */
22 off_t plockf(int fd, int cmd, off_t offset, off_t len)
24 struct flock fl;
25 int op;
27 op = -1;
28 fl.l_type = -1;
30 if (cmd & _F_READ) {
31 fl.l_type = F_RDLCK;
32 } else if (cmd & _F_WRITE) {
33 fl.l_type = F_WRLCK;
36 if (cmd & _F_LOCK) {
37 op = F_SETLKW;
38 } else if (cmd & _F_TLOCK) {
39 op = F_SETLK;
40 } else if (cmd & F_UNLOCK) {
41 fl.l_type = F_UNLCK;
42 op = F_SETLKW; /* not very relevant */
45 fl.l_whence = SEEK_SET;
46 fl.l_start = offset;
47 fl.l_len = len;
49 return fcntl(fd, op, &fl);
52 /* like pread but either fails, or return a complete read; if we return less
53 * than count is because EOF was reached */
54 ssize_t spread(int fd, void *buf, size_t count, off_t offset)
56 int rv, c;
58 c = 0;
60 while (c < count) {
61 rv = pread(fd, (char *) buf + c, count - c, offset + c);
63 if (rv == count)
64 /* we're done */
65 return count;
66 else if (rv < 0)
67 /* error */
68 return rv;
69 else if (rv == 0)
70 /* got EOF */
71 return c;
73 /* incomplete read, keep on reading */
74 c += rv;
77 return count;
80 /* like spread() but for pwrite() */
81 ssize_t spwrite(int fd, const void *buf, size_t count, off_t offset)
83 int rv, c;
85 c = 0;
87 while (c < count) {
88 rv = pwrite(fd, (char *) buf + c, count - c, offset + c);
90 if (rv == count)
91 /* we're done */
92 return count;
93 else if (rv <= 0)
94 /* error/nothing was written */
95 return rv;
97 /* incomplete write, keep on writing */
98 c += rv;
101 return count;
104 /* build the journal directory name out of the filename */
105 int get_jdir(const char *filename, char *jdir)
107 char *base, *baset;
108 char *dir, *dirt;
110 baset = strdup(filename);
111 if (baset == NULL)
112 return 0;
113 base = basename(baset);
115 dirt = strdup(filename);
116 if (dirt == NULL)
117 return 0;
118 dir = dirname(dirt);
120 snprintf(jdir, PATH_MAX, "%s/.%s.jio", dir, base);
122 free(baset);
123 free(dirt);
125 return 1;
128 /* build the filename of a given transaction */
129 int get_jtfile(const char *filename, int tid, char *jtfile)
131 char *base, *baset;
132 char *dir, *dirt;
134 baset = strdup(filename);
135 if (baset == NULL)
136 return 0;
137 base = basename(baset);
139 dirt = strdup(filename);
140 if (dirt == NULL)
141 return 0;
142 dir = dirname(dirt);
144 snprintf(jtfile, PATH_MAX, "%s/.%s.jio/%d", dir, base, tid);
146 free(baset);
147 free(dirt);
149 return 1;