Fix fread() with 2gb+ sizes

This commit is contained in:
Justine Tunney 2024-05-24 19:28:23 -07:00
parent 5f61d273e4
commit ed93fc3dd7
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
8 changed files with 254 additions and 119 deletions

View file

@ -16,53 +16,67 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/stdio/stdio.h"
#include "libc/testlib/testlib.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
/*
* This test was contributed by @ahgamut
* https://github.com/jart/cosmopolitan/issues/61#issuecomment-792214575
*/
void SetUpOnce(void) {
testlib_enable_tmp_setup_teardown();
char path[PATH_MAX];
void teardown(void) {
unlink(path);
}
int writefile(const char* filename) {
int stat = 0;
FILE* fp = fopen(filename, "w");
stat = fputs("cosmopolitan libc\n", fp);
fclose(fp);
return stat;
}
int readfile(const char* filename) {
int stat = 0;
char buf1[30];
char buf2[30];
FILE *fp1, *fp2;
fp1 = fopen(filename, "r");
if (!fp1) {
printf("failed to read %s in r\n", filename);
int setup(void) {
int fd;
const char* tmpdir;
if ((tmpdir = getenv("TMPDIR")))
strlcpy(path, tmpdir, sizeof(path));
else
strlcpy(path, "/tmp", sizeof(path));
strlcat(path, "/freopen_test.XXXXXX", sizeof(path));
if ((fd = mkstemp(path)) == -1)
return 1;
}
buf1[0] = fgetc(fp1);
buf1[1] = '\0';
fp2 = freopen(filename, "rb", fp1);
if (!fp2) {
printf("failed to read %s in rb\n", filename);
return 1;
}
stat = fread(buf2, sizeof(buf2[0]), 20, fp2);
ASSERT_EQ(18, stat);
buf2[stat] = '\0';
fclose(fp2);
ASSERT_STREQ("c", buf1);
ASSERT_STREQ("cosmopolitan libc\n", buf2);
if (write(fd, "cosmopolitan libc\n", 18) != 18)
return 2;
if (close(fd))
return 3;
return 0;
}
TEST(freopen, test) {
writefile("file.txt");
readfile("file.txt");
int test(void) {
FILE* fp;
char buf[20];
if (!(fp = fopen(path, "r")))
return 4;
if (fgetc(fp) != 'c')
return 5;
if (!(fp = freopen(path, "rb", fp)))
return 6;
if (fread(buf, 1, 20, fp) != 18)
return 7;
if (memcmp(buf, "cosmopolitan libc\n", 18))
return 8;
if (fclose(fp))
return 9;
return 0;
}
int main(int argc, char* argv[]) {
int rc;
if ((rc = setup())) {
perror(path);
teardown();
return rc;
}
rc = test();
teardown();
return rc;
}