/*1* CDDL HEADER START2*3* The contents of this file are subject to the terms of the4* Common Development and Distribution License (the "License").5* You may not use this file except in compliance with the License.6*7* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE8* or http://www.opensolaris.org/os/licensing.9* See the License for the specific language governing permissions10* and limitations under the License.11*12* When distributing Covered Code, include this CDDL HEADER in each13* file and include the License file at usr/src/OPENSOLARIS.LICENSE.14* If applicable, add the following below this CDDL HEADER, with the15* fields enclosed by brackets "[]" replaced with your own identifying16* information: Portions Copyright [yyyy] [name of copyright owner]17*18* CDDL HEADER END19*/2021/*22* Copyright 2007 Sun Microsystems, Inc. All rights reserved.23* Use is subject to license terms.24*/252627/*28* --------------------------------------------------------------29* BugId 5047993 : Getting bad read data.30*31* Usage: readmmap <filename>32*33* where:34* filename is an absolute path to the file name.35*36* Return values:37* 1 : error38* 0 : no errors39* --------------------------------------------------------------40*/41#include <stdio.h>42#include <stdlib.h>43#include <time.h>44#include <unistd.h>45#include <fcntl.h>46#include <errno.h>47#include <sys/mman.h>4849int50main(int argc, char **argv)51{52char *filename = "badfile";53size_t size = 4395;54size_t idx = 0;55char *buf = NULL;56char *map = NULL;57int fd = -1, bytes, retval = 0;58unsigned seed;5960if (argc < 2 || optind == argc) {61(void) fprintf(stderr,62"usage: %s <file name>\n", argv[0]);63exit(1);64}6566if ((buf = calloc(1, size)) == NULL) {67perror("calloc");68exit(1);69}7071filename = argv[optind];7273(void) remove(filename);7475fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0666);76if (fd == -1) {77perror("open to create");78retval = 1;79goto end;80}8182bytes = write(fd, buf, size);83if (bytes != size) {84(void) printf("short write: %d != %zu\n", bytes, size);85retval = 1;86goto end;87}8889map = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);90if (map == MAP_FAILED) {91perror("mmap");92retval = 1;93goto end;94}95seed = time(NULL);96srandom(seed);9798idx = random() % size;99map[idx] = 1;100101if (msync(map, size, MS_SYNC) != 0) {102perror("msync");103retval = 1;104goto end;105}106107if (munmap(map, size) != 0) {108perror("munmap");109retval = 1;110goto end;111}112113bytes = pread(fd, buf, size, 0);114if (bytes != size) {115(void) printf("short read: %d != %zu\n", bytes, size);116retval = 1;117goto end;118}119120if (buf[idx] != 1) {121(void) printf(122"bad data from read! got buf[%zu]=%d, expected 1\n",123idx, buf[idx]);124retval = 1;125goto end;126}127128(void) printf("good data from read: buf[%zu]=1\n", idx);129end:130if (fd != -1) {131(void) close(fd);132}133if (buf != NULL) {134free(buf);135}136137return (retval);138}139140141