/* * JR-IDE Project * - (c) 2020 Alan Hightower * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include #include #include #define LOGERR(fmt, args...) \ fprintf (stderr, "\nERROR: " fmt "\n\n", ## args) int main (int argc, char *argv[]) { if (argc < 2) { fprintf (stderr, "\nUsage: %s \n\n", argv[0]); return -1; } int sts = -1, fd = -1; struct stat st_info; uint8_t *buffer = NULL; do { if (stat (argv[1], &st_info)) { LOGERR("Unable to stat '%s' - %s", argv[1], strerror (errno)); break; } if ((fd = open (argv[1], O_RDWR)) < 0) { LOGERR("Unable to open '%s' - %s", argv[1], strerror (errno)); break; } if (!(buffer = (uint8_t *) malloc (st_info.st_size))) { LOGERR("Unable to allocate %ld bytes - %s", st_info.st_size, strerror (errno)); break; } size_t len = read (fd, buffer, st_info.st_size); if (len != (size_t) st_info.st_size) { LOGERR("Unable to read %ld bytes (%ld) - %s", st_info.st_size, (unsigned long) len, strerror (errno)); break; } int i; uint8_t sum = 0; for (i = 0; i < (int) len; i++) sum += buffer[i]; if (!sum) { printf ("File '%s' already checksum'd to zero\n", argv[1]); sts = 0; break; } if (lseek (fd, len - 1, SEEK_SET) != (off_t) (len - 1)) { LOGERR("Unable to seek to end of file - %s", strerror (errno)); break; } sum -= buffer[len - 1]; sum = 0x100 - (int) sum; if (write (fd, &sum, 1) != 1) { LOGERR("Unable to write checksum - %s", strerror (errno)); break; } printf (" -CSUM- Checksum Fix-up \'%s\' (0x%02x)\n", argv[1], sum); sts = 0; } while (0); if (fd >= 0) close (fd); if (buffer) free (buffer); return sts; }