AmendHub

Download (as of this amendment):

jcs

/

textview

/

amendments

/

63

util: Sync with upstream


jcs made amendment 63 11 months ago
--- util.c Wed Aug 30 18:01:45 2023 +++ util.c Wed Oct 2 09:22:23 2024 @@ -17,27 +17,51 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ +/* strcasecmp and strncasecmp: + * + * Copyright (c) 1987, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + /* THINK C Project must have a header of "#include <MacHeaders>" */ +#include <GestaltEqu.h> +#include <Folders.h> +#include <Script.h> +#include <SetUpA4.h> +#include <Traps.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <GestaltEqu.h> -#include <Script.h> -#include <SetUpA4.h> #include "util.h" -/* - * Define to enable malloc debugging which creates an allocation larger - * than the requested size, then embeds the allocated size and 2 canary - * bytes before and after the allocation. On xfree(), the canary bytes - * are verified and if any are not correct, the program panics. - */ -/* #define MALLOC_DEBUG 1 */ - /* ALRT resources */ -#define ASK_ALERT_ID 130 +#define ASK_ALERT_ID 130 #define ERROR_STRING_SIZE 1024 static char err_str[ERROR_STRING_SIZE]; @@ -84,6 +108,46 @@ static DialogPtr progress_dialog = NULL; static TEHandle track_control_te = NULL; +/* + * strcasecmp: This array is designed for mapping upper and lower case + * letter together for a case independent comparison. The mappings are + * based upon ascii character sequences. + */ +static const unsigned char strcasecmp_charmap[] = { + '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', + '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', + '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', + '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', + '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', + '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', + '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', + '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', + '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', + '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', + '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', + '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', + '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', + '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', + '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', + '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', + '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', + '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', + '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', + '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', + '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247', + '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257', + '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267', + '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277', + '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307', + '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317', + '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327', + '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', + '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', + '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', + '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', + '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377', +}; + enum { STOP_ALERT, CAUTION_ALERT, @@ -102,8 +166,6 @@ void util_init(void) { alert_ditl_h = xNewHandle(sizeof(alert_ditl)); - if (alert_ditl_h == NULL) - ExitToShell(); HLock(alert_ditl_h); memcpy(*alert_ditl_h, alert_ditl, sizeof(alert_ditl)); HUnlock(alert_ditl_h); @@ -115,46 +177,154 @@ util_init(void) #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4)) +#ifdef MALLOC_DEBUG +/* + * malloc tracking, storing a stack trace of each xmalloc call and its + * size, which can be dumped with xalloc_print(). xfree also gains the + * ability to detect junk frees. + * + * Requires project options 'Always generate stack frames', + * 'Macsbug Names', and 'Long format' to be enabled. + */ +#if !__option(force_frame) || !__option(long_macsbug_names) +#error +#endif + +#define XALLOC_SYMBOL_SIZE 32 +#define XALLOC_NSYMBOLS 64 +#define XALLOC_MAX_STACK_DEPTH 10 +static char *symbols = NULL; +struct xalloc { + char *stack[XALLOC_MAX_STACK_DEPTH]; + unsigned long addr; + unsigned long size; +}; +#define XALLOC_NXALLOCS 512 +static struct xalloc *xallocs = NULL; +#endif + void * xmalloc(size_t size) { -#ifdef MALLOC_DEBUG void *ptr; - unsigned char *cptr; +#ifdef MALLOC_DEBUG + static char cursym[XALLOC_SYMBOL_SIZE], *tsym, *sym; + struct xalloc *xa; + unsigned long _a6, ret; + unsigned char *code; + size_t n, cn, j; + short nframe, tries; #endif - + if (size == 0) panic("xmalloc: zero size"); + ptr = NewPtr(size); + if (ptr == NULL) + return NULL; + #ifdef MALLOC_DEBUG - ptr = NewPtr(size + 8); + asm { + move.l a6,_a6 + }; + + if (symbols == NULL) { + symbols = NewPtr(n = XALLOC_SYMBOL_SIZE * XALLOC_NSYMBOLS); + if (symbols == NULL) + panic("NewPtr failed for xalloc symbols"); + memset(symbols, 0, n); + } + if (xallocs == NULL) { + xallocs = (struct xalloc *)NewPtr(n = (XALLOC_NXALLOCS * + sizeof(struct xalloc))); + if (xallocs == NULL) + panic("NewPtr failed for xallocs"); + memset(xallocs, 0, n); + } + + xa = NULL; + for (n = 0; n < XALLOC_NXALLOCS; n++) { + if (xallocs[n].addr == 0) { + xa = &xallocs[n]; + break; + } + } + if (xa == NULL) + panic("out of xalloc space"); - cptr = (unsigned char *)ptr; - cptr[0] = 0xff; - cptr[1] = 0xff; - cptr[2] = (size >> 24) & 0xff; - cptr[3] = (size >> 16) & 0xff; - cptr[4] = (size >> 8) & 0xff; - cptr[5] = size & 0xff; + /* + * A6 register points to previous stack A6. Above A6 is our return + * address. Walk the code after the return address looking for an RTS + * instruction, then walk 3 bytes after that and we should have that + * function's symbol. Then jump to the previous A6 that our A6 points + * to and do it again to find the previous function symbol, repeating + * until we hit "main" or "uthread_begin". + */ + for (nframe = 0; nframe < XALLOC_MAX_STACK_DEPTH; nframe++) { + ret = *(unsigned long *)(_a6 + 4); + code = (unsigned char *)ret; - cptr[6 + size] = 0xff; - cptr[6 + size + 1] = 0xff; + cursym[0] = '\0'; + for (tries = 0; tries < 1024; code += 2, tries++) { + if (code[0] == 0x4e && code[1] == 0x75) { /* RTS */ + code += 3; + strlcpy(cursym, (char *)code, sizeof(cursym)); + break; + } + } + + if (!cursym[0]) + break; + + sym = NULL; + for (n = 0; n < XALLOC_NSYMBOLS; n++) { + tsym = symbols + (XALLOC_SYMBOL_SIZE * n); + + if (tsym[0] == '\0') + break; + if (strcmp(tsym, cursym) == 0) { + sym = tsym; + break; + } + } + if (sym == NULL) { + for (n = 0; n < XALLOC_NSYMBOLS; n++) { + tsym = symbols + (XALLOC_SYMBOL_SIZE * n); + if (tsym[0] != '\0') + continue; + + strlcpy(tsym, cursym, XALLOC_SYMBOL_SIZE); + sym = tsym; + break; + } + } + if (sym == NULL) + break; + + xa->stack[nframe] = sym; + + if (strcmp(sym, "main") == 0 || strcmp(sym, "uthread_begin") == 0) + break; + + /* walk back up the chain */ + _a6 = *(unsigned long *)_a6; + } - return cptr + 6; -#else - return NewPtr(size); + xa->addr = (unsigned long)ptr; + xa->size = size; #endif + + return ptr; } void xfree(void *ptrptr) { unsigned long *addr = (unsigned long *)ptrptr; + void *ptr; #ifdef MALLOC_DEBUG - size_t size; - unsigned char *cptr; + size_t n; #endif - void *ptr; if (ptrptr == NULL) panic("xfree(NULL)"); @@ -162,25 +332,20 @@ xfree(void *ptrptr) ptr = (void *)*addr; if (ptr == NULL) panic("xfree(&NULL) likely a double-free"); - + #ifdef MALLOC_DEBUG - cptr = (unsigned char *)ptr - 6; - if (cptr[0] != 0xff || cptr[1] != 0xff) - panic("xfree() pre-buf canary dead"); - - size = ((unsigned long)(cptr[2]) << 24) | - ((unsigned long)(cptr[3]) << 16) | - ((unsigned long)(cptr[4]) << 8) | - (unsigned long)(cptr[5]); - - if (cptr[6 + size] != 0xff || cptr[6 + size + 1] != 0xff) - panic("xfree() post-buf canary dead"); - - DisposePtr(cptr); -#else - DisposePtr(ptr); + for (n = 0; n < XALLOC_NXALLOCS; n++) { + if (xallocs[n].addr == (unsigned long)ptr) { + memset(&xallocs[n], 0, sizeof(struct xalloc)); + break; + } + } + if (n == XALLOC_NXALLOCS) + panic("xfree() without xalloc, possibly a junk free", + (unsigned long)ptr); #endif + DisposePtr(ptr); *addr = 0L; } @@ -266,32 +431,47 @@ xstrndup(const char *str, size_t maxlen) return copy; } -/* if var having used_size can't fit add, grow it by grow_amount */ -bool -grow_to_fit(void *var, size_t *var_size, size_t used_size, size_t add, - size_t grow_amount) +#ifdef MALLOC_DEBUG +void +xalloc_print(size_t (*printer)(const char *, ...)) { - char **p = var; - char *curp = *p; - char *newp; - size_t new_size; + ssize_t n, j, len; + size_t total = 0, nallocs = 0; + char chain[128]; - if (used_size + add < *var_size) - return true; - - new_size = *var_size; - while (new_size < used_size + add) - new_size += grow_amount; + for (n = 0; n < XALLOC_NXALLOCS; n++) { + if (xallocs[n].addr == 0) + continue; - newp = xrealloc(curp, new_size); - if (newp == NULL) - return false; + total += xallocs[n].size; + nallocs++; + + chain[0] = '\0'; + len = 0; + for (j = XALLOC_MAX_STACK_DEPTH - 1; j >= 0; j--) { + if (xallocs[n].stack[j] == 0) + continue; + + if (chain[0] != '\0') { + if (len >= sizeof(chain) - 2) + break; + chain[len++] = ' '; + chain[len++] = ':'; + chain[len++] = ' '; + chain[len++] = '\0'; + } + + len = strlcat(chain, xallocs[n].stack[j], sizeof(chain)); + if (len >= sizeof(chain)) + break; + } + + printer("%ld @ %s", xallocs[n].size, chain); + } - *var_size = new_size; - *p = newp; - - return true; + printer("%ld bytes in %ld allocations in use", total, nallocs); } +#endif /* * String functions @@ -304,11 +484,8 @@ getline(char *str, size_t len, char **ret) for (i = 0; i < len; i++) { if (str[i] == '\r' || i == len - 1) { - if (*ret == NULL) { + if (*ret == NULL) *ret = xmalloc(i + 1); - if (*ret == NULL) - return -1; - } memcpy(*ret, str, i + 1); (*ret)[i] = '\0'; return i + 1; @@ -392,6 +569,49 @@ strpos_quoted(char *str, char c) return -1; } +size_t +hexify(unsigned char *input, size_t len, unsigned char *output) +{ + static const char hexchars[] = "0123456789abcdef"; + size_t n, retlen = 0; + + for (n = 0; n < len; n++) { + *output++ = hexchars[input[n] >> 4]; + *output++ = hexchars[input[n] & 0xf]; + retlen += 2; + } + + return retlen; +} + +size_t +unhexify(unsigned char *input, size_t len, unsigned char *output) +{ + size_t n, retlen = 0; + uint8_t c; + + for (n = 0; n < len; n++, input++) { + if (*input >= '0' && *input <= '9') + c = *input - '0'; + else if (*input >= 'a' && *input <= 'f') + c = *input - 'a' + 10; + else if (*input >= 'A' && *input <= 'F') + c = *input - 'A' + 10; + else + continue; + + if (n % 2 == 0) + *output = c << 4; + else { + *output |= c; + retlen++; + output++; + } + } + + return retlen; +} + char * OSTypeToString(OSType type) { @@ -406,8 +626,76 @@ OSTypeToString(OSType type) return ostype_s; } +short +strcasecmp(const char *s1, const char *s2) +{ + const unsigned char *cm = strcasecmp_charmap; + const unsigned char *us1 = (const unsigned char *)s1; + const unsigned char *us2 = (const unsigned char *)s2; + + while (cm[*us1] == cm[*us2++]) + if (*us1++ == '\0') + return (0); + return (cm[*us1] - cm[*--us2]); +} + +short +strncasecmp(const char *s1, const char *s2, size_t n) +{ + if (n != 0) { + const unsigned char *cm = strcasecmp_charmap; + const unsigned char *us1 = (const unsigned char *)s1; + const unsigned char *us2 = (const unsigned char *)s2; + + do { + if (cm[*us1] != cm[*us2++]) + return (cm[*us1] - cm[*--us2]); + if (*us1++ == '\0') + break; + } while (--n != 0); + } + return (0); +} + +char * +strcasestr(const char *s, const char *find) +{ + const unsigned char *cm = strcasecmp_charmap; + const unsigned char *us = (const unsigned char *)s; + const unsigned char *ufind = (const unsigned char *)find; + const unsigned char *tus, *tufind; + + if (find == NULL) + return NULL; + if (find[0] == '\0') + return (char *)s; + + while (*us) { + if (cm[*us] == cm[*ufind]) { + tus = us; + tufind = ufind; + + while (*tufind) { + if (*tus == '\0') + goto advance_us; + if (cm[*tus] != cm[*tufind]) + goto advance_us; + tus++; + tufind++; + } + + return (char *)us; + } + +advance_us: + us++; + } + + return NULL; +} + /* - * BSD err(3) and warn(3) functions + * BSD warn(3) functions */ void @@ -416,13 +704,13 @@ vwarn(short alert_func, const char *format, va_list ap Rect bounds; short hit, itype; WindowPtr win, dialog; - Handle ihandle; + Handle ihandle, okhandle; Rect irect; + progress(NULL); GetPort(&win); vsnprintf(err_str, ERROR_STRING_SIZE, format, ap); - ParamText(CtoPstr(err_str), "\p", "\p", "\p"); center_in_screen(320, 110, false, &bounds); @@ -449,7 +737,7 @@ vwarn(short alert_func, const char *format, va_list ap ShowWindow(dialog); for (;;) { - ModalDialog(0, &hit); + ModalDialog(ModalDialogFilter, &hit); if (hit == ok) break; } @@ -481,22 +769,11 @@ panic(const char *format, ...) vwarn(STOP_ALERT, format, ap); va_end(ap); + Debugger(); ExitToShell(); } void -err(short ret, const char *format, ...) -{ - va_list ap; - - va_start(ap, format); - vwarn(STOP_ALERT, format, ap); - va_end(ap); - - ExitToShell(); -} - -void warn(const char *format, ...) { va_list ap; @@ -507,16 +784,6 @@ warn(const char *format, ...) } void -warnx(const char *format, ...) -{ - va_list ap; - - va_start(ap, format); - vwarn(CAUTION_ALERT, format, ap); - va_end(ap); -} - -void note(const char *format, ...) { va_list ap; @@ -540,9 +807,9 @@ short ask(const char *format, ...) { Rect bounds; - short hit; WindowPtr win, dialog; va_list ap; + short hit; GetPort(&win); @@ -563,7 +830,7 @@ ask(const char *format, ...) ShowWindow(dialog); for (;;) { - ModalDialog(0, &hit); + ModalDialog(ModalDialogFilter, &hit); if (hit == 1 || hit == 2) break; } @@ -604,24 +871,28 @@ about(char *program_name) ReleaseResource(vers); appicon_note("%s", vers_s); } else - warnx("Can't find version number!"); + warn("Can't find version number!"); } void progress(char *format, ...) { static Str255 progress_s; + Cursor c; + CursHandle ch; Handle thandle; va_list argptr; Rect bounds; Rect trect; short ttype; + bool new = false; if (format == NULL) { if (progress_dialog != NULL) { DisposDialog(progress_dialog); DisposHandle(progress_ditl_h); progress_dialog = NULL; + SetCursor(&arrow); } return; } @@ -640,13 +911,19 @@ progress(char *format, ...) center_in_screen(330, 60, false, &bounds); progress_dialog = NewDialog(nil, &bounds, "\p", false, dBoxProc, (WindowPtr)-1L, false, 0, progress_ditl_h); + new = true; } GetDItem(progress_dialog, 1, &ttype, &thandle, &trect); SetIText(thandle, progress_s); - ShowWindow(progress_dialog); - DrawDialog(progress_dialog); + if (new) { + ch = GetCursor(watchCursor); + c = **ch; + SetCursor(&c); + ShowWindow(progress_dialog); + DrawDialog(progress_dialog); + } } void @@ -696,6 +973,24 @@ centered_sfput_dialog(void) return p; } +void +outline_button(ControlHandle button) +{ + PenState pen; + Rect rect; + + SetPort((*button)->contrlOwner); + GetPenState(&pen); + PenNormal(); + + rect = (*button)->contrlRect; + InsetRect(&rect, -4, -4); + PenSize(3, 3); + FrameRoundRect(&rect, (rect.bottom - rect.top) / 2, + (rect.bottom - rect.top) / 2); + SetPenState(&pen); +} + /* * General Mac-specific non-GUI functions */ @@ -768,37 +1063,31 @@ xGetStringAsChar(short id) HLock(h); l = (*h)[0]; out = xmalloc(l + 1); - if (out != NULL) { - memcpy((void *)out, (void *)(*h + 1), l); - out[l] = '\0'; - } + memcpy((void *)out, (void *)(*h + 1), l); + out[l] = '\0'; ReleaseResource(h); return out; } -bool -xGetStringAsLong(short id, long *ret) +long +xGetStringAsLong(short id) { char *c; + long r; c = xGetStringAsChar(id); - if (c == NULL) - return false; - *ret = atol(c); + r = atol(c); xfree(&c); - return true; + return r; } -bool +void xSetHandleSize(Handle h, Size s) { SetHandleSize(h, s); - if (MemError()) { - warn("Failed to SetHandleSize to %ld", s); - return false; - } - return true; + if (MemError()) + panic("Failed to SetHandleSize to %ld", s); } /* @@ -806,7 +1095,7 @@ xSetHandleSize(Handle h, Size s) */ short -getpath(short vRefNum, Str255 fileName, Str255 ret, bool include_file) +getpath(short vRefNum, Str255 fileName, Str255 *ret, bool include_file) { WDPBRec wdir; HVolumeParam wvol; @@ -816,24 +1105,20 @@ getpath(short vRefNum, Str255 fileName, Str255 ret, bo char *tmpret = NULL, *tmp = NULL; char *lastcolon; - ret[0] = 0; - if (strchr((char *)fileName + 1, ':') != NULL) { /* already a full path */ - memcpy(ret, fileName, 256); + memcpy(*ret, fileName, 256); if (!include_file) { - PtoCstr(ret); - lastcolon = strrchr((char *)ret, ':'); + PtoCstr(*ret); + lastcolon = strrchr((char *)*ret, ':'); lastcolon[0] = '\0'; - CtoPstr(ret); + CtoPstr(*ret); } return 0; } name = xmalloc(FILENAME_MAX); - if (name == NULL) - return 1; - + wdir.ioVRefNum = wdir.ioWDVRefNum = vRefNum; wdir.ioWDIndex = 0; wdir.ioWDProcID = 0; @@ -867,17 +1152,8 @@ getpath(short vRefNum, Str255 fileName, Str255 ret, bo wcinfo.ioDrDirID = wdir.ioWDDirID; tmp = xmalloc(FILENAME_MAX); - if (tmp == NULL) { - xfree(&name); - return 1; - } tmpret = xmalloc(FILENAME_MAX); - if (tmp == NULL) { - xfree(&tmp); - xfree(&name); - return 1; - } - + /* go backwards, prepending each folder's parent */ while (wcinfo.ioDrParID != 1) { wcinfo.ioDrDirID = wcinfo.ioDrParID; /* .. */ @@ -907,7 +1183,7 @@ getpath(short vRefNum, Str255 fileName, Str255 ret, bo strlcat(tmpret, name, FILENAME_MAX); } } else if (retlen == 0) { - ret[0] = 0; + (*ret)[0] = 0; xfree(&tmp); xfree(&tmpret); xfree(&name); @@ -915,7 +1191,7 @@ getpath(short vRefNum, Str255 fileName, Str255 ret, bo } CtoPstr(tmpret); - memcpy(ret, tmpret, FILENAME_MAX); + memcpy(*ret, tmpret, FILENAME_MAX); xfree(&tmp); xfree(&tmpret); xfree(&name); @@ -930,8 +1206,6 @@ stat(char *path, struct stat *sb) short ret; ppath = xstrdup(path); - if (ppath == NULL) - return -1; CtoPstr(ppath); ret = FStat((unsigned char *)ppath, sb); xfree(&ppath); @@ -964,6 +1238,7 @@ bool FIsDir(Str255 path) { struct stat st; + short ret; if (FStat(path, &st) != 0) return false; @@ -1074,8 +1349,6 @@ copy_file_contents(short source_ref, short dest_ref) return error; buf = xmalloc(1024); - if (buf == NULL) - return -1; while (source_size > 0) { count = 1024; @@ -1127,7 +1400,73 @@ FSReadLine(short frefnum, char *buf, size_t buflen) return total_read; } +TrapType +GetTrapType(unsigned long theTrap) +{ + if (BitAnd(theTrap, 0x0800) > 0) + return ToolTrap; + return OSTrap; +} + +bool +TrapAvailable(unsigned long trap) +{ + TrapType trapType = ToolTrap; + unsigned long numToolBoxTraps; + + if (NGetTrapAddress(_InitGraf, ToolTrap) == + NGetTrapAddress(0xAA6E, ToolTrap)) + numToolBoxTraps = 0x200; + else + numToolBoxTraps = 0x400; + + trapType = GetTrapType(trap); + if (trapType == ToolTrap) { + trap = BitAnd(trap, 0x07FF); + if (trap >= numToolBoxTraps) + trap = _Unimplemented; + } + + return (NGetTrapAddress(trap, trapType) != + NGetTrapAddress(_Unimplemented, ToolTrap)); +} + +void +GetSystemFolder(short *vRefNumP, long *dirIDP) +{ + SysEnvRec info; + long wdProcID; + + SysEnvirons(1, &info); + if (GetWDInfo(info.sysVRefNum, vRefNumP, dirIDP, &wdProcID) != noErr) { + *vRefNumP = 0; + *dirIDP = 0; + } +} + +void +GetSystemSubfolder(OSType folder, bool create, short *vRefNumP, long *dirIDP) +{ + bool hasFolderMgr = false; + long feature; + + if (TrapAvailable(_GestaltDispatch) && + Gestalt(gestaltFindFolderAttr, &feature) == noErr) + hasFolderMgr = true; + + if (!hasFolderMgr) { + GetSystemFolder(vRefNumP, dirIDP); + return; + } + + if (FindFolder(kOnSystemDisk, folder, create, vRefNumP, + dirIDP) != noErr) { + *vRefNumP = 0; + *dirIDP = 0; + } +} + /* * Gestalt functions */ @@ -1202,6 +1541,19 @@ get_version(bool long_version) return vers_s; } +bool +screen_saver_running(void) +{ + short error; + long resp; + + error = Gestalt('SAVR', &resp); /* gestaltScreenSaverAttr */ + if (error == 0 && (resp & (1 << 1))) /* gestaltSaverAsleep */ + return true; + + return false; +} + /* * General Mac-specific GUI functions */ @@ -1238,10 +1590,6 @@ DrawGrowIconOnly(WindowPtr win) RgnHandle tmp; GetClip(tmp = NewRgn()); - if (tmp == NULL) { - warn("NewRgn() failed"); - return; - } r = win->portRect; r.top = r.bottom - SCROLLBAR_WIDTH; r.left = r.right - SCROLLBAR_WIDTH + 1; @@ -1432,10 +1780,22 @@ pascal bool ModalDialogFilter(DialogPtr dlg, EventRecord *event, short *hit) { WindowPtr event_win; - short event_in; + short event_in, itype; char key; + ControlHandle ihandle; + Rect irect; switch (event->what) { + case nullEvent: + /* + * TODO: support passing this through to a function the caller + * can specify to do something while we're staying modal + */ + break; + case updateEvt: + GetDItem(dlg, ok, &itype, &ihandle, &irect); + outline_button(ihandle); + break; case mouseDown: event_in = FindWindow(event->where, &event_win); @@ -1623,6 +1983,21 @@ RestoreHiddenMenuBar(void) DrawMenuBar(); } +bool +CommandPeriodPressed(void) +{ + EventRecord event; + + if (!GetNextEvent(keyDownMask | autoKeyMask, &event)) + return false; + + if ((event.modifiers & cmdKey) && + ((event.message & charCodeMask) == '.')) + return true; + + return false; +} + /* C Extensions */ /* @@ -1764,17 +2139,18 @@ static struct format { int precision; } default_format; -int bounded_vfprintf(FILE *fp, const char *fmt, va_list arg); +short bounded_vfprintf(FILE *fp, const char *fmt, va_list arg); static int nullio(FILE *fp, int i); -int +short bounded_vfprintf(FILE *fp, const char *fmt, va_list arg) { - register int c, i, nwritten = 0; + register int c, i, j, nwritten = 0; register unsigned long n; + long double x; register char *s; #define VFPRINTF_BUFLEN 512 - char buf[VFPRINTF_BUFLEN], *digits, *t; + static char buf[VFPRINTF_BUFLEN], *digits, *t; struct format F; for (c = *fmt; c; c = *++fmt) { @@ -1992,7 +2368,7 @@ conv: switch (c) { else { if (!F.havePrecision) i = strlen(s); - else if ((t = memchr(s, '\0', F.precision)) != NULL) + else if (t = memchr(s, '\0', F.precision)) i = t - s; else i = F.precision; @@ -2050,7 +2426,7 @@ done: return(nwritten); } -int +short snprintf(char *s, size_t size, const char *fmt, ...) { return(vsnprintf(s, size, fmt, __va(fmt))); @@ -2062,20 +2438,32 @@ nullio(FILE *fp, int i) return(EOF); } -int +short vsnprintf(char *s, size_t size, const char *fmt, void *p) { FILE f; int n; + unsigned char zb; memset(&f, 0, sizeof(f)); f.refnum = -1; - f.ptr = (unsigned char *) s; + f.ptr = (unsigned char *)s; f.cnt = size; f.proc = nullio; f.dirty = 1; - if ((n = bounded_vfprintf(&f, fmt, p)) >= 0) - s[n] = 0; + if (size == 0) + zb = s[0]; + + if ((n = bounded_vfprintf(&f, fmt, p)) >= 0) { + if (n < size) + s[n] = 0; + else + s[size - 1] = 0; + } + + if (size == 0) + s[0] = zb; + return(n); } --- util.h Mon Mar 27 21:33:13 2023 +++ util.h Tue Oct 1 20:15:20 2024 @@ -18,28 +18,34 @@ #define __UTIL_H__ #include <stdlib.h> -#include <limits.h> +#include "stdint.h" #include <time.h> -#ifndef SIZE_MAX -#define SIZE_MAX ULONG_MAX -#endif +/* uncomment to enable malloc tracking */ +#define MALLOC_DEBUG #define nitems(what) (sizeof((what)) / sizeof((what)[0])) #define member_size(type, member) sizeof(((type *)0)->member) -#define MALLOC_NOTE_SIZE 32 - #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define BOUND(a, min, max) ((a) > (max) ? (max) : ((a) < (min) ? (min) : (a))) -#define CHARS_TO_LONG(a,b,c,d) (unsigned long)(\ +#define EXPAND_TO_FIT(var, var_size, used_size, add, grow_amount) { \ + if ((used_size) + (add) >= (var_size)) { \ + while ((used_size) + (add) >= (var_size)) { \ + (var_size) += (grow_amount); \ + } \ + (var) = xrealloc((var), (var_size)); \ + } \ +} + +#define BYTES_TO_LONG(a,b,c,d) (unsigned long)(\ ((unsigned long)((unsigned char)(a)) << 24) | \ ((unsigned long)((unsigned char)(b)) << 16) | \ ((unsigned long)((unsigned char)(c)) << 8) | \ (unsigned long)((unsigned char)(d)) ) -#define CHARS_TO_SHORT(a,b) (unsigned short)(\ +#define BYTES_TO_SHORT(a,b) (unsigned short)(\ ((unsigned short)((unsigned char)(a)) << 8) | \ (unsigned short)((unsigned char)(b)) ) @@ -52,19 +58,70 @@ #define MAX_TEXTEDIT_SIZE 32767L -#ifndef bool -typedef Boolean bool; -#endif -typedef signed long off_t; -typedef signed long ssize_t; -typedef unsigned char u_char; -typedef unsigned long u_int; -typedef unsigned char u_int8_t; -typedef unsigned short u_int16_t; -typedef unsigned long u_int32_t; +/* 24107 days */ +#define UNIX_TO_MAC_TIME(uts) ((unsigned long)(uts) + 2082844800) +#define MAC_TO_UNIX_TIME(mts) ((unsigned long)(mts) - 2082844800) -#define BYTE_ORDER BIG_ENDIAN +/* singly-linked lists */ +#define SLIST_HEAD(name, type) struct name { struct type *slh_first; } +#define SLIST_HEAD_INITIALIZER(head) { NULL } +#define SLIST_ENTRY(type) struct { struct type *sle_next; } +#define SLIST_FIRST(head) ((head)->slh_first) +#define SLIST_END(head) NULL +#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head)) +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) +#define SLIST_INIT(head) do { SLIST_FIRST((head)) = NULL; } while (0) +#define SLIST_FOREACH(var, head, field) \ + for ((var) = SLIST_FIRST(head); \ + (var) != SLIST_END(head); \ + (var) = SLIST_NEXT(var, field)) +#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SLIST_FIRST(head); \ + (var) && ((tvar) = SLIST_NEXT(var, field), 1); \ + (var) = (tvar)) + +#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ + (elm)->field.sle_next = (slistelm)->field.sle_next; \ + (slistelm)->field.sle_next = (elm); \ +} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) do { \ + (elm)->field.sle_next = (head)->slh_first; \ + (head)->slh_first = (elm); \ +} while (0) + +#define SLIST_APPEND(head, elm, type, field) do { \ + if (SLIST_EMPTY(head)) { \ + SLIST_INSERT_HEAD(head, elm, field); \ + } else { \ + struct type *curelm = (head)->slh_first; \ + while (curelm->field.sle_next != NULL) \ + curelm = curelm->field.sle_next; \ + curelm->field.sle_next = (elm); \ + } \ +} while (0) + +#define SLIST_REMOVE_AFTER(elm, field) do { \ + (elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ +} while (0) + +#define SLIST_REMOVE_HEAD(head, field) do { \ + (head)->slh_first = (head)->slh_first->field.sle_next; \ +} while (0) + +#define SLIST_REMOVE(head, elm, type, field) do { \ + if ((head)->slh_first == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->slh_first; \ + while (curelm->field.sle_next != (elm)) \ + curelm = curelm->field.sle_next; \ + curelm->field.sle_next = curelm->field.sle_next->field.sle_next; \ + } \ + (elm)->field.sle_next = NULL; \ +} while (0) + typedef struct { short push[2], rts; void *addr; @@ -89,21 +146,24 @@ void * xrealloc(void *src, size_t size); void * xreallocarray(void *, size_t, size_t); char * xstrdup(const char *); char * xstrndup(const char *str, size_t maxlen); +#ifdef MALLOC_DEBUG +void xalloc_print(size_t (*printer)(const char *, ...)); +#endif -bool grow_to_fit(void *var, size_t *var_size, size_t used_size, size_t add, - size_t grow_amount); - short getline(char *str, size_t len, char **ret); const char * ordinal(unsigned short n); size_t rtrim(char *str, char *chars); long strpos_quoted(char *str, char c); +size_t hexify(unsigned char *input, size_t len, unsigned char *output); +size_t unhexify(unsigned char *input, size_t len, unsigned char *output); char * OSTypeToString(OSType type); +char * strcasestr(const char *s, const char *find); +short strcasecmp(const char *s1, const char *s2); +short strncasecmp(const char *s1, const char *s2, size_t n); unsigned long xorshift32(void); void panic(const char *format, ...); -void err(short ret, const char *format, ...); -void warnx(const char *format, ...); void warn(const char *format, ...); void note(const char *format, ...); void appicon_note(const char *format, ...); @@ -116,24 +176,31 @@ void window_rect(WindowPtr win, Rect *ret); void center_in_screen(short width, short height, bool titlebar, Rect *b); Point centered_sfget_dialog(void); Point centered_sfput_dialog(void); +void outline_button(ControlHandle button); Handle xNewHandle(size_t size); Handle xGetResource(ResType type, short id); StringHandle xGetString(short id); char * xGetStringAsChar(short id); -bool xGetStringAsLong(short id, long *ret); -bool xSetHandleSize(Handle h, Size s); +long xGetStringAsLong(short id); +void xSetHandleSize(Handle h, Size s); -short getpath(short vRefNum, Str255 fileName, Str255 ret, bool include_file); +short getpath(short vRefNum, Str255 fileName, Str255 *ret, bool include_file); bool FIsDir(Str255 path); short stat(char *path, struct stat *sb); short FStat(Str255 path, struct stat *sb); OSErr copy_file(Str255 source, Str255 dest, bool overwrite); OSErr copy_file_contents(short source_ref, short dest_ref); OSErr FSReadLine(short frefnum, char *buf, size_t buflen); +TrapType GetTrapType(unsigned long theTrap); +bool TrapAvailable(unsigned long trap); +void GetSystemFolder(short *vRefNumP, long *dirIDP); +void GetSystemSubfolder(OSType folder, bool create, short *vRefNumP, + long *dirIDP); char * gestalt_machine_type(void); char * get_version(bool long_version); +bool screen_saver_running(void); short FontHeight(short font_id, short size); void DrawGrowIconOnly(WindowPtr win); @@ -152,12 +219,13 @@ void PasswordDialogFieldFinish(void); pascal void NullCaretHook(void); void HideMenuBar(void); void RestoreHiddenMenuBar(void); +bool CommandPeriodPressed(void); size_t strlcat(char *dst, const char *src, size_t dsize); size_t strlcpy(char *dst, const char *src, size_t dsize); char * strndup(const char *str, size_t maxlen); char * strsep(char **stringp, const char *delim); -int snprintf(char *s, size_t size, const char *fmt, ...); -int vsnprintf(char *s, size_t size, const char *fmt, void *p); +short snprintf(char *s, size_t size, const char *fmt, ...); +short vsnprintf(char *s, size_t size, const char *fmt, void *p); #endif \ No newline at end of file