summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorAndrey Smirnov <andrew.smirnov@gmail.com>2019-03-06 23:49:10 -0800
committerSascha Hauer <s.hauer@pengutronix.de>2019-03-11 07:55:45 +0100
commit05374a6eded63894263a27886ef19056362967be (patch)
treede9a4ce6cda172d9c91cd9092ad2b61b3feda739 /lib
parent369d39adfe79334db5ed04d6f2acaf096c68b8a2 (diff)
downloadbarebox-05374a6eded63894263a27886ef19056362967be.tar.gz
barebox-05374a6eded63894263a27886ef19056362967be.tar.xz
libfile: Make failure path of open_and_lseek() consistent
Change the code of open_and_lseek() to make sure that opened file is closed in every failure path as well. While at it make sure we don't mix returning function return code and returning errno by opting to always return the former. Signed-off-by: Andrey Smirnov <andrew.smirnov@gmail.com> Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
Diffstat (limited to 'lib')
-rw-r--r--lib/libfile.c26
1 files changed, 12 insertions, 14 deletions
diff --git a/lib/libfile.c b/lib/libfile.c
index 9a223d2328..089749253d 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -522,12 +522,12 @@ err_out1:
* @mode: The file open mode
* @pos: The position to lseek to
*
- * Return: If successful this function returns a positive filedescriptor
- * number, otherwise a negative error code is returned
+ * Return: If successful this function returns a positive
+ * filedescriptor number, otherwise -1 is returned
*/
int open_and_lseek(const char *filename, int mode, loff_t pos)
{
- int fd, ret;
+ int fd;
fd = open(filename, mode);
if (fd < 0) {
@@ -541,28 +541,26 @@ int open_and_lseek(const char *filename, int mode, loff_t pos)
if (mode & (O_WRONLY | O_RDWR)) {
struct stat s;
- ret = fstat(fd, &s);
- if (ret) {
+ if (fstat(fd, &s)) {
perror("fstat");
- return ret;
+ goto out;
}
- if (s.st_size < pos) {
- ret = ftruncate(fd, pos);
- if (ret) {
- perror("ftruncate");
- return ret;
- }
+ if (s.st_size < pos && ftruncate(fd, pos)) {
+ perror("ftruncate");
+ goto out;
}
}
if (lseek(fd, pos, SEEK_SET) != pos) {
perror("lseek");
- close(fd);
- return -errno;
+ goto out;
}
return fd;
+out:
+ close(fd);
+ return -1;
}
/**