svn commit: r274809 - user/marcel/libvdsk/libvdsk
Marcel Moolenaar
marcel at FreeBSD.org
Fri Nov 21 19:13:56 UTC 2014
Author: marcel
Date: Fri Nov 21 19:13:54 2014
New Revision: 274809
URL: https://svnweb.freebsd.org/changeset/base/274809
Log:
Improve vdsk_open():
1. Use calloc(3) instead of malloc(3) so that the user context is
always pre-initialized.
2. Wrap the sequence of steps in a `do { ... } while (0)' block so
that we can use break to exit. Introduce ctx as the variable to
return and use it to determine success or failure.
With a single entry and a single exit, we can more easily add some
kind of tracing or logging in the future.
Modified:
user/marcel/libvdsk/libvdsk/vdsk.c
Modified: user/marcel/libvdsk/libvdsk/vdsk.c
==============================================================================
--- user/marcel/libvdsk/libvdsk/vdsk.c Fri Nov 21 18:35:50 2014 (r274808)
+++ user/marcel/libvdsk/libvdsk/vdsk.c Fri Nov 21 19:13:54 2014 (r274809)
@@ -52,37 +52,50 @@ vdskctx
vdsk_open(const char *path, int flags, size_t size)
{
struct stat sb;
+ vdskctx ctx;
struct vdsk *vdsk;
- size += sizeof(struct vdsk);
- vdsk = malloc(size);
- if (vdsk == NULL)
- return (NULL);
-
- vdsk->fd = open(path, flags);
- if (vdsk->fd == -1) {
- free(vdsk);
- return (NULL);
- }
+ ctx = NULL;
- if (fstat(vdsk->fd, &sb) == -1) {
- close(vdsk->fd);
- free(vdsk);
- return (NULL);
- }
+ do {
+ size += sizeof(struct vdsk);
+ vdsk = calloc(1, size);
+ if (vdsk == NULL)
+ break;
+
+ vdsk->fd = open(path, flags);
+ if (vdsk->fd == -1)
+ break;
+
+ if (fstat(vdsk->fd, &sb) == -1)
+ break;
+
+ if (S_ISCHR(sb.st_mode)) {
+ if (ioctl(vdsk->fd, DIOCGMEDIASIZE,
+ &vdsk->capacity) < 0)
+ break;
+ if (ioctl(vdsk->fd, DIOCGSECTORSIZE,
+ &vdsk->sectorsize) < 0)
+ break;
+ } else {
+ vdsk->capacity = sb.st_size;
+ vdsk->sectorsize = DEV_BSIZE;
+ }
- if (S_ISCHR(sb.st_mode)) {
- if (ioctl(vdsk->fd, DIOCGMEDIASIZE, &vdsk->capacity) < 0 ||
- ioctl(vdsk->fd, DIOCGSECTORSIZE, &vdsk->sectorsize) < 0) {
- close(vdsk->fd);
+ /* Complete... */
+ ctx = vdsk + 1;
+ } while (0);
+
+ if (ctx == NULL) {
+ if (vdsk != NULL) {
+ if (vdsk->fd != -1)
+ close(vdsk->fd);
free(vdsk);
- return (NULL);
+ vdsk = NULL;
}
- } else {
- vdsk->capacity = sb.st_size;
- vdsk->sectorsize = DEV_BSIZE;
}
- return (vdsk + 1);
+
+ return (ctx);
}
int
More information about the svn-src-user
mailing list