Complete batch 20261016-C-embedded-2: 45 verified GLM/Pi samples, independent regrades and archives; preserve difficulty misses and Salty blockage.
119 lines
3.0 KiB
C
119 lines
3.0 KiB
C
#define _POSIX_C_SOURCE 200809L
|
|
#include "journal.h"
|
|
#include <errno.h>
|
|
#include <limits.h>
|
|
#include <sys/stat.h>
|
|
|
|
static int offset_valid(uint64_t offset, size_t count)
|
|
{
|
|
uint64_t maximum = (uint64_t)INT64_MAX;
|
|
return offset <= maximum && (uint64_t)count <= maximum - offset;
|
|
}
|
|
|
|
static int failed_system_call(void)
|
|
{
|
|
return errno != 0 ? -errno : -EIO;
|
|
}
|
|
|
|
int journal_size(int descriptor, uint64_t *length)
|
|
{
|
|
struct stat info;
|
|
int status;
|
|
do {
|
|
status = fstat(descriptor, &info);
|
|
} while (status < 0 && errno == EINTR);
|
|
if (status < 0) {
|
|
return failed_system_call();
|
|
}
|
|
if (info.st_size < 0) {
|
|
return -EIO;
|
|
}
|
|
*length = (uint64_t)info.st_size;
|
|
return 0;
|
|
}
|
|
|
|
int journal_read_exact(const journal_io *io, int descriptor,
|
|
uint8_t *bytes, size_t count,
|
|
uint64_t offset, size_t *received)
|
|
{
|
|
if (!offset_valid(offset, count)) {
|
|
return -EOVERFLOW;
|
|
}
|
|
size_t done = 0;
|
|
while (done < count) {
|
|
ssize_t result = io->read_at(io->context, descriptor,
|
|
bytes + done, count - done,
|
|
(off_t)(offset + done));
|
|
if (result < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
return failed_system_call();
|
|
}
|
|
if (result == 0) {
|
|
break;
|
|
}
|
|
if ((size_t)result > count - done) {
|
|
return -EIO;
|
|
}
|
|
done += (size_t)result;
|
|
}
|
|
*received = done;
|
|
return 0;
|
|
}
|
|
|
|
int journal_write_exact(const journal_io *io, int descriptor,
|
|
const uint8_t *bytes, size_t count,
|
|
uint64_t offset)
|
|
{
|
|
if (!offset_valid(offset, count)) {
|
|
return -EOVERFLOW;
|
|
}
|
|
size_t done = 0;
|
|
while (done < count) {
|
|
ssize_t result = io->write_at(io->context, descriptor,
|
|
bytes + done, count - done,
|
|
(off_t)(offset + done));
|
|
if (result < 0) {
|
|
if (errno == EINTR) {
|
|
continue;
|
|
}
|
|
return failed_system_call();
|
|
}
|
|
if (result == 0 || (size_t)result > count - done) {
|
|
return -EIO;
|
|
}
|
|
done += (size_t)result;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int journal_resize(const journal_io *io, int descriptor, uint64_t length)
|
|
{
|
|
if (!offset_valid(length, 0)) {
|
|
return -EOVERFLOW;
|
|
}
|
|
for (;;) {
|
|
int result = io->resize(io->context, descriptor, (off_t)length);
|
|
if (result == 0) {
|
|
return 0;
|
|
}
|
|
if (errno != EINTR) {
|
|
return failed_system_call();
|
|
}
|
|
}
|
|
}
|
|
|
|
int journal_synchronize(const journal_io *io, int descriptor)
|
|
{
|
|
for (;;) {
|
|
int result = io->synchronize(io->context, descriptor);
|
|
if (result == 0) {
|
|
return 0;
|
|
}
|
|
if (errno != EINTR) {
|
|
return failed_system_call();
|
|
}
|
|
}
|
|
}
|