diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..c443f8ebca759c3097439023b2d3ac86887555fa --- /dev/null +++ b/.clang-format @@ -0,0 +1,211 @@ +--- +Language: Cpp +# BasedOnStyle: Google +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveMacros: None +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true +DerivePointerAlignment: true +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^<ext/.*\.h>' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*\.h>' + Priority: 1 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 3 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '([-_](test|unittest))?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseLabels: true +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +LambdaBodyIndentation: Signature +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Left +PPIndentWidth: -1 +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + - ParseTestProto + - ParsePartialTestProto + CanonicalDelimiter: pb + BasedOnStyle: google +ReferenceAlignment: Pointer +ReflowComments: true +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Auto +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 5db5d1464ac2a5d265e39f87ac14c3d085cdee61..002d2314c063d5dccce89d47624c72a0632953ad 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -17,6 +17,7 @@ run pre-commit: image: registry.esss.lu.se/ics-docker/pre-commit:latest script: - pre-commit run --all-files + allow_failure: true shellcheck: image: pipelinecomponents/shellcheck:latest diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 29b6724c8df5fb06fdf49c9d39e214ba3662dcb8..ef1fe2bb58b9dff343ab122fae309d9f7560244c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -21,3 +21,8 @@ repos: rev: v13.0.0 hooks: - id: clang-format + - repo: https://github.com/pocc/pre-commit-hooks + rev: v1.3.5 + hooks: + - id: cppcheck + args: ["--enable=all", "--suppress=missingIncludeSystem", "--language=c", "--std=c99"] diff --git a/require-ess/src/asprintf.c b/require-ess/src/asprintf.c index 7290e021a7f85f871b4bf16b96535eb8235eb5e5..1b18caaf3784524f34489ebc62bceeb82e949358 100644 --- a/require-ess/src/asprintf.c +++ b/require-ess/src/asprintf.c @@ -1,4 +1,8 @@ +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + #include "asprintf.h" + #include <stdarg.h> #include <stdio.h> #include <stdlib.h> @@ -17,7 +21,7 @@ int vasprintf(char **pbuffer, const char *format, va_list ap) { #else /* if we have no va_copy, we probably don't need one */ #define ap2 ap -#endif +#endif // va_copy #if defined(_WIN32) len = _vscprintf(format, ap2); @@ -27,15 +31,14 @@ int vasprintf(char **pbuffer, const char *format, va_list ap) { #ifdef va_copy va_end(ap2); -#endif +#endif // va_copy if (len <= 0) { fprintf(stderr, "vasprintf: error calculating needed size\n"); return -1; } *pbuffer = malloc(len + 1); - if (*pbuffer == NULL) - return -1; + if (*pbuffer == NULL) return -1; return vsprintf(*pbuffer, format, ap); } diff --git a/require-ess/src/asprintf.h b/require-ess/src/asprintf.h index d2e232e15abf5bae4ebb2cef647a08b41edf674e..4d502526eaa1bf5f6bd5c7c65a4b390f93df0765 100644 --- a/require-ess/src/asprintf.h +++ b/require-ess/src/asprintf.h @@ -1,18 +1,23 @@ -#ifndef asprintf_h -#define asprintf_h +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#pragma once + #ifdef __cplusplus extern "C" { -#endif +#endif // __cplusplus + #include <stdarg.h> + #ifndef __GNUC__ #define __attribute__(arg) -#endif +#endif // __GNUC__ int asprintf(char **pbuffer, const char *format, ...) __attribute__((__format__(__printf__, 2, 3))); int vasprintf(char **pbuffer, const char *format, va_list ap) __attribute__((__format__(__printf__, 2, 0))); + #ifdef __cplusplus } -#endif -#endif +#endif // __cplusplus diff --git a/require-ess/src/dbLoadTemplate.h b/require-ess/src/dbLoadTemplate.h index 0d37f6ce0d19d0a55e2f998b967ef0fe64a5a6d8..a720a515c1fbd009b6271126dc6d2662c2cc71f4 100644 --- a/require-ess/src/dbLoadTemplate.h +++ b/require-ess/src/dbLoadTemplate.h @@ -6,13 +6,10 @@ * EPICS BASE is distributed subject to a Software License Agreement found * in file LICENSE that is included with this distribution. \*************************************************************************/ -/* dbLoadTemplate.h */ -#ifndef INCdbLoadTemplateh -#define INCdbLoadTemplateh +#pragma once #include "dbCoreAPI.h" + DBCORE_API int dbLoadTemplate(const char *sub_file, const char *cmd_collect, const char *path); - -#endif /*INCdbLoadTemplateh*/ diff --git a/require-ess/src/expr.c b/require-ess/src/expr.c index 9ec91aa39892b299182375c154b920f296ec1847..150548b7b5c0a8cb743a836d8ca5b0f0a7f7bd08 100644 --- a/require-ess/src/expr.c +++ b/require-ess/src/expr.c @@ -1,18 +1,20 @@ +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#include "expr.h" + #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include "expr.h" - int exprDebug; static int parseSubExpr(const char **pp, long *v, int pr, int op); static long parseString(const char **pp, const char **pstart); #define parseExpr(pp, v) parseSubExpr(pp, v, 0, 0) -#define skipSpace(p) \ - while (isspace((unsigned char)*p)) \ - p++ +#define skipSpace(p) \ + while (isspace((unsigned char)*p)) p++ static int parseValue(const char **pp, long *v) { long val; @@ -32,10 +34,8 @@ static int parseValue(const char **pp, long *v) { if (memchr("+-~!", o, 4)) { /* unary operators */ p++; - if (!parseValue(&p, &val)) - return 0; /* no valid value */ - if (exprDebug) - printf("parseValue: %c %ld\n", o, val); + if (!parseValue(&p, &val)) return 0; /* no valid value */ + if (exprDebug) printf("parseValue: %c %ld\n", o, val); if (o == '-') val = -val; else if (o == '~') @@ -45,16 +45,13 @@ static int parseValue(const char **pp, long *v) { } else if (o == '(') { /* sub-expression */ p++; - if (parseExpr(&p, &val) < 0) - return 0; /* no valid expression */ + if (parseExpr(&p, &val) < 0) return 0; /* no valid expression */ skipSpace(p); - if (*p++ != ')') - return 0; /* missing ) */ + if (*p++ != ')') return 0; /* missing ) */ } else if (o == '#') { /* string length operator */ p++; - if (exprDebug) - printf("parseValue: string length of %s\n", p); + if (exprDebug) printf("parseValue: string length of %s\n", p); if (*p == '"' || *p == '\'') val = parseString(&p, NULL); else @@ -63,8 +60,7 @@ static int parseValue(const char **pp, long *v) { /* number */ char *e; val = strtol(p, &e, 0); - if (e == p) - return 0; /* no number */ + if (e == p) return 0; /* no number */ if (isalpha((unsigned char)*e) || *e == '.') { /* part of plain word or floating point number */ @@ -79,20 +75,14 @@ static int parseValue(const char **pp, long *v) { static long ipow(long base, long exp) { long val; - if (exp == 2) - return base * base; - if (exp == 3) - return base * base * base; - if (exp == 1) - return base; - if (exp == 0) - return 1; - if (exp < 0) - return 0; + if (exp == 2) return base * base; + if (exp == 3) return base * base * base; + if (exp == 1) return base; + if (exp == 0) return 1; + if (exp < 0) return 0; val = ipow(base, exp >> 1); val *= val; - if (exp & 1) - val *= base; + if (exp & 1) val *= base; return val; } @@ -100,8 +90,7 @@ static char parseSep(const char **pp, const char *seps) { const char *p = *pp; skipSpace(p); - if (!*p || !strchr(seps, *p)) - return 0; + if (!*p || !strchr(seps, *p)) return 0; *pp = p + 1; return *p; } @@ -149,19 +138,18 @@ static int startsWith(const char *p, const char *s) { int i = 0; while (*s) { i++; - if (*p++ != *s++) - return 0; + if (*p++ != *s++) return 0; } return i; } static int parseOp(const char **pp) { const char *p = *pp; - int o, l; skipSpace(p); if (ispunct((unsigned char)*p)) { - for (o = 1; o < (int)(sizeof(ops) / sizeof(ops[0])); o++) { + for (int o = 1; o < (int)(sizeof(ops) / sizeof(ops[0])); o++) { + int l; if ((l = startsWith(p, ops[o].str))) { /* operator found */ *pp = p + l; @@ -176,7 +164,7 @@ static int parseSubExpr(const char **pp, long *v, int pr, int o) { const char *p = *pp; long val = o ? *v : 0; long val2; - int o2 = o; + int o2; if (exprDebug) printf("parseExpr(%d): start %ld %s \"%s\"\n", pr, val, ops[o].str, p); @@ -203,99 +191,92 @@ static int parseSubExpr(const char **pp, long *v, int pr, int o) { if (exprDebug) printf("parseExpr(%d): calc %ld %s %ld\n", pr, val, ops[o].str, val2); switch (o) { - case op_none: - val = val2; - break; - case op_pow: - val = ipow(val, val2); - break; - case op_mul: - val *= val2; - break; - case op_div: - val /= val2; - break; - case op_mod: - val %= val2; - break; - case op_plus: - val += val2; - break; - case op_minus: - val -= val2; - break; - case op_lshift: - val <<= val2; - break; - case op_urshift: - val = (unsigned long)val >> val2; - break; - case op_rshift: - val >>= val2; - break; - case op_min: - if (val2 < val) - val = val2; - break; - case op_max: - if (val2 > val) - val = val2; - break; - case op_cmp: - val = val < val2 ? -1 : val == val2 ? 0 : 1; - break; - case op_lteq: - val = val <= val2; - break; - case op_gteq: - val = val >= val2; - break; - case op_lt: - val = val < val2; - break; - case op_gt: - val = val > val2; - break; - case op_eq: - val = val == val2; - break; - case op_neq: - val = val != val2; - break; - case op_logicand: - val = val && val2; - break; - case op_logicor: - val = val || val2; - break; - case op_bitand: - val &= val2; - break; - case op_bitxor: - val ^= val2; - break; - case op_bitor: - val |= val2; - break; - case op_alt: - if (!val) + case op_none: val = val2; - break; + break; + case op_pow: + val = ipow(val, val2); + break; + case op_mul: + val *= val2; + break; + case op_div: + val /= val2; + break; + case op_mod: + val %= val2; + break; + case op_plus: + val += val2; + break; + case op_minus: + val -= val2; + break; + case op_lshift: + val <<= val2; + break; + case op_urshift: + val = (unsigned long)val >> val2; + break; + case op_rshift: + val >>= val2; + break; + case op_min: + if (val2 < val) val = val2; + break; + case op_max: + if (val2 > val) val = val2; + break; + case op_cmp: + val = val < val2 ? -1 : val == val2 ? 0 : 1; + break; + case op_lteq: + val = val <= val2; + break; + case op_gteq: + val = val >= val2; + break; + case op_lt: + val = val < val2; + break; + case op_gt: + val = val > val2; + break; + case op_eq: + val = val == val2; + break; + case op_neq: + val = val != val2; + break; + case op_logicand: + val = val && val2; + break; + case op_logicor: + val = val || val2; + break; + case op_bitand: + val &= val2; + break; + case op_bitxor: + val ^= val2; + break; + case op_bitor: + val |= val2; + break; + case op_alt: + if (!val) val = val2; + break; } - if (exprDebug) - printf("parseExpr(%d): result %ld\n", pr, val); + if (exprDebug) printf("parseExpr(%d): result %ld\n", pr, val); if (o2 == op_if) { long val3 = 0; val2 = 1; - if (exprDebug) - printf("parseExpr(%d) if %ld\n", pr, val); + if (exprDebug) printf("parseExpr(%d) if %ld\n", pr, val); if ((o2 = parseExpr(&p, &val2)) >= 0) { - if (exprDebug) - printf("parseExpr(%d) then %ld\n", pr, val2); + if (exprDebug) printf("parseExpr(%d) then %ld\n", pr, val2); if (parseSep(&p, ":")) { parseExpr(&p, &val3); - if (exprDebug) - printf("parseExpr(%d) else %ld\n", pr, val3); + if (exprDebug) printf("parseExpr(%d) else %ld\n", pr, val3); } } if (exprDebug) @@ -304,8 +285,7 @@ static int parseSubExpr(const char **pp, long *v, int pr, int o) { if (exprDebug) printf("parseExpr(%d): result %ld, o2=%d, rest \"%s\" \n", pr, val, o2, p); - if (o2 == -1) - goto nextop; + if (o2 == -1) goto nextop; } o = o2; } while (ops[o].pr && pr <= ops[o].pr); @@ -319,27 +299,21 @@ static int parseSubExpr(const char **pp, long *v, int pr, int o) { static const char *getFormat(const char **pp) { static char format[20]; const char *p = *pp; - unsigned int i = 1; - if (exprDebug) - printf("getFormat %s\n", p); + if (exprDebug) printf("getFormat %s\n", p); if ((format[0] = *p++) == '%') { - while (i < sizeof(format) && memchr(" #-+0", *p, 5)) - format[i++] = *p++; - while (i < sizeof(format) && *p >= '0' && *p <= '9') - format[i++] = *p++; - if (i < sizeof(format)) - format[i++] = 'l'; + unsigned int i = 1; + while (i < sizeof(format) && memchr(" #-+0", *p, 5)) format[i++] = *p++; + while (i < sizeof(format) && *p >= '0' && *p <= '9') format[i++] = *p++; + if (i < sizeof(format)) format[i++] = 'l'; if (i < sizeof(format) && memchr("diouxXc", *p, 7)) { format[i++] = *p++; - format[i] = 0; + format[i] = 0; // FIXME (alo): not our memory! *pp = p; - if (exprDebug) - printf("format = '%s'\n", format); + if (exprDebug) printf("format = '%s'\n", format); return format; } } - if (exprDebug) - printf("no format\n"); + if (exprDebug) printf("no format\n"); return NULL; } @@ -350,34 +324,28 @@ static int parseSlice(const char **pp, long *pstart, long *plength) { long string_length = *plength; char o; - if (*p++ != '[') - return 0; + if (*p++ != '[') return 0; parseExpr(&p, &slice_start); - if (slice_start < 0) - slice_start += string_length; - if ((o = parseSep(&p, ":,"))) /* [start,length] or [start:end] */ - { + if (slice_start < 0) slice_start += string_length; + if ((o = parseSep(&p, ":,"))) /* [start,length] or [start:end] */ { parseExpr(&p, &slice_length); if (o == ':') { - if (slice_length < 0) - slice_length += string_length; + if (slice_length < 0) slice_length += string_length; slice_length -= slice_start; } - } else + } else { slice_length = 1; + } if (slice_start < 0) { slice_length += slice_start; slice_start = 0; } - if (slice_start > string_length) - slice_length = 0; + if (slice_start > string_length) slice_length = 0; if (slice_length > string_length - slice_start) slice_length = string_length - slice_start; - if (slice_length < 0) - slice_length = 0; + if (slice_length < 0) slice_length = 0; skipSpace(p); - if (*p++ != ']') - return 0; + if (*p++ != ']') return 0; *pstart += slice_start; *plength = slice_length; *pp = p; @@ -392,24 +360,20 @@ static long parseString(const char **pp, const char **pstart) { char q; q = *p++; - while (*p) /* string length with escapes */ - { + while (*p) /* string length with escapes */ { if (*p == '\\') - if (*++p == 0) - break; - if (*p++ == q) - break; + if (*++p == 0) break; + if (*p++ == q) break; length++; } - while (parseSlice(&p, &slice_start, &length)) - ; + while (parseSlice(&p, &slice_start, &length)) { + } if (exprDebug) printf("parseString %.*s[%ld,%ld]\n", (int)(p - string_start), string_start, slice_start, length); if (length && pstart) { while (slice_start-- > 0) { - if (*string_start++ == '\\') - string_start++; + if (*string_start++ == '\\') string_start++; } *pstart = ++string_start; } @@ -421,8 +385,7 @@ static void writeString(char **pw, const char *r, long length, char q) { char *w = *pw; *w++ = q; while (length-- > 0) { - if (*r == '\\') - *w++ = *r++; + if (*r == '\\') *w++ = *r++; *w++ = *r++; } *w++ = q; @@ -445,14 +408,12 @@ size_t replaceExpressions(const char *r, char *buffer, size_t buffersize) { q = *r; string_length = parseString(&r, &string_start); writeString(&w, string_start, string_length, q); - if (exprDebug) - printf("quoted string %s\n", s); + if (exprDebug) printf("quoted string %s\n", s); } else if (*r == '%') { /* formatted expression */ const char *r2 = r; const char *f; - if (exprDebug) - printf("formatted expression after '%s'\n", s); + if (exprDebug) printf("formatted expression after '%s'\n", s); if ((f = getFormat(&r2)) && parseExpr(&r2, &val) >= 0) { r = r2; if (w > buffer && w[-1] == '(' && *r2++ == ')') { @@ -460,8 +421,7 @@ size_t replaceExpressions(const char *r, char *buffer, size_t buffersize) { r = r2; } w += sprintf(w, f, val); - if (exprDebug) - printf("formatted expression %s\n", s); + if (exprDebug) printf("formatted expression %s\n", s); } } else if (parseExpr(&r, &val) >= 0) { /* unformatted expression */ @@ -470,32 +430,26 @@ size_t replaceExpressions(const char *r, char *buffer, size_t buffersize) { w = s; r--; string_length = parseString(&r, &string_start); - if (val) - writeString(&w, string_start, string_length, q); + if (val) writeString(&w, string_start, string_length, q); if (parseSep(&r, ":")) { string_length = parseString(&r, &string_start); - if (!val) - writeString(&w, string_start, string_length, q); + if (!val) writeString(&w, string_start, string_length, q); } } else { w += sprintf(w, "%ld", val); } - if (exprDebug) - printf("expression %s\n", s); + if (exprDebug) printf("expression %s\n", s); } else { /* unquoted string (i.e plain word) */ do { if ((*w++ = *r++) == '\\') - if (*r) - *w++ = *r++; + if (*r) *w++ = *r++; } while (*r && !strchr("%(\"', \t\n", *r)); *w = 0; - if (exprDebug) - printf("plain word '%s'\n", s); + if (exprDebug) printf("plain word '%s'\n", s); } /* copy space */ - while (isspace((unsigned char)*r) || *r == ',') - *w++ = *r++; + while (isspace((unsigned char)*r) || *r == ',') *w++ = *r++; /* terminate */ *w = 0; } diff --git a/require-ess/src/expr.h b/require-ess/src/expr.h index 3924c3fdfe949b882b209a0ab907d8869d52f376..ecea81172d767cc25397e687b0baf93fb958738c 100644 --- a/require-ess/src/expr.h +++ b/require-ess/src/expr.h @@ -1,9 +1,13 @@ -#ifndef expr_h -#define expr_h +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#pragma once + +#include <stddef.h> #ifdef __cplusplus extern { -#endif +#endif // __cplusplus extern int exprDebug; @@ -18,5 +22,4 @@ extern { #ifdef __cplusplus } -#endif -#endif +#endif // __cplusplus diff --git a/require-ess/src/require.c b/require-ess/src/require.c index 42a31d8a261fd413afd73b71004d0b878aeba709..b0c178bd4211f25c88bd7d42e7e4ce223eeb1f69 100644 --- a/require-ess/src/require.c +++ b/require-ess/src/require.c @@ -1,3 +1,6 @@ +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + /* * ld - load code dynamically * @@ -12,25 +15,26 @@ /* for vasprintf and dl_iterate_phdr */ #ifndef _GNU_SOURCE #define _GNU_SOURCE -#endif -#endif +#endif // _GNU_SOURCE +#endif // __unix /* for 64 bit (NFS) file systems */ #define _FILE_OFFSET_BITS 64 +#include "require.h" + #include <ctype.h> +#include <dbAccess.h> #include <epicsVersion.h> #include <errno.h> #include <initHooks.h> +#include <iocsh.h> #include <osiFileName.h> #include <recSup.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> - -#include <dbAccess.h> -#include <iocsh.h> /* This prototype is missing in older EPICS versions */ DBCORE_API int epicsStdCall iocshCmd(const char *cmd); #include <epicsExit.h> @@ -38,7 +42,6 @@ DBCORE_API int epicsStdCall iocshCmd(const char *cmd); #include <epicsStdio.h> #include <osiFileName.h> -#include "require.h" #include "version.h" int requireDebug; @@ -48,32 +51,32 @@ int requireDebug; #ifndef OS_CLASS #ifdef __linux #define OS_CLASS "Linux" -#endif +#endif // __linux #ifdef SOLARIS #define OS_CLASS "solaris" -#endif +#endif // SOLARIS #ifdef __rtems__ #define OS_CLASS "RTEMS" -#endif +#endif // __rtems__ #ifdef CYGWIN32 #define OS_CLASS "cygwin32" -#endif +#endif // CYGWIN32 #ifdef freebsd #define OS_CLASS "freebsd" -#endif +#endif // freebsd #ifdef darwin #define OS_CLASS "Darwin" -#endif +#endif // darwin #ifdef _AIX32 #define OS_CLASS "AIX" -#endif -#endif +#endif // _AIX32 +#endif // OS_CLASS #include <dlfcn.h> #define HMODULE void * @@ -84,17 +87,17 @@ int requireDebug; #define PREFIX #define INFIX #define EXT ".dll" -#else +#else // CYGWIN32 #define PREFIX "lib" #define INFIX #define EXT ".so" -#endif +#endif // CYGWIN32 #elif defined(_WIN32) #ifndef OS_CLASS #define OS_CLASS "WIN32" -#endif +#endif // OS_CLASS #include <Psapi.h> #include <windows.h> @@ -115,17 +118,15 @@ static char *realpath(const char *path, char *buffer) { int len = MAX_PATH; if (buffer == NULL) { len = GetFullPathName(path, 0, NULL, NULL); - if (len == 0) - return NULL; + if (len == 0) return NULL; buffer = malloc(len); - if (buffer == NULL) - return NULL; + if (buffer == NULL) return NULL; } GetFullPathName(path, len, buffer, NULL); return buffer; } -#else +#else // defined(none) #warning unknown OS #define PREFIX @@ -133,68 +134,64 @@ static char *realpath(const char *path, char *buffer) { #define EXT #define getAddress(module, name) NULL -#endif +#endif // defined /* for readdir: Windows or Posix */ #if defined(_WIN32) #define DIR_HANDLE HANDLE #define DIR_ENTRY WIN32_FIND_DATA -#define IF_OPEN_DIR(f) \ - if (snprintf(f + modulediroffs, sizeof(f) - modulediroffs, "\\*.*"), \ - (dir = FindFirstFile(filename, &direntry)) != INVALID_HANDLE_VALUE || \ +#define IF_OPEN_DIR(f) \ + if (snprintf(f + modulediroffs, sizeof(f) - modulediroffs, "\\*.*"), \ + (dir = FindFirstFile(filename, &direntry)) != INVALID_HANDLE_VALUE || \ (FindClose(dir), 0)) #define START_DIR_LOOP do -#define END_DIR_LOOP \ - while (FindNextFile(dir, &direntry)) \ - ; \ +#define END_DIR_LOOP \ + while (FindNextFile(dir, &direntry)) \ + ; \ FindClose(dir); -#define SKIP_NON_DIR(e) \ - if (!(e.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || \ - (e.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) \ +#define SKIP_NON_DIR(e) \ + if (!(e.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || \ + (e.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) \ continue; #define FILENAME(e) e.cFileName -#else +#else // defined(_WIN32) #include <dirent.h> #define DIR_HANDLE DIR * #define IF_OPEN_DIR(f) if ((dir = opendir(f))) #define DIR_ENTRY struct dirent * #define START_DIR_LOOP while ((errno = 0, direntry = readdir(dir)) != NULL) -#define END_DIR_LOOP \ - if (!direntry && errno) \ - fprintf(stderr, "error reading directory %s: %s\n", filename, \ - strerror(errno)); \ - if (dir) \ - closedir(dir); +#define END_DIR_LOOP \ + if (!direntry && errno) \ + fprintf(stderr, "error reading directory %s: %s\n", filename, \ + strerror(errno)); \ + if (dir) closedir(dir); #ifdef _DIRENT_HAVE_D_TYPE -#define SKIP_NON_DIR(e) \ - if (e->d_type != DT_DIR && e->d_type != DT_UNKNOWN) \ - continue; -#else +#define SKIP_NON_DIR(e) \ + if (e->d_type != DT_DIR && e->d_type != DT_UNKNOWN) continue; +#else // _DIRENT_HAVE_D_TYPE #define SKIP_NON_DIR(e) -#endif +#endif // _DIRENT_HAVE_D_TYPE #define FILENAME(e) e->d_name -#endif +#endif // defined(_WIN32) #define LIBDIR "lib" OSI_PATH_SEPARATOR #define TEMPLATEDIR "db" -/* -#define TOSTR(s) TOSTR2(s) -#define TOSTR2(s) #s -const char epicsRelease[] = -TOSTR(EPICS_VERSION)"."TOSTR(EPICS_REVISION)"."TOSTR(EPICS_MODIFICATION); +// #define TOSTR(s) TOSTR2(s) +// #define TOSTR2(s) #s +// const char epicsRelease[] = +// TOSTR(EPICS_VERSION)"."TOSTR(EPICS_REVISION)"."TOSTR(EPICS_MODIFICATION); -#ifndef T_A -#error T_A not defined: Compile with USR_CFLAGS += -DT_A='"${T_A}"' -#endif -const char targetArch[] = T_A; - */ +// #ifndef T_A +// #error T_A not defined: Compile with USR_CFLAGS += -DT_A='"${T_A}"' +// #endif +// const char targetArch[] = T_A; #ifndef OS_CLASS #error OS_CLASS not defined: Try to compile with USR_CFLAGS += -DOS_CLASS='"${OS_CLASS}"' -#endif +#endif // OS_CLASS const char osClass[] = OS_CLASS; @@ -261,8 +258,7 @@ int putenvprintf(const char *format, ...) { char *val; int status = 0; - if (!format) - return -1; + if (!format) return -1; va_start(ap, format); if (vasprintf(&var, format, ap) < 0) { perror("require putenvprintf"); @@ -270,8 +266,7 @@ int putenvprintf(const char *format, ...) { } va_end(ap); - if (requireDebug) - printf("require: putenv(\"%s\")\n", var); + if (requireDebug) printf("require: putenv(\"%s\")\n", var); val = strchr(var, '='); if (!val) { @@ -293,17 +288,18 @@ void pathAdd(const char *varname, const char *dirname) { if (!varname || !dirname) { fprintf(stderr, "usage: pathAdd \"ENVIRONMENT_VARIABLE\",\"directory\"\n"); - fprintf(stderr, " Adds or moves the directory to the front of the " - "ENVIRONMENT_VARIABLE\n"); + fprintf(stderr, + " Adds or moves the directory to the front of the " + "ENVIRONMENT_VARIABLE\n"); fprintf(stderr, " but after a leading \".\".\n"); return; } /* add directory to front */ old_path = getenv(varname); - if (old_path == NULL) + if (old_path == NULL) { putenvprintf("%s=." OSI_PATH_LIST_SEPARATOR "%s", varname, dirname); - else { + } else { size_t len = strlen(dirname); char *p; @@ -316,8 +312,7 @@ void pathAdd(const char *varname, const char *dirname) { while ((p = strstr(p, dirname)) != NULL) { if ((p == old_path || *(p - 1) == OSI_PATH_LIST_SEPARATOR[0]) && (p[len] == 0 || p[len] == OSI_PATH_LIST_SEPARATOR[0])) { - if (p == old_path) - break; /* already at front, nothing to do */ + if (p == old_path) break; /* already at front, nothing to do */ memmove(old_path + len + 1, old_path, p - old_path - 1); strcpy(old_path, dirname); old_path[len] = OSI_PATH_LIST_SEPARATOR[0]; @@ -327,8 +322,7 @@ void pathAdd(const char *varname, const char *dirname) { } p += len; } - if (p == NULL) - /* add new directory to the front (after "." )*/ + if (p == NULL) /* add new directory to the front (after "." )*/ putenvprintf("%s=." OSI_PATH_LIST_SEPARATOR "%s" OSI_PATH_LIST_SEPARATOR "%s", varname, dirname, old_path); @@ -340,8 +334,7 @@ char *realpathSeparator(const char *location) { char *buffer = malloc(PATH_MAX + strlen(OSI_PATH_SEPARATOR)); buffer = realpath(location, buffer); if (!buffer) { - if (requireDebug) - printf("require: realpath(%s) failed\n", location); + if (requireDebug) printf("require: realpath(%s) failed\n", location); return NULL; } ll = strlen(buffer); @@ -358,13 +351,11 @@ static int setupDbPath(const char *module, const char *dbdir) { char *absdir = realpathSeparator(dbdir); /* so we can change directory later safely */ if (absdir == NULL) { - if (requireDebug) - printf("require: cannot resolve %s\n", dbdir); + if (requireDebug) printf("require: cannot resolve %s\n", dbdir); return -1; } - if (requireDebug) - printf("require: found template directory %s\n", absdir); + if (requireDebug) printf("require: found template directory %s\n", absdir); /* set up db search path environment variables <module>_DB template path of <module> @@ -437,17 +428,15 @@ must wait until initHooks is loaded before we can register the hook. */ static void fillModuleListRecord(initHookState state) { - if (state == initHookAfterFinishDevSup) /* MODULES record exists and has - allocated memory */ - { + /* MODULES record exists and has allocated memory */ + if (state == initHookAfterFinishDevSup) { DBADDR modules, versions, modver; int have_modules, have_versions, have_modver; moduleitem *m; int i = 0; long c = 0; - if (requireDebug) - printf("require: fillModuleListRecord\n"); + if (requireDebug) printf("require: fillModuleListRecord\n"); have_modules = (getRecordHandle(":MODULES", DBF_STRING, moduleCount, &modules) == 0); @@ -482,12 +471,9 @@ static void fillModuleListRecord(initHookState state) { (int)maxModuleNameLength, m->content, m->content + lm); } } - if (have_modules) - dbGetRset(&modules)->put_array_info(&modules, i); - if (have_versions) - dbGetRset(&versions)->put_array_info(&versions, i); - if (have_modver) - dbGetRset(&modver)->put_array_info(&modver, c + 1); + if (have_modules) dbGetRset(&modules)->put_array_info(&modules, i); + if (have_versions) dbGetRset(&versions)->put_array_info(&versions, i); + if (have_modver) dbGetRset(&modver)->put_array_info(&modver, c + 1); } } @@ -508,13 +494,11 @@ void registerModule(const char *module, const char *version, if (firstTime) { initHookRegister(fillModuleListRecord); - if (requireDebug) - printf("require: initHookRegister\n"); + if (requireDebug) printf("require: initHookRegister\n"); firstTime = 0; } - if (!version) - version = ""; + if (!version) version = ""; if (location) { absLocation = realpathSeparator(location); @@ -533,11 +517,10 @@ void registerModule(const char *module, const char *version, strcpy(m->content + lm + lv, absLocation ? absLocation : ""); free(absLocation); - for (pm = &loadedModules; *pm != NULL; pm = &(*pm)->next) - ; + for (pm = &loadedModules; *pm != NULL; pm = &(*pm)->next) { + } *pm = m; - if (lm > maxModuleNameLength) - maxModuleNameLength = lm; + if (lm > maxModuleNameLength) maxModuleNameLength = lm; moduleListBufferSize += lv; moduleCount++; @@ -549,13 +532,11 @@ void registerModule(const char *module, const char *version, } /* only do registration register stuff at init */ - if (interruptAccept) - return; + if (interruptAccept) return; /* create a record with the version string */ mylocation = getenv("require_DIR"); - if (mylocation == NULL) - return; + if (mylocation == NULL) return; if (asprintf(&absLocationRequire, "%s" OSI_PATH_SEPARATOR "db" OSI_PATH_SEPARATOR "moduleversion.template", @@ -596,29 +577,34 @@ static int findLibRelease(struct dl_phdr_info *info, /* shared library info */ char *p; char *version; char *symname; - char name[PATH_MAX + 11]; /* get space for library path + "LibRelease" */ + /* get space for library path + "LibRelease" */ + char name[PATH_MAX + 11]; (void)data; /* unused */ if (size < sizeof(struct dl_phdr_info)) return 0; /* wrong version of struct dl_phdr_info */ + /* find a symbol with a name like "_<module>LibRelease" where <module> is from the library name "<location>/lib<module>.so" */ - if (info->dlpi_name == NULL || info->dlpi_name[0] == 0) - return 0; /* no library name */ - strcpy(name, info->dlpi_name); /* get a modifiable copy of the library name */ - handle = - dlopen(info->dlpi_name, RTLD_LAZY); /* re-open already loaded library */ - p = strrchr(name, - '/'); /* find file name part in "<location>/lib<module>.so" */ + + /* no library name */ + if (info->dlpi_name == NULL || info->dlpi_name[0] == 0) return 0; + /* get a modifiable copy of the library name */ + strcpy(name, info->dlpi_name); + /* re-open already loaded library */ + handle = dlopen(info->dlpi_name, RTLD_LAZY); + /* find file name part in "<location>/lib<module>.so" */ + p = strrchr(name, '/'); if (p) { location = name; *++p = 0; - } else - p = name; /* terminate "<location>/" (if exists) */ - *(symname = p + 2) = '_'; /* replace "lib" with "_" */ - p = strchr(symname, '.'); /* find ".so" extension */ - if (p == NULL) - p = symname + strlen(symname); /* no file extension ? */ + } else { + /* terminate "<location>/" (if exists) */ + p = name; + } + *(symname = p + 2) = '_'; /* replace "lib" with "_" */ + p = strchr(symname, '.'); /* find ".so" extension */ + if (p == NULL) p = symname + strlen(symname); /* no file extension ? */ strcpy(p, "LibRelease"); /* append "LibRelease" to module name */ version = dlsym(handle, symname); /* find symbol "_<module>LibRelease" */ if (version) { @@ -649,28 +635,30 @@ static void registerExternalModules() { char *version; char *symname; unsigned int i; - char name[MAX_PATH + 11]; /* get space for library path + "LibRelease" */ + /* get space for library path + "LibRelease" */ + char name[MAX_PATH + 11]; /* iterate over all loaded libraries */ - if (!EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) - return; + if (!EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) return; for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { /* Get the full path to the module's file. */ if (!GetModuleFileName(hMods[i], name, MAX_PATH)) continue; /* no library name */ name[sizeof(name) - 1] = 0; /* WinXP may not terminate the string */ - p = strrchr(name, - '\\'); /* find file name part in "<location>/<module>.dll" */ + + /* find file name part in "<location>/<module>.dll" */ + p = strrchr(name, '\\'); if (p) { location = name; - } else - p = name; /* find end of "<location>\\" (if exists) */ + } else { + /* find end of "<location>\\" (if exists) */ + p = name; + } symname = p; - p = strchr(symname, '.'); /* find ".dll" */ - if (p == NULL) - p = symname + strlen(symname); /* no file extension ? */ - memmove(symname + 2, symname, p - symname); /* make room for 0 and '_' */ - *symname++ = 0; /* terminate "<location>/" */ + p = strchr(symname, '.'); /* find ".dll" */ + if (p == NULL) p = symname + strlen(symname); /* no file extension ? */ + memmove(symname + 2, symname, p - symname); /* make room for 0 and '_' */ + *symname++ = 0; /* terminate "<location>/" */ *symname = '_'; /* prefix module name with '_' */ strcpy((p += 2), "LibRelease"); /* append "LibRelease" to module name */ @@ -702,8 +690,7 @@ size_t foreachLoadedLib(size_t (*func)(const char *name, const char *version, const char *version = name + strlen(name) + 1; const char *path = version + strlen(version) + 1; result = func(name, version, path, arg); - if (result) - return result; + if (result) return result; } return 0; } @@ -736,8 +723,7 @@ int isModuleLoaded(const char *libname) { moduleitem *m; for (m = loadedModules; m; m = m->next) { - if (strcmp(m->content, libname) == 0) - return TRUE; + if (strcmp(m->content, libname) == 0) return TRUE; } return FALSE; } @@ -765,8 +751,7 @@ int libversionShow(const char *outfile) { fprintf(stderr, "can't write to %s: %s\n", outfile, strerror(errno)); return -1; } - if (outfile) - fclose(out); + if (outfile) fclose(out); return 0; } @@ -776,9 +761,8 @@ int libversionShow(const char *outfile) { #define TESTVERS 2 #define HIGHER 3 -#define debug(...) \ - if (requireDebug) \ - printf(__VA_ARGS__) +#define debug(...) \ + if (requireDebug) printf(__VA_ARGS__) static int compareDigit(int found, int requested, const char *name) { debug("require: compareDigit: found %d, requested %d for digit %s\n", found, @@ -814,12 +798,14 @@ static int compareNumericVersion(semver_t *sv_found, semver_t *sv_request, if (sv_request->build == -1) { if (already_matched) { - debug("require: compareVersions: No build number requested. Returning " - "HIGHER\n"); + debug( + "require: compareVersions: No build number requested. Returning " + "HIGHER\n"); return HIGHER; } else { - debug("require: compareVersions: No build number requested. Returning " - "MATCH\n"); + debug( + "require: compareVersions: No build number requested. Returning " + "MATCH\n"); return MATCH; } } @@ -854,21 +840,25 @@ static int compareVersions(const char *found, const char *request, // test version, look for exact. if (strlen(sv_request->test_str) > 0) { if (strcmp(found, request) == 0) { - debug("require: compareVersions: Test version requested and found, " - "matches exactly\n"); + debug( + "require: compareVersions: Test version requested and found, " + "matches exactly\n"); match = EXACT; } else if (strlen(sv_found->test_str) > 0) { - debug("require: compareVersions: Test versions requested and found, no " - "match\n"); + debug( + "require: compareVersions: Test versions requested and found, no " + "match\n"); match = MISMATCH; } else { - debug("require: compareVersions: found numeric version, higher than " - "test\n"); + debug( + "require: compareVersions: found numeric version, higher than " + "test\n"); match = HIGHER; } } else if (strlen(sv_found->test_str) > 0) { - debug("require: compareVersions: Numeric version requested, test version " - "found\n"); + debug( + "require: compareVersions: Numeric version requested, test version " + "found\n"); match = MISMATCH; } else { match = compareNumericVersion(sv_found, sv_request, already_matched); @@ -910,8 +900,9 @@ int require(const char *module, const char *version, const char *args) { } if (module == NULL) { - printf("Usage: require \"<module>\" [, \"<version>\" | \"ifexists\"] [, " - "\"<args>\"]\n"); + printf( + "Usage: require \"<module>\" [, \"<version>\" | \"ifexists\"] [, " + "\"<args>\"]\n"); printf("Loads " PREFIX "<module>" INFIX EXT " and <libname>.dbd\n"); printf("And calls <module>_registerRecordDeviceDriver\n"); printf("If available, runs startup script snippet (only before iocInit)\n"); @@ -928,23 +919,19 @@ int require(const char *module, const char *version, const char *args) { const char *v = version; version = args; args = v; - if (requireDebug) - printf("require: swap version and args\n"); + if (requireDebug) printf("require: swap version and args\n"); } - if (version && version[0] == 0) - version = NULL; + if (version && version[0] == 0) version = NULL; if (version && strcmp(version, "none") == 0) { - if (requireDebug) - printf("require: skip version=none\n"); + if (requireDebug) printf("require: skip version=none\n"); return 0; } if (version) { /* needed for old style only: */ - if (asprintf(&versionstr, "-%s", version) < 0) - return errno; + if (asprintf(&versionstr, "-%s", version) < 0) return errno; if (isdigit((unsigned char)version[0]) && version[strlen(version) - 1] == '+') { /* @@ -952,26 +939,21 @@ int require(const char *module, const char *version, const char *args) { load highest matching version (here "1.2") and check later */ char *p = strrchr(versionstr, '.'); - if (p == NULL) - p = versionstr; + if (p == NULL) p = versionstr; *p = 0; } - } else + } else { versionstr = ""; - if (requireDebug) - printf("require: versionstr = \"%s\"\n", versionstr); + } + if (requireDebug) printf("require: versionstr = \"%s\"\n", versionstr); status = require_priv(module, version, args, versionstr); - if (version) - free(versionstr); + if (version) free(versionstr); - if (status == 0) - return 0; - if (status != -1) - perror("require"); - if (interruptAccept) - return status; + if (status == 0) return 0; + if (status != -1) perror("require"); + if (interruptAccept) return status; /* require failed in startup script before iocInit */ fprintf(stderr, "Aborting startup script\n"); @@ -982,48 +964,42 @@ int require(const char *module, const char *version, const char *args) { static off_t fileSize(const char *filename) { struct stat filestat; if (stat(filename, &filestat) != 0) { - if (requireDebug) - printf("require: %s does not exist\n", filename); + if (requireDebug) printf("require: %s does not exist\n", filename); return -1; } switch (filestat.st_mode & S_IFMT) { - case S_IFREG: - if (requireDebug) - printf("require: file %s exists, size %lld bytes\n", filename, - (unsigned long long)filestat.st_size); - return filestat.st_size; - case S_IFDIR: - if (requireDebug) - printf("require: directory %s exists\n", filename); - return 0; + case S_IFREG: + if (requireDebug) + printf("require: file %s exists, size %lld bytes\n", filename, + (unsigned long long)filestat.st_size); + return filestat.st_size; + case S_IFDIR: + if (requireDebug) printf("require: directory %s exists\n", filename); + return 0; #ifdef S_IFBLK - case S_IFBLK: - if (requireDebug) - printf("require: %s is a block device\n", filename); - return -1; + case S_IFBLK: + if (requireDebug) printf("require: %s is a block device\n", filename); + return -1; #endif #ifdef S_IFCHR - case S_IFCHR: - if (requireDebug) - printf("require: %s is a character device\n", filename); - return -1; + case S_IFCHR: + if (requireDebug) printf("require: %s is a character device\n", filename); + return -1; #endif #ifdef S_IFIFO - case S_IFIFO: - if (requireDebug) - printf("require: %s is a FIFO/pipe\n", filename); - return -1; + case S_IFIFO: + if (requireDebug) printf("require: %s is a FIFO/pipe\n", filename); + return -1; #endif #ifdef S_IFSOCK - case S_IFSOCK: - if (requireDebug) - printf("require: %s is a socket\n", filename); - return -1; + case S_IFSOCK: + if (requireDebug) printf("require: %s is a socket\n", filename); + return -1; #endif - default: - if (requireDebug) - printf("require: %s is an unknown type of special file\n", filename); - return -1; + default: + if (requireDebug) + printf("require: %s is an unknown type of special file\n", filename); + return -1; } } #define fileExists(filename) (fileSize(filename) >= 0) @@ -1042,28 +1018,23 @@ static int handleDependencies(const char *module, char *depfilename) { while (fgets(buffer, sizeof(buffer) - 1, depfile)) { rmodule = buffer; /* ignore leading spaces */ - while (isspace((unsigned char)*rmodule)) - rmodule++; + while (isspace((unsigned char)*rmodule)) rmodule++; /* ignore empty lines and comment lines */ - if (*rmodule == 0 || *rmodule == '#') - continue; + if (*rmodule == 0 || *rmodule == '#') continue; /* rmodule at start of module name */ rversion = rmodule; /* find end of module name */ - while (*rversion && !isspace((unsigned char)*rversion)) - rversion++; + while (*rversion && !isspace((unsigned char)*rversion)) rversion++; /* terminate module name */ *rversion++ = 0; /* ignore spaces */ - while (isspace((unsigned char)*rversion)) - rversion++; + while (isspace((unsigned char)*rversion)) rversion++; /* rversion at start of version */ if (*rversion) { end = rversion; /* find end of version */ - while (*end && !isspace((unsigned char)*end)) - end++; + while (*end && !isspace((unsigned char)*end)) end++; /* add + to numerial versions if not yet there */ /* @@ -1089,9 +1060,9 @@ static int handleDependencies(const char *module, char *depfilename) { return 0; } -static int -require_priv(const char *module, const char *version, const char *args, - const char *versionstr /* "-<version>" or "" (for old style only */ +static int require_priv( + const char *module, const char *version, const char *args, + const char *versionstr /* "-<version>" or "" (for old style only */ ) { int status; const char *loaded = NULL; @@ -1119,20 +1090,20 @@ require_priv(const char *module, const char *version, const char *args, version, args); #if defined __GNUC__ && __GNUC__ < 3 -#define TRY_FILE(offs, args...) \ - (snprintf(filename + offs, sizeof(filename) - offs, args) && \ +#define TRY_FILE(offs, args...) \ + (snprintf(filename + offs, sizeof(filename) - offs, args) && \ fileExists(filename)) -#define TRY_NONEMPTY_FILE(offs, args...) \ - (snprintf(filename + offs, sizeof(filename) - offs, args) && \ +#define TRY_NONEMPTY_FILE(offs, args...) \ + (snprintf(filename + offs, sizeof(filename) - offs, args) && \ fileNotEmpty(filename)) #else -#define TRY_FILE(offs, ...) \ - (snprintf(filename + offs, sizeof(filename) - offs, __VA_ARGS__) && \ +#define TRY_FILE(offs, ...) \ + (snprintf(filename + offs, sizeof(filename) - offs, __VA_ARGS__) && \ fileExists(filename)) -#define TRY_NONEMPTY_FILE(offs, ...) \ - (snprintf(filename + offs, sizeof(filename) - offs, __VA_ARGS__) && \ +#define TRY_NONEMPTY_FILE(offs, ...) \ + (snprintf(filename + offs, sizeof(filename) - offs, __VA_ARGS__) && \ fileNotEmpty(filename)) #endif @@ -1144,14 +1115,11 @@ require_priv(const char *module, const char *version, const char *args, driverpath = getenv("EPICS_DRIVER_PATH"); if (!globalTemplates) { char *t = getenv("TEMPLATES"); - if (t) - globalTemplates = strdup(t); + if (t) globalTemplates = strdup(t); } - if (driverpath == NULL) - driverpath = "."; - if (requireDebug) - printf("require: searchpath=%s\n", driverpath); + if (driverpath == NULL) driverpath = "."; + if (requireDebug) printf("require: searchpath=%s\n", driverpath); if (version && strcmp(version, "ifexists") == 0) { ifexists = 1; @@ -1164,32 +1132,31 @@ require_priv(const char *module, const char *version, const char *args, if (loaded) { /* Library already loaded. Check Version. */ switch (compareVersions(loaded, version, FALSE)) { - case TESTVERS: - if (version) - printf("Warning: Module %s test version %s already loaded where %s was " - "requested\n", - module, loaded, version); - case EXACT: - case MATCH: - printf("Module %s version %s already loaded\n", module, loaded); - break; - default: - printf("Conflict between requested %s version %s and already loaded " - "version %s.\n", - module, version, loaded); - return -1; + case TESTVERS: + if (version) + printf( + "Warning: Module %s test version %s already loaded where %s was " + "requested\n", + module, loaded, version); + case EXACT: + case MATCH: + printf("Module %s version %s already loaded\n", module, loaded); + break; + default: + printf( + "Conflict between requested %s version %s and already loaded " + "version %s.\n", + module, version, loaded); + return -1; } dirname = getLibLocation(module); - if (dirname[0] == 0) - return 0; - if (requireDebug) - printf("require: library found in %s\n", dirname); + if (dirname[0] == 0) return 0; + if (requireDebug) printf("require: library found in %s\n", dirname); snprintf(filename, sizeof(filename), "%s%n", dirname, &releasediroffs); putenvprintf("MODULE=%s", module); pathAdd("SCRIPT_PATH", dirname); } else { - if (requireDebug) - printf("require: no %s version loaded yet\n", module); + if (requireDebug) printf("require: no %s version loaded yet\n", module); /* Search for module in driverpath */ for (dirname = driverpath; dirname != NULL; dirname = end) { @@ -1207,11 +1174,9 @@ require_priv(const char *module, const char *version, const char *args, dirlen = (int)(end++ - dirname); else dirlen = (int)strlen(dirname); - if (dirlen == 0) - continue; /* ignore empty driverpath elements */ + if (dirlen == 0) continue; /* ignore empty driverpath elements */ - if (requireDebug) - printf("require: trying %.*s\n", dirlen, dirname); + if (requireDebug) printf("require: trying %.*s\n", dirlen, dirname); snprintf(filename, sizeof(filename), "%.*s" OSI_PATH_SEPARATOR "%s" OSI_PATH_SEPARATOR "%n", dirlen, @@ -1221,8 +1186,7 @@ require_priv(const char *module, const char *version, const char *args, /* Does the module directory exist? */ IF_OPEN_DIR(filename) { - if (requireDebug) - printf("require: found directory %s\n", filename); + if (requireDebug) printf("require: found directory %s\n", filename); /* Now look for versions. */ START_DIR_LOOP { @@ -1240,68 +1204,68 @@ require_priv(const char *module, const char *version, const char *args, currentFilename, version); switch ((status = compareVersions(currentFilename, version, FALSE))) { - case TESTVERS: /* test version found */ - case EXACT: /* exact match found */ - case MATCH: /* all given numbers match. */ - { - someArchFound = 1; - - if (requireDebug) - printf("require: %s %s may match %s\n", module, currentFilename, - version); - - /* Check if it has our EPICS version and architecture. */ - /* Even if it has no library, at least it has a dep file in the lib - * dir */ - - /* Step 1 : library file location */ - /* filename = "<dirname>/[dirlen]<module>/[modulediroffs]" */ - if (!TRY_FILE(modulediroffs, - "%s" OSI_PATH_SEPARATOR LIBDIR - "%s" OSI_PATH_SEPARATOR, - currentFilename, targetArch)) - /* filename = - "<dirname>/[dirlen]<module>/[modulediroffs]<version>/lib/<targetArch>/" - */ + case TESTVERS: /* test version found */ + case EXACT: /* exact match found */ + case MATCH: /* all given numbers match. */ { + someArchFound = 1; + + if (requireDebug) + printf("require: %s %s may match %s\n", module, currentFilename, + version); + + /* Check if it has our EPICS version and architecture. */ + /* Even if it has no library, at least it has a dep file in the + * lib dir */ + + /* Step 1 : library file location */ + /* filename = "<dirname>/[dirlen]<module>/[modulediroffs]" */ + if (!TRY_FILE(modulediroffs, + "%s" OSI_PATH_SEPARATOR LIBDIR + "%s" OSI_PATH_SEPARATOR, + currentFilename, targetArch)) { + /* filename = + * "<dirname>/[dirlen]<module>/[modulediroffs]<version>/lib/<targetArch>/" + */ + if (requireDebug) + printf("require: %s %s has no support for %s %s\n", module, + currentFilename, epicsRelease, targetArch); + continue; + } + + if (status == EXACT) { + if (requireDebug) + printf("require: %s %s matches %s exactly\n", module, + currentFilename, version); + /* We are done. */ + end = NULL; + break; + } + + /* Is it higher than the one we found before? */ + if (found && requireDebug) + printf( + "require: %s %s support for %s %s found, compare against " + "previously found %s\n", + module, currentFilename, epicsRelease, targetArch, found); + if (!found || + compareVersions(currentFilename, found, TRUE) == HIGHER) { + if (requireDebug) + printf("require: %s %s looks promising\n", module, + currentFilename); + break; + } if (requireDebug) - printf("require: %s %s has no support for %s %s\n", module, - currentFilename, epicsRelease, targetArch); + printf("require: version %s is lower than %s \n", + currentFilename, found); continue; } - - if (status == EXACT) { + default: { if (requireDebug) - printf("require: %s %s matches %s exactly\n", module, + printf("require: %s %s does not match %s\n", module, currentFilename, version); - /* We are done. */ - end = NULL; - break; - } - - /* Is it higher than the one we found before? */ - if (found && requireDebug) - printf("require: %s %s support for %s %s found, compare against " - "previously found %s\n", - module, currentFilename, epicsRelease, targetArch, found); - if (!found || - compareVersions(currentFilename, found, TRUE) == HIGHER) { - if (requireDebug) - printf("require: %s %s looks promising\n", module, - currentFilename); - break; + continue; } - if (requireDebug) - printf("require: version %s is lower than %s \n", currentFilename, - found); - continue; - } - default: { - if (requireDebug) - printf("require: %s %s does not match %s\n", module, - currentFilename, version); - continue; - } } /* we have found something (EXACT or MATCH) */ free(founddir); @@ -1311,28 +1275,24 @@ require_priv(const char *module, const char *version, const char *args, return errno; /* founddir = "<dirname>/[dirlen]<module>/[modulediroffs]<version>" */ found = founddir + modulediroffs; /* version part in the path */ - if (status == EXACT) - break; + if (status == EXACT) break; } END_DIR_LOOP } else { /* filename = "<dirname>/[dirlen]<module>/" */ - if (requireDebug) - printf("require: no %s directory\n", filename); + if (requireDebug) printf("require: no %s directory\n", filename); /* try local/old style module only if no new style candidate has been * found */ if (!found) { /* look for dep file */ releasediroffs = libdiroffs = dirlen; - if (TRY_FILE(dirlen, "%s%s.dep", module, versionstr)) - /* filename = - "<dirname>/[dirlen][releasediroffs][libdiroffs]<module>(-<version>)?.dep" - */ - { - if (requireDebug) - printf("require: found old style %s\n", filename); + if (TRY_FILE(dirlen, "%s%s.dep", module, versionstr)) { + /* filename = + "<dirname>/[dirlen][releasediroffs][libdiroffs]<module>(-<version>)?.dep" + */ + if (requireDebug) printf("require: found old style %s\n", filename); printf("Module %s%s found in %.*s\n", module, versionstr, dirlen, filename); goto checkdep; @@ -1345,8 +1305,7 @@ require_priv(const char *module, const char *version, const char *args, "<dirname>/[dirlen][releasediroffs][libdiroffs]PREFIX<module>INFIX(-<version>)?[extoffs]EXT" */ ) { - if (requireDebug) - printf("require: found old style %s\n", filename); + if (requireDebug) printf("require: found old style %s\n", filename); printf("Module %s%s found in %.*s\n", module, versionstr, dirlen, filename); goto loadlib; @@ -1383,17 +1342,15 @@ require_priv(const char *module, const char *version, const char *args, found, founddir); /* Step 2 : Looking for Dep file */ - if (requireDebug) - printf("require: looking for dependency file\n"); + if (requireDebug) printf("require: looking for dependency file\n"); if (!TRY_FILE(0, "%s" OSI_PATH_SEPARATOR "%n" LIBDIR "%s" OSI_PATH_SEPARATOR "%n%s.dep", - founddir, &releasediroffs, targetArch, &libdiroffs, module)) - /* filename = - "<dirname>/[dirlen]<module>/<version>/R<epicsRelease>/[releasediroffs]/lib/<targetArch>/[libdiroffs]/module.dep" - */ - { + founddir, &releasediroffs, targetArch, &libdiroffs, module)) { + /* filename = + "<dirname>/[dirlen]<module>/<version>/R<epicsRelease>/[releasediroffs]/lib/<targetArch>/[libdiroffs]/module.dep" + */ fprintf(stderr, "Dependency file %s not found\n", filename); } else { checkdep: @@ -1403,22 +1360,19 @@ require_priv(const char *module, const char *version, const char *args, /* or (old) * "<dirname>/[dirlen]][releasediroffs][libdiroffs]<module>(-<version>)?.dep" */ - if (handleDependencies(module, filename) == -1) - return -1; + if (handleDependencies(module, filename) == -1) return -1; } - if (requireDebug) - printf("require: looking for library file\n"); + if (requireDebug) printf("require: looking for library file\n"); if (!(TRY_FILE(libdiroffs, PREFIX "%s" INFIX "%s%n" EXT, module, versionstr, - &extoffs))) - /* filename = - "<dirname>/[dirlen]<module>/<version>/R<epicsRelease>/[releasediroffs]/lib/<targetArch>/[libdiroffs]/PREFIX<module>INFIX[extoffs](EXT)?" - */ - /* or (old) - "<dirname>/[dirlen][releasediroffs][libdiroffs]PREFIX<module>INFIX(-<version>)?[extoffs](EXT)?" - */ - { + &extoffs))) { + /* filename = + "<dirname>/[dirlen]<module>/<version>/R<epicsRelease>/[releasediroffs]/lib/<targetArch>/[libdiroffs]/PREFIX<module>INFIX[extoffs](EXT)?" + */ + /* or (old) + "<dirname>/[dirlen][releasediroffs][libdiroffs]PREFIX<module>INFIX(-<version>)?[extoffs](EXT)?" + */ printf("Module %s has no library\n", module); } else { loadlib: @@ -1429,13 +1383,11 @@ require_priv(const char *module, const char *version, const char *args, * "<dirname>/[dirlen][releasediroffs][libdiroffs]PREFIX<module>INFIX(-<version>)?[extoffs]EXT" */ printf("Loading library %s\n", filename); - if ((libhandle = loadlib(filename)) == NULL) - return -1; + if ((libhandle = loadlib(filename)) == NULL) return -1; /* now check what version we really got (with compiled-in version number) */ - if (asprintf(&symbolname, "_%sLibRelease", module) < 0) - return errno; + if (asprintf(&symbolname, "_%sLibRelease", module) < 0) return errno; found = (const char *)getAddress(libhandle, symbolname); free(symbolname); @@ -1465,8 +1417,7 @@ require_priv(const char *module, const char *version, const char *args, TRY_NONEMPTY_FILE(releasediroffs, ".." OSI_PATH_SEPARATOR ".." OSI_PATH_SEPARATOR "dbd" OSI_PATH_SEPARATOR "%s.dbd", - module)) /* org EPICSbase */ - { + module)) /* org EPICSbase */ { printf("Loading dbd file %s\n", filename); if (dbLoadDatabase(filename, NULL, NULL) != 0) { fprintf(stderr, "Error loading %s\n", filename); @@ -1492,8 +1443,7 @@ require_priv(const char *module, const char *version, const char *args, status = 0; - if (requireDebug) - printf("require: looking for template directory\n"); + if (requireDebug) printf("require: looking for template directory\n"); /* filename = * "<dirname>/[dirlen]<module>/<version>/R<epicsRelease>/[releasediroffs]..." */ @@ -1507,9 +1457,10 @@ require_priv(const char *module, const char *version, const char *args, putenvprintf("TEMPLATES=%s", globalTemplates); } - if (loaded && args == NULL) - return 0; /* no need to execute startup script twice if not with new - arguments */ + /* no need to execute startup script twice if not with new arguments */ + if (loaded && args == NULL) { + return 0; + } return status; } diff --git a/require-ess/src/require.h b/require-ess/src/require.h index 59224c9f3ff1a410a3d3c4d4442557ccd1935e91..e961d02df192e06d1e2e5297506570c40844f0a5 100644 --- a/require-ess/src/require.h +++ b/require-ess/src/require.h @@ -1,13 +1,17 @@ -#ifndef require_h -#define require_h +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#pragma once + +#include <stddef.h> #ifdef __cplusplus extern "C" { -#endif +#endif // __cplusplus #ifndef __GNUC__ #define __attribute__(dummy) -#endif +#endif // __GNUC__ int require(const char *libname, const char *version, const char *args); size_t foreachLoadedLib(size_t (*func)(const char *name, const char *version, @@ -23,6 +27,4 @@ void pathAdd(const char *varname, const char *dirname); #ifdef __cplusplus } -#endif - -#endif +#endif // __cplusplus diff --git a/require-ess/src/runScript.c b/require-ess/src/runScript.c index 191e71d1a14ec141a796bd77e0be50734f86720a..69e2329749ecbd2103bf5c1289be8652b72915c3 100644 --- a/require-ess/src/runScript.c +++ b/require-ess/src/runScript.c @@ -1,6 +1,10 @@ +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif + #include <ctype.h> #include <dbAccess.h> #include <epicsVersion.h> @@ -12,7 +16,7 @@ #include <stdlib.h> #include <string.h> -#define EPICSVER \ +#define EPICSVER \ EPICS_VERSION * 10000 + EPICS_REVISION * 100 + EPICS_MODIFICATION #if defined(_WIN32) @@ -24,24 +28,23 @@ DBCORE_API int epicsStdCall iocshCmd(const char *cmd); #include <epicsExport.h> -#define IS_ABS_PATH(filename) \ +#define IS_ABS_PATH(filename) \ (filename[0] == OSI_PATH_SEPARATOR[0]) /* may be different for other OS ? */ #include "expr.h" #include "require.h" -#define SAVEENV(var) \ - do { \ - old_##var = getenv(#var); \ - if (old_##var) \ - old_##var = strdup(old_##var); \ +#define SAVEENV(var) \ + do { \ + old_##var = getenv(#var); \ + if (old_##var) old_##var = strdup(old_##var); \ } while (0) -#define RESTOREENV(var) \ - do { \ - if (old_##var) { \ - putenvprintf("%s=%s", #var, old_##var); \ - free(old_##var); \ - } \ +#define RESTOREENV(var) \ + do { \ + if (old_##var) { \ + putenvprintf("%s=%s", #var, old_##var); \ + free(old_##var); \ + } \ } while (0) int runScriptDebug = 0; @@ -68,15 +71,12 @@ int runScript(const char *filename, const char *args) { goto error; macSuppressWarning(mac, 1); - if ((line_exp = malloc(line_exp_size)) == NULL) - goto error; - if ((line_raw = malloc(line_raw_size)) == NULL) - goto error; + if ((line_exp = malloc(line_exp_size)) == NULL) goto error; + if ((line_raw = malloc(line_raw_size)) == NULL) goto error; /* add args to macro definitions */ if (args) { - if (runScriptDebug) - printf("runScript: macParseDefns \"%s\"\n", args); + if (runScriptDebug) printf("runScript: macParseDefns \"%s\"\n", args); macParseDefns(mac, (char *)args, &pairs); macInstallMacros(mac, pairs); free(pairs); @@ -100,20 +100,15 @@ int runScript(const char *filename, const char *args) { dirlen = (int)(end++ - dirname); else dirlen = (int)strlen(dirname); - if (dirlen == 0) - continue; /* ignore empty path elements */ - if (dirname[dirlen - 1] == OSI_PATH_SEPARATOR[0]) - dirlen--; + if (dirlen == 0) continue; /* ignore empty path elements */ + if (dirname[dirlen - 1] == OSI_PATH_SEPARATOR[0]) dirlen--; asprintf(&fullname, "%.*s" OSI_PATH_SEPARATOR "%s", dirlen, dirname, filename); - if (runScriptDebug) - printf("runScript: trying %s\n", fullname); + if (runScriptDebug) printf("runScript: trying %s\n", fullname); file = fopen(fullname, "r"); - if (!file && (errno & 0xffff) != ENOENT) - perror(fullname); + if (!file && (errno & 0xffff) != ENOENT) perror(fullname); free(fullname); - if (file) - break; + if (file) break; } } if (file == NULL) { @@ -133,12 +128,10 @@ int runScript(const char *filename, const char *args) { /* check if we have a line longer than the buffer size */ while (line_raw[(len = (long)strlen(line_raw)) - 1] != '\n' && !feof(file)) { - if (runScriptDebug) - printf("runScript partial line: \"%s\"\n", line_raw); + if (runScriptDebug) printf("runScript partial line: \"%s\"\n", line_raw); if ((line_raw = realloc(line_raw, line_raw_size *= 2)) == NULL) goto error; - if (fgets(line_raw + len, line_raw_size - len, file) == NULL) - break; + if (fgets(line_raw + len, line_raw_size - len, file) == NULL) break; } while (len > 0 && isspace((unsigned char)line_raw[len - 1])) line_raw[--len] = 0; /* get rid of '\n' and friends */ @@ -153,32 +146,26 @@ int runScript(const char *filename, const char *args) { printf("runScript: grow expand buffer: len=%ld size=%ld\n", len, line_exp_size); free(line_exp); - if ((line_exp = malloc(line_exp_size *= 2)) == NULL) - goto error; + if ((line_exp = malloc(line_exp_size *= 2)) == NULL) goto error; } if (runScriptDebug) printf("runScript expanded line (%ld chars): '%s'\n", len, line_exp); printf("%s\n", line_exp); p = line_exp; - while (isspace((unsigned char)*p)) - p++; - if (*p == 0 || *p == '#') - continue; + while (isspace((unsigned char)*p)) p++; + if (*p == 0 || *p == '#') continue; /* find local variable assignments */ if ((x = strpbrk(p, "=(, \t\n\r")) != NULL && *x == '=') { *x++ = 0; replaceExpressions(x, line_raw, line_raw_size); - if (runScriptDebug) - printf("runScript: assign %s=%s\n", p, line_raw); + if (runScriptDebug) printf("runScript: assign %s=%s\n", p, line_raw); macPutValue(mac, p, line_raw); continue; } - if (runScriptDebug) - printf("runScript: iocshCmd: '%s'\n", line_exp); + if (runScriptDebug) printf("runScript: iocshCmd: '%s'\n", line_exp); status = iocshCmd(line_exp); - if (status != 0) - break; + if (status != 0) break; } goto end; error: @@ -189,10 +176,8 @@ error: end: free(line_raw); free(line_exp); - if (mac) - macDeleteHandle(mac); - if (file) - fclose(file); + if (mac) macDeleteHandle(mac); + if (file) fclose(file); /* restore environment */ RESTOREENV(MODULE); @@ -227,11 +212,12 @@ void afterInitHook(initHookState state) { if (item->type == 1) { printf("%s\n", item->x.cmd); iocshCmd(item->x.cmd); - } else + } else { ((void (*)())item->x.a[0])(item->x.a[1], item->x.a[2], item->x.a[3], item->x.a[4], item->x.a[5], item->x.a[6], item->x.a[7], item->x.a[8], item->x.a[9], item->x.a[10], item->x.a[11]); + } } } @@ -266,8 +252,7 @@ static struct cmditem *newItem(char *cmd, int type) { int afterInit(char *cmd, char *a1, char *a2, char *a3, char *a4, char *a5, char *a6, char *a7, char *a8, char *a9, char *a10, char *a11) { struct cmditem *item = newItem(cmd, 0); - if (!item) - return -1; + if (!item) return -1; item->x.a[0] = cmd; item->x.a[1] = a1; @@ -308,8 +293,7 @@ static const iocshFuncDef afterInitDef = { static void afterInitFunc(const iocshArgBuf *args) { int i, n; struct cmditem *item = newItem(args[0].aval.av[1], 1); - if (!item) - return; + if (!item) return; n = sprintf(item->x.cmd, "%.255s", args[0].aval.av[1]); for (i = 2; i < args[0].aval.ac; i++) { diff --git a/require-ess/src/strdup.c b/require-ess/src/strdup.c index 598c316cc8f9bd8b4f788a165afca864fc48d8a6..53111b516ca65e99eb86e7ac88b5e08821cfb08c 100644 --- a/require-ess/src/strdup.c +++ b/require-ess/src/strdup.c @@ -1,10 +1,14 @@ +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#include "strdup.h" + #include <stdlib.h> #include <string.h> char *strdup(const char *s) { char *d = malloc(strlen(s) + 1); - if (d) - strcpy(d, s); + if (d) strcpy(d, s); return d; } @@ -13,8 +17,7 @@ char *strndup(const char *s, size_t n) { char *d; l = strlen(s); - if (n > l) - n = l; + if (n > l) n = l; d = malloc(n + 1); strncpy(d, s, l); d[n] = 0; diff --git a/require-ess/src/strdup.h b/require-ess/src/strdup.h index f20c9f9bc969727f68746d7bf3383b088e47f391..2f3ea7024ce9c11b588642ed7bf5b80227b1a1e5 100644 --- a/require-ess/src/strdup.h +++ b/require-ess/src/strdup.h @@ -1,11 +1,17 @@ -#ifndef strdup_h -#define strdup_h +/* Copyright (C) 2020 Dirk Zimoch */ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#pragma once + +#include <stddef.h> + #ifdef __cplusplus extern "C" { -#endif +#endif // __cplusplus + char *strdup(const char *s); char *strndup(const char *s, size_t n); + #ifdef __cplusplus } -#endif -#endif +#endif // __cplusplus diff --git a/require-ess/src/version.c b/require-ess/src/version.c index 9a66e9b7e07cb8a5efaa17bcdad6969adb0da33d..bd59fe80a56571ff0126a88543ca9b76cae46e75 100644 --- a/require-ess/src/version.c +++ b/require-ess/src/version.c @@ -1,4 +1,7 @@ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + #include "version.h" + #include <regex.h> #include <stdio.h> #include <stdlib.h> diff --git a/require-ess/src/version.h b/require-ess/src/version.h index 8f72da6c755ead92b92a29001e8da69c942c3b6c..a3cf1789c7bf3904a363ee808e473d5d45ee82ed 100644 --- a/require-ess/src/version.h +++ b/require-ess/src/version.h @@ -1,9 +1,13 @@ +/* Copyright (C) 2020-2022 European Spallation Source, ERIC */ + +#pragma once + typedef struct semver_t { char *version_str; int major; int minor; int patch; - int build; // can be negative; implies that build has not been specified + int build; // can be negative; implies that build has not been specified char *test_str; } semver_t; diff --git a/require.Makefile b/require.Makefile index ce1a85fbf2e0cb66ff6f9cdb118c78045ef768fc..3cf2f10ef35a57b69806b1dd9b9abb269afcf0ff 100644 --- a/require.Makefile +++ b/require.Makefile @@ -1,4 +1,3 @@ -# # Copyright (c) 2004 - 2017 Paul Scherrer Institute # Copyright (c) 2017 - Present European Spallation Source ERIC # @@ -15,13 +14,8 @@ # You should have received a copy of the GNU General Public License along with # this program. If not, see https://www.gnu.org/licenses/gpl-2.0.txt # -# PSI original author : Dirk Zimoch -# ESS original author : Jeong Han Lee -# ESS current author : Simon Rose -# email : simon.rose@ess.eu -# -# Date : Mon Dec 6 20:57:10 CET 2021 -# version : 3.4.1 +# Author: Dirk Zimoch (PSI) +# Maintainer: Simon Rose (ESS) <simon.rose@ess.eu> # This is the one time path in order to compile and install @@ -32,9 +26,9 @@ where_am_I := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) # It is easy to maintain RULES_E3 if we use the "repository" makefile # instead of the installed makefile. +# include $(where_am_I)/tools/driver.makefile - BUILDCLASSES += Linux APP := . @@ -48,67 +42,63 @@ SOURCES += $(APPSRC)/runScript.c DBDS += $(APPSRC)/runScript.dbd SOURCES += $(APPSRC)/expr.c - -## SOURCES += $(APPSRC)/dbLoadTemplate.y DBDS += $(APPSRC)/dbLoadTemplate.dbd # ESS doesn't have any T2_ppc604 and vxWorks target # Friday, May 11 22:05:07 CEST 2018, jhlee # -#SOURCES_T2 += strdup.c -#SOURCES_vxWorks += asprintf.c +# SOURCES_T2 += strdup.c +# SOURCES_vxWorks += asprintf.c # -#HEADERS += strdup.h -#HEADERS += asprintf.h +# HEADERS += strdup.h +# HEADERS += asprintf.h HEADERS += $(APPSRC)/require.h -#HEADERS += require_env.h +# HEADERS += require_env.h # We need to find the Linux link.h before the EPICS link.h +# USR_INCLUDES_Linux=-idirafter $(EPICS_BASE)/include +USR_CFLAGS += -std=c99 + # ESS require doesn't use T_A, because Linux should handle linux as "1" # instead of its name. ESS require can handle them within the EPICS # IOC shell internally. # -#USR_CFLAGS += -DT_A='"${T_A}"' +# USR_CFLAGS += -DT_A='"${T_A}"' # ESS doesn't support WIN32 # This should really go into some global WIN32 config file +# # USR_CFLAGS_WIN32 += /D_WIN32_WINNT=0x501 - TEMPLATES += $(APPDB)/moduleversion.template -#TEMPLATES += moduleversion.db +# TEMPLATES += moduleversion.db vpath dbLoadTemplate_lex.l ../$(APPSRC) dbLoadTemplate.c: dbLoadTemplate_lex.c ../$(APPSRC)/dbLoadTemplate.h -## moduleversion should convert to db instead of template -## So, ESS uses it internally independent upon any IOC -## varialbes - +# moduleversion should convert to db instead of template +# So, ESS uses it internally independent upon any IOC +# variables +# EPICS_BASE_HOST_BIN = $(EPICS_BASE)/bin/$(EPICS_HOST_ARCH) MSI = $(EPICS_BASE_HOST_BIN)/msi - USR_DBFLAGS += -I . -I .. USR_DBFLAGS += -I$(EPICS_BASE)/db - TMPS = $(wildcard $(APPDB)/*.template) +.PHONY: db db: $(TMPS) +.PHONY: $(TMPS) $(TMPS): @printf "Inflating database ... %44s >>> %40s \n" "$@" "$(basename $(@)).db" @rm -f $(basename $(@)).db.d $(basename $(@)).db @$(MSI) -D $(USR_DBFLAGS) -o $(basename $(@)).db $@ > $(basename $(@)).db.d @$(MSI) $(USR_DBFLAGS) -o $(basename $(@)).db $@ - - - - -.PHONY: db $(TMPS)